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/any23-core/src/main/java/org/deri/any23/extractor/rdf/TurtleExtractor.java b/any23-core/src/main/java/org/deri/any23/extractor/rdf/TurtleExtractor.java index aa547cc0..284793f6 100644 --- a/any23-core/src/main/java/org/deri/any23/extractor/rdf/TurtleExtractor.java +++ b/any23-core/src/main/java/org/deri/any23/extractor/rdf/TurtleExtractor.java @@ -1,110 +1,122 @@ /* * Copyright 2008-2010 Digital Enterprise Research Institute (DERI) * * 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.deri.any23.extractor.rdf; import org.deri.any23.extractor.ExtractionException; import org.deri.any23.extractor.ExtractionResult; import org.deri.any23.extractor.Extractor.ContentExtractor; import org.deri.any23.extractor.ExtractorDescription; import org.deri.any23.extractor.ExtractorFactory; import org.deri.any23.extractor.SimpleExtractorFactory; import org.openrdf.model.URI; import org.openrdf.rio.ParseErrorListener; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.turtle.TurtleParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * * Concrete implementation of {@link org.deri.any23.extractor.Extractor.ContentExtractor} able to perform the * extraction on <a href="http://www.w3.org/TeamSubmission/turtle/">Turtle</a> documents. * */ public class TurtleExtractor implements ContentExtractor { public static final ExtractorFactory<TurtleExtractor> factory = SimpleExtractorFactory.create( "rdf-turtle", null, Arrays.asList( "text/rdf+n3", "text/n3", "application/n3", "application/x-turtle", "application/turtle", "text/turtle" ), "example-turtle.ttl", TurtleExtractor.class ); private static final Logger logger = LoggerFactory.getLogger(TurtleExtractor.class); private boolean stopAtFirstError = true; - public void run(InputStream in, URI documentURI, ExtractionResult out) + public void run(InputStream in, URI documentURI, final ExtractionResult out) throws IOException, ExtractionException { try { TurtleParser parser = new TurtleParser(); parser.setDatatypeHandling( RDFParser.DatatypeHandling.VERIFY ); parser.setStopAtFirstError(stopAtFirstError); parser.setParseErrorListener( new ParseErrorListener() { public void warning(String msg, int lineNo, int colNo) { - logger.warn( report(msg, lineNo, colNo) ); + try { + out.notifyError(ExtractionResult.ErrorLevel.WARN, msg, lineNo, colNo ); + } catch (Exception e) { + notifyExceptionInNotification(e); + } } public void error(String msg, int lineNo, int colNo) { - logger.error( report(msg, lineNo, colNo) ); + try { + out.notifyError(ExtractionResult.ErrorLevel.ERROR, msg, lineNo, colNo ); + } catch (Exception e) { + notifyExceptionInNotification(e); + } } public void fatalError(String msg, int lineNo, int colNo) { - logger.error( report("FATAL: " + msg, lineNo, colNo) ); + try { + out.notifyError(ExtractionResult.ErrorLevel.FATAL, msg, lineNo, colNo ); + } catch (Exception e) { + notifyExceptionInNotification(e); + } } - private String report(String msg, int lineNo, int colNo) { - return String.format("'%s [%d, %d]'", msg, lineNo, colNo); + private void notifyExceptionInNotification(Exception e) { + logger.error("An exception occurred while notifying an error.", e); } }); parser.setRDFHandler( new RDFHandlerAdapter(out) ); parser.parse( in, documentURI.stringValue() ); } catch (RDFHandlerException ex) { throw new RuntimeException("Should not happen, RDFHandlerAdapter does not throw this", ex); } catch (RDFParseException ex) { throw new ExtractionException(ex); } } public ExtractorDescription getDescription() { return factory; } public void setStopAtFirstError(boolean f) { stopAtFirstError = f; } public boolean getStopAtFirstError() { return stopAtFirstError; } }
false
true
public void run(InputStream in, URI documentURI, ExtractionResult out) throws IOException, ExtractionException { try { TurtleParser parser = new TurtleParser(); parser.setDatatypeHandling( RDFParser.DatatypeHandling.VERIFY ); parser.setStopAtFirstError(stopAtFirstError); parser.setParseErrorListener( new ParseErrorListener() { public void warning(String msg, int lineNo, int colNo) { logger.warn( report(msg, lineNo, colNo) ); } public void error(String msg, int lineNo, int colNo) { logger.error( report(msg, lineNo, colNo) ); } public void fatalError(String msg, int lineNo, int colNo) { logger.error( report("FATAL: " + msg, lineNo, colNo) ); } private String report(String msg, int lineNo, int colNo) { return String.format("'%s [%d, %d]'", msg, lineNo, colNo); } }); parser.setRDFHandler( new RDFHandlerAdapter(out) ); parser.parse( in, documentURI.stringValue() ); } catch (RDFHandlerException ex) { throw new RuntimeException("Should not happen, RDFHandlerAdapter does not throw this", ex); } catch (RDFParseException ex) { throw new ExtractionException(ex); } }
public void run(InputStream in, URI documentURI, final ExtractionResult out) throws IOException, ExtractionException { try { TurtleParser parser = new TurtleParser(); parser.setDatatypeHandling( RDFParser.DatatypeHandling.VERIFY ); parser.setStopAtFirstError(stopAtFirstError); parser.setParseErrorListener( new ParseErrorListener() { public void warning(String msg, int lineNo, int colNo) { try { out.notifyError(ExtractionResult.ErrorLevel.WARN, msg, lineNo, colNo ); } catch (Exception e) { notifyExceptionInNotification(e); } } public void error(String msg, int lineNo, int colNo) { try { out.notifyError(ExtractionResult.ErrorLevel.ERROR, msg, lineNo, colNo ); } catch (Exception e) { notifyExceptionInNotification(e); } } public void fatalError(String msg, int lineNo, int colNo) { try { out.notifyError(ExtractionResult.ErrorLevel.FATAL, msg, lineNo, colNo ); } catch (Exception e) { notifyExceptionInNotification(e); } } private void notifyExceptionInNotification(Exception e) { logger.error("An exception occurred while notifying an error.", e); } }); parser.setRDFHandler( new RDFHandlerAdapter(out) ); parser.parse( in, documentURI.stringValue() ); } catch (RDFHandlerException ex) { throw new RuntimeException("Should not happen, RDFHandlerAdapter does not throw this", ex); } catch (RDFParseException ex) { throw new ExtractionException(ex); } }
diff --git a/Sendgrid.java b/Sendgrid.java index 7cec0be..f307624 100644 --- a/Sendgrid.java +++ b/Sendgrid.java @@ -1,674 +1,674 @@ package googleSendgridJava; import java.net.HttpURLConnection; import java.util.*; import java.io.IOException; import java.util.Iterator; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import com.google.appengine.labs.repackaged.org.json.JSONException; import com.google.appengine.labs.repackaged.org.json.JSONObject; import com.google.appengine.labs.repackaged.org.json.JSONArray; public class Sendgrid { private String from, reply_to, subject, text, html; protected Boolean use_headers = true; public String message = ""; private ArrayList<String> to_list = new ArrayList<String>(); private ArrayList<String> to_name_list = new ArrayList<String>(); private ArrayList<String> bcc_list = new ArrayList<String>(); private JSONObject header_list = new JSONObject(); protected String domain = "https://sendgrid.com/", endpoint= "api/mail.send.json", username, password; public Sendgrid(String username, String password) { this.username = username; this.password = password; } /** * getTos - Return the list of recipients * * @return List of recipients */ public ArrayList<String> getTos() { return this.to_list; } /** * setTo - Initialize a single email for the recipient 'to' field * Destroy previous recipient 'to' data. * * @param email A list of email addresses * @return The SendGrid object. */ public Sendgrid setTo(String email) { this.to_list = new ArrayList<String>(); this.to_list.add(email); this.to_name_list.add(""); return this; } /** * addTo - Append an email address to the existing list of addresses * Preserve previous recipient 'to' data. * * @param email Recipient email address * @param name Recipient name * @return The SendGrid object. */ public Sendgrid addTo(String email, String name) { if (name.length() > 0){ this.addToName(name); } else { this.addToName(""); } this.to_list.add(email); return this; } /** * addTo - Make the second parameter("name") of "addTo" method optional * * @param email A single email address * @return The SendGrid object. */ public Sendgrid addTo(String email) { return addTo(email, ""); } /** * getTos - Return the list of names for recipients * * @return List of names */ public ArrayList<String> getToNames() { return this.to_name_list; } /** * addToName - Append an recipient name to the existing list of names * * @param email Recipient email address * @param name Recipient name * @return The SendGrid object. */ public Sendgrid addToName(String name) { this.to_name_list.add(name); return this; } /** * getFrom - Get the from email address * * @return The from email address */ public String getFrom() { return this.from; } /** * setFrom - Set the from email * * @param email An email address * @return The SendGrid object. */ public Sendgrid setFrom(String email) { this.from = email; return this; } /** * getReplyTo - Get reply to address * * @return the reply to address */ public String getReplyTo() { return this.reply_to; } /** * setReplyTo - set the reply-to address * * @param email the email to reply to * @return the SendGrid object. */ public Sendgrid setReplyTo(String email) { this.reply_to = email; return this; } /** * getBccs - return the list of Blind Carbon Copy recipients * * @return ArrayList - the list of Blind Carbon Copy recipients */ public ArrayList<String> getBccs() { return this.bcc_list; } /** * setBcc - Initialize the list of Carbon Copy recipients * destroy previous recipient Blind Carbon Copy data * * @param email an email address * @return the SendGrid object. */ public Sendgrid setBcc(String email) { this.bcc_list = new ArrayList<String>(); this.bcc_list.add(email); return this; } /** * addBcc - Append an email address to the list of Blind Carbon Copy * recipients * * @param email - an email address */ public Sendgrid addBcc(String email) { if (this.bcc_list.size() > 0) { this.bcc_list.add(email); } else { this.setBcc(email); } return this; } /** * getSubject - Get the email subject * * @return The email subject */ public String getSubject() { return this.subject; } /** * setSubject - Set the email subject * * @param subject The email subject * @return The SendGrid object */ public Sendgrid setSubject(String subject) { this.subject = subject; return this; } /** * getText - Get the plain text part of the email * * @return the plain text part of the email */ public String getText() { return this.text; } /** * setText - Set the plain text part of the email * * @param text The plain text of the email * @return The SendGrid object. */ public Sendgrid setText(String text) { this.text = text; return this; } /** * getHtml - Get the HTML part of the email * * @return The HTML part of the email. */ public String getHtml() { return this.html; } /** * setHTML - Set the HTML part of the email * * @param html The HTML part of the email * @return The SendGrid object. */ public Sendgrid setHtml(String html) { this.html = html; return this; } /** * setCategories - Set the list of category headers * destroys previous category header data * * @param category_list the list of category values * @return the SendGrid object. * @throws JSONException */ public Sendgrid setCategories(String[] category_list) throws JSONException { JSONArray categories_json = new JSONArray(category_list); this.header_list.put("category", categories_json); return this; } /** * setCategory - Clears the category list and adds the given category * * @param category the new category to append * @return the SendGrid object. * @throws JSONException */ public Sendgrid setCategory(String category) throws JSONException { JSONArray json_category = new JSONArray(new String[]{category}); this.header_list.put("category", json_category); return this; } /** * addCategory - Append a category to the list of categories * * @param category the new category to append * @return the SendGrid object. * @throws JSONException */ public Sendgrid addCategory(String category) throws JSONException { if (true == this.header_list.has("category")) { ((JSONArray) this.header_list.get("category")).put(category); } else { this.setCategory(category); } return this; } /** * setSubstitutions - Substitute a value for list of values, where each value corresponds * to the list emails in a one to one relationship. (IE, value[0] = email[0], * value[1] = email[1]) * * @param key_value_pairs key/value pairs where the value is an array of values * @return the SendGrid object. */ public Sendgrid setSubstitutions(JSONObject key_value_pairs) { try { this.header_list.put("sub", key_value_pairs); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } /** * addSubstitution - Substitute a value for list of values, where each value corresponds * to the list emails in a one to one relationship. (IE, value[0] = email[0], * value[1] = email[1]) * * @param from_key the value to be replaced * @param to_values an array of values to replace the from_value * @return the SendGrid object. * @throws JSONException * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ public Sendgrid addSubstitution(String from_value, String[] to_values) throws JSONException { if (false == this.header_list.has("sub")) { this.header_list.put("sub", new JSONObject()); } JSONArray json_values = new JSONArray(to_values); ((JSONObject) this.header_list.get("sub")).put(from_value, json_values); return this; } /** * setSection - Set a list of section values * * @param key_value_pairs key/value pairs * @return the SendGrid object. * @throws JSONException */ public Sendgrid setSections(JSONObject key_value_pairs) throws JSONException { this.header_list.put("section", key_value_pairs); return this; } /** * addSection - append a section value to the list of section values * * @param from_value the value to be replaced * @param to_value the value to replace * @return the SendGrid object. * @throws JSONException */ public Sendgrid addSection(String from_value, String to_value) throws JSONException { if (false == this.header_list.has("section")) { this.header_list.put("section", new JSONObject() ); } ((JSONObject) this.header_list.get("section")).put(from_value, to_value); return this; } /** * setUniqueArguments - Set a list of unique arguments, to be used for tracking purposes * * @param key_value_pairs - list of unique arguments */ public Sendgrid setUniqueArguments(JSONObject key_value_pairs) { try { this.header_list.put("unique_args", key_value_pairs); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } /** * addUniqueArgument - Set a key/value pair of unique arguments, to be used for tracking purposes * * @param key the key * @param value the value */ public Sendgrid addUniqueArgument(String key, String value) { if (false == this.header_list.has("unique_args")) { try { this.header_list.put("unique_args", new JSONObject()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { ((JSONObject) this.header_list.get("unique_args")).put(key, value); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } /** * setFilterSettings - Set filter/app settings * * @param filter_settings - JSONObject of fiter settings */ public Sendgrid setFilterSettings(JSONObject filter_settings) { try { this.header_list.put("filters", filter_settings); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } /** * addFilterSetting - Append a filter setting to the list of filter settings * * @param filter_name filter name * @param parameter_name parameter name * @param parameter_value setting value * @throws JSONException */ public Sendgrid addFilterSetting(String filter_name, String parameter_name, String parameter_value) throws JSONException { if (false == this.header_list.has("filters")) { this.header_list.put("filters", new JSONObject()); } if (false == ((JSONObject) this.header_list.get("filters")).has(filter_name)) { ((JSONObject) this.header_list.get("filters")).put(filter_name, new JSONObject()); } if (false == ((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).has("settings")) { ((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).put("settings", new JSONObject()); } ((JSONObject) ((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).get("settings")) .put(parameter_name, parameter_value); return this; } /** * getHeaders - return the list of headers * * @return JSONObject with headers */ public JSONObject getHeaders() { return this.header_list; } /** * setHeaders - Sets the list headers * destroys previous header data * * @param key_value_pairs the list of header data * @return the SendGrid object. */ public Sendgrid setHeaders(JSONObject key_value_pairs) { this.header_list = key_value_pairs; return this; } /** * _arrayToUrlPart - Converts an ArrayList to a url friendly string * * @param array the array to convert * @param token the name of parameter * @return a url part that can be concatenated to a url request */ protected String _arrayToUrlPart(ArrayList<String> array, String token) { String string = ""; for(int i = 0;i < array.size();i++) { try { string += "&" + token + "[]=" + URLEncoder.encode(array.get(i), "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return string; } /** * _prepMessageData - Takes the mail message and returns a url friendly querystring * * @return the data query string to be posted * @throws JSONException */ protected Map<String, String> _prepMessageData() throws JSONException { Map<String,String> params = new HashMap<String, String>(); params.put("api_user", this.username); params.put("api_key", this.password); params.put("subject", this.getSubject()); params.put("html", this.getHtml()); params.put("text",this.getText()); params.put("from", this.getFrom()); if (this.getReplyTo() != null) { params.put("replyto", this.getReplyTo()); } if (this._useHeaders() == true) { JSONObject headers = this.getHeaders(); params.put("to", this.getFrom()); headers.put("to", this.getTos().toString()); this.setHeaders(headers); params.put("x-smtpapi", this.getHeaders().toString()); } else { params.put("to", this.getTos().toString()); } if (this.getToNames().size() > 0) { params.put("toname", this.getToNames().toString()); } return params; } /** * send - Send an email * * @throws JSONException */ public void send() throws JSONException { Map<String,String> data = new HashMap<String, String>(); data = this._prepMessageData(); StringBuffer requestParams = new StringBuffer(); Iterator<String> paramIterator = data.keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = data.get(key); if (key == "to" && this.getTos().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&"); } else { if (key == "toname" && this.getToNames().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname")+"&"); } else { - try { + try { requestParams.append(URLEncoder.encode(key, "UTF-8")); } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; - } + } requestParams.append("="); - try { + try { requestParams.append(URLEncoder.encode(value, "UTF-8")); - } catch (UnsupportedEncodingException e) { + } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; - } + } requestParams.append("&"); } } } String request = this.domain + this.endpoint; if (this.getBccs().size() > 0){ request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1); } try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestParams.toString()); // Get the response writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line, response = ""; while ((line = reader.readLine()) != null) { // Process line... response += line; } reader.close(); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK message = "success"; } else { // Server returned HTTP error code. JSONObject apiResponse = new JSONObject(response); JSONArray errorsObj = (JSONArray) apiResponse.get("errors"); for (int i = 0; i < errorsObj.length(); i++) { if (i != 0) { message += ", "; } message += errorsObj.get(i); } } } catch (MalformedURLException e) { message = "Malformed URL Exception"; } catch (IOException e) { message = "IO Exception"; } } /** * useHeaders - Checks to see whether or not we can or should you headers. In most cases, * we prefer to send our recipients through the headers, but in some cases, * we actually don't want to. However, there are certain circumstances in * which we have to. */ private Boolean _useHeaders() { if ((this._preferNotToUseHeaders() == true) && (this._isHeadersRequired() == false)) { return false; } else { return true; } } /** * _preferNotToUseHeaders - There are certain cases in which headers are not a preferred choice * to send email, as it limits some basic email functionality. Here, we * check for any of those rules, and add them in to decide whether or * not to use headers * * @return if true we don't */ private Boolean _preferNotToUseHeaders() { if (this.getBccs().size() == 0) { return true; } if (this.use_headers != null && this.use_headers == false) { return true; } return false; } /** * isHeaderRequired - determines whether or not we need to force recipients through the smtpapi headers * * @return if true headers are required */ private Boolean _isHeadersRequired() { if (this.use_headers == true) { return true; } return false; } }
false
true
public void send() throws JSONException { Map<String,String> data = new HashMap<String, String>(); data = this._prepMessageData(); StringBuffer requestParams = new StringBuffer(); Iterator<String> paramIterator = data.keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = data.get(key); if (key == "to" && this.getTos().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&"); } else { if (key == "toname" && this.getToNames().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname")+"&"); } else { try { requestParams.append(URLEncoder.encode(key, "UTF-8")); } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; } requestParams.append("="); try { requestParams.append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; } requestParams.append("&"); } } } String request = this.domain + this.endpoint; if (this.getBccs().size() > 0){ request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1); } try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestParams.toString()); // Get the response writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line, response = ""; while ((line = reader.readLine()) != null) { // Process line... response += line; } reader.close(); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK message = "success"; } else { // Server returned HTTP error code. JSONObject apiResponse = new JSONObject(response); JSONArray errorsObj = (JSONArray) apiResponse.get("errors"); for (int i = 0; i < errorsObj.length(); i++) { if (i != 0) { message += ", "; } message += errorsObj.get(i); } } } catch (MalformedURLException e) { message = "Malformed URL Exception"; } catch (IOException e) { message = "IO Exception"; } }
public void send() throws JSONException { Map<String,String> data = new HashMap<String, String>(); data = this._prepMessageData(); StringBuffer requestParams = new StringBuffer(); Iterator<String> paramIterator = data.keySet().iterator(); while (paramIterator.hasNext()) { String key = paramIterator.next(); String value = data.get(key); if (key == "to" && this.getTos().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&"); } else { if (key == "toname" && this.getToNames().size() > 0) { requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname")+"&"); } else { try { requestParams.append(URLEncoder.encode(key, "UTF-8")); } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; } requestParams.append("="); try { requestParams.append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { message = "Unsupported Encoding Exception"; } requestParams.append("&"); } } } String request = this.domain + this.endpoint; if (this.getBccs().size() > 0){ request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1); } try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestParams.toString()); // Get the response writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line, response = ""; while ((line = reader.readLine()) != null) { // Process line... response += line; } reader.close(); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // OK message = "success"; } else { // Server returned HTTP error code. JSONObject apiResponse = new JSONObject(response); JSONArray errorsObj = (JSONArray) apiResponse.get("errors"); for (int i = 0; i < errorsObj.length(); i++) { if (i != 0) { message += ", "; } message += errorsObj.get(i); } } } catch (MalformedURLException e) { message = "Malformed URL Exception"; } catch (IOException e) { message = "IO Exception"; } }
diff --git a/src/TreeWalker.java b/src/TreeWalker.java index 8228c09..3b8886f 100644 --- a/src/TreeWalker.java +++ b/src/TreeWalker.java @@ -1,451 +1,451 @@ import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; import java.io.*; import org.antlr.runtime.*; import java.util.*; public class TreeWalker { public void walkTree(CommonTree t, String filename) { try { BufferedWriter out = new BufferedWriter(new FileWriter(filename + ".rb")); out.write("require \"set\"\n"); if(!(t.getType() == 0)){ walk((CommonTree) t, out); } //traverse all the child nodes of the root if root was empty else{ for ( int i = 0; i < t.getChildCount(); i++ ) { walk(((CommonTree)t.getChild(i)), out); } } out.close(); } catch (IOException e) {} } public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ - // out.write(t.getText() + ".main("); - out.write(t.getText()); + out.write(t.getText() + ".main"); + // out.write(t.getText()); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} } }
true
true
public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ // out.write(t.getText() + ".main("); out.write(t.getText()); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} }
public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ out.write(t.getText() + ".main"); // out.write(t.getText()); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} }
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java index ee9a9ca..a11118b 100644 --- a/src/simpleserver/stream/StreamTunnel.java +++ b/src/simpleserver/stream/StreamTunnel.java @@ -1,1527 +1,1525 @@ /* * Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS) * * 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 simpleserver.stream; import static simpleserver.lang.Translations.t; import static simpleserver.util.Util.print; import static simpleserver.util.Util.println; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import simpleserver.Authenticator.AuthRequest; import simpleserver.Color; import simpleserver.Coordinate; import simpleserver.Coordinate.Dimension; import simpleserver.Main; import simpleserver.Player; import simpleserver.Server; import simpleserver.command.PlayerListCommand; import simpleserver.config.data.Chests.Chest; import simpleserver.config.xml.Config.BlockPermission; public class StreamTunnel { private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING"); private static final int IDLE_TIME = 30000; private static final int BUFFER_SIZE = 1024; private static final byte BLOCK_DESTROYED_STATUS = 2; private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$"); private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-z]"); private static final Pattern JOIN_PATTERN = Pattern.compile("\u00a7.((\\d|\\w|\\u00a7)*) (joined|left) the game."); private static final String CONSOLE_CHAT_PATTERN = "\\[Server:.*\\]"; private static final int MESSAGE_SIZE = 60; private static final int MAXIMUM_MESSAGE_SIZE = 119; private final boolean isServerTunnel; private final String streamType; private final Player player; private final Server server; private final byte[] buffer; private final Tunneler tunneler; private DataInput in; private DataOutput out; private InputStream inputStream; private OutputStream outputStream; private StreamDumper inputDumper; private StreamDumper outputDumper; private boolean inGame = false; private volatile long lastRead; private volatile boolean run = true; private Byte lastPacket; private char commandPrefix; public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel, Player player) { this.isServerTunnel = isServerTunnel; if (isServerTunnel) { streamType = "ServerStream"; } else { streamType = "PlayerStream"; } this.player = player; server = player.getServer(); commandPrefix = server.options.getBoolean("useSlashes") ? '/' : '!'; inputStream = in; outputStream = out; DataInputStream dIn = new DataInputStream(in); DataOutputStream dOut = new DataOutputStream(out); if (EXPENSIVE_DEBUG_LOGGING) { try { OutputStream dump = new FileOutputStream(streamType + "Input.debug"); InputStreamDumper dumper = new InputStreamDumper(dIn, dump); inputDumper = dumper; this.in = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open input debug dump!"); throw new RuntimeException(e); } try { OutputStream dump = new FileOutputStream(streamType + "Output.debug"); OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump); outputDumper = dumper; this.out = dumper; } catch (FileNotFoundException e) { System.out.println("Unable to open output debug dump!"); throw new RuntimeException(e); } } else { this.in = dIn; this.out = dOut; } buffer = new byte[BUFFER_SIZE]; tunneler = new Tunneler(); tunneler.start(); lastRead = System.currentTimeMillis(); } public void stop() { run = false; } public boolean isAlive() { return tunneler.isAlive(); } public boolean isActive() { return System.currentTimeMillis() - lastRead < IDLE_TIME || player.isRobot(); } private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readFloat())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1b: // Steer Vehicle write(packetId); write(in.readFloat()); write(in.readFloat()); write(in.readBoolean()); write(in.readBoolean()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x2c: // Entity Properties write(packetId); write(in.readInt()); write(in.readInt()); write(readUTF16()); write(in.readDouble()); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); short chunkCount = in.readShort(); int dataLength = in.readInt(); write(chunkCount); write(dataLength); write(in.readBoolean()); copyNBytes(chunkCount * 12 + dataLength); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x3f: // particle write(packetId); write(readUTF16()); // name of particle write(in.readFloat()); // x write(in.readFloat()); // y write(in.readFloat()); // z write(in.readFloat()); // offset x write(in.readFloat()); // offset y write(in.readFloat()); // offset z write(in.readFloat()); // particle speed write(in.readInt()); // num of particles break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String title = readUTF16(); byte number = in.readByte(); boolean provided = in.readBoolean(); - int unknown = in.readInt(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); title = t("Open Chest"); } else { title = server.data.chests.chestName(player.openedChest()); } } else { title = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); title = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(title); write(number); write(provided); - write(unknown); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); copyNBytes(length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); write(in.readInt()); write(in.readInt()); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readFloat()); write(in.readFloat()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xce: // scoreboard objectives write(packetId); write(readUTF16()); write(readUTF16()); write(in.readByte()); break; case (byte) 0xcf: // update score write(packetId); write(readUTF16()); byte updateRemove = in.readByte(); write(updateRemove); if (updateRemove != 1) { write(readUTF16()); write(in.readInt()); } break; case (byte) 0xd0: // display scoreboard write(packetId); write(in.readByte()); write(readUTF16()); break; case (byte) 0xd1: // teams write(packetId); write(readUTF16()); byte mode = in.readByte(); short playerCount = -1; write(mode); if (mode == 0 || mode == 2) { write(readUTF16()); // team display name write(readUTF16()); // team prefix write(readUTF16()); // team suffix write(in.readByte()); // friendly fire } // only ran if 0,3,4 if (mode == 0 || mode == 3 || mode == 4) { playerCount = in.readShort(); write(playerCount); if (playerCount != -1) { for (int i = 0; i < playerCount; i++) { write(readUTF16()); } } } break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; } private void copyItem() throws IOException { if (write(in.readShort()) > 0) { write(in.readByte()); write(in.readShort()); short length; if ((length = write(in.readShort())) > 0) { copyNBytes(length); } } } private void skipItem() throws IOException { if (in.readShort() > 0) { in.readByte(); in.readShort(); short length; if ((length = in.readShort()) > 0) { skipNBytes(length); } } } private long copyVLC() throws IOException { long value = 0; int shift = 0; while (true) { int i = write(in.readByte()); value |= (i & 0x7F) << shift; if ((i & 0x80) == 0) { break; } shift += 7; } return value; } private String readUTF16() throws IOException { short length = in.readShort(); StringBuilder string = new StringBuilder(); for (int i = 0; i < length; i++) { string.append(in.readChar()); } return string.toString(); } private void lockChest(Coordinate coordinate) { Chest adjacentChest = server.data.chests.adjacentChest(coordinate); if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) { if (adjacentChest != null && !adjacentChest.isOpen()) { server.data.chests.giveLock(adjacentChest.owner, coordinate, adjacentChest.name); } else { if (adjacentChest != null) { adjacentChest.lock(player); adjacentChest.name = player.nextChestName(); } server.data.chests.giveLock(player, coordinate, player.nextChestName()); } player.setAttemptedAction(null); player.addTMessage(Color.GRAY, "This chest is now locked."); } else if (!server.data.chests.isChest(coordinate)) { server.data.chests.addOpenChest(coordinate); } server.data.save(); } private void copyPlayerLocation() throws IOException { double x = in.readDouble(); double y = in.readDouble(); double stance = in.readDouble(); double z = in.readDouble(); player.position.updatePosition(x, y, z, stance); if (server.options.getBoolean("enableEvents")) { player.checkLocationEvents(); } write(x); write(y); write(stance); write(z); } private void copyPlayerLook() throws IOException { float yaw = in.readFloat(); float pitch = in.readFloat(); player.position.updateLook(yaw, pitch); write(yaw); write(pitch); } private void copyUnknownBlob() throws IOException { byte item = in.readByte(); write(item); while (item != 0x7f) { int type = (item & 0xE0) >> 5; switch (type) { case 0: write(in.readByte()); break; case 1: write(in.readShort()); break; case 2: write(in.readInt()); break; case 3: write(in.readFloat()); break; case 4: write(readUTF16()); break; case 5: copyItem(); break; case 6: write(in.readInt()); write(in.readInt()); write(in.readInt()); } item = in.readByte(); write(item); } } private void skipUnknownBlob() throws IOException { byte item = in.readByte(); while (item != 0x7f) { int type = (item & 0xE0) >> 5; switch (type) { case 0: in.readByte(); break; case 1: in.readShort(); break; case 2: in.readInt(); break; case 3: in.readFloat(); break; case 4: readUTF16(); break; case 5: skipItem(); break; case 6: in.readInt(); in.readInt(); in.readInt(); } item = in.readByte(); } } private byte write(byte b) throws IOException { out.writeByte(b); return b; } private byte[] write(byte[] b) throws IOException { out.write(b); return b; } private short write(short s) throws IOException { out.writeShort(s); return s; } private int write(int i) throws IOException { out.writeInt(i); return i; } private long write(long l) throws IOException { out.writeLong(l); return l; } private float write(float f) throws IOException { out.writeFloat(f); return f; } private double write(double d) throws IOException { out.writeDouble(d); return d; } private String write(String s) throws IOException { write((short) s.length()); out.writeChars(s); return s; } private boolean write(boolean b) throws IOException { out.writeBoolean(b); return b; } private void skipNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); } private void copyNBytes(int bytes) throws IOException { int overflow = bytes / buffer.length; for (int c = 0; c < overflow; ++c) { in.readFully(buffer, 0, buffer.length); out.write(buffer, 0, buffer.length); } in.readFully(buffer, 0, bytes % buffer.length); out.write(buffer, 0, bytes % buffer.length); } private void kick(String reason) throws IOException { write((byte) 0xff); write(reason); packetFinished(); } private String getLastColorCode(String message) { String colorCode = ""; int lastIndex = message.lastIndexOf('\u00a7'); if (lastIndex != -1 && lastIndex + 1 < message.length()) { colorCode = message.substring(lastIndex, lastIndex + 2); } return colorCode; } private void sendMessage(String message) throws IOException { if (message.length() > 0) { if (message.length() > MESSAGE_SIZE) { int end = MESSAGE_SIZE - 1; while (end > 0 && message.charAt(end) != ' ') { end--; } if (end == 0) { end = MESSAGE_SIZE; } else { end++; } if (end > 0 && message.charAt(end) == '\u00a7') { end--; } String firstPart = message.substring(0, end); sendMessagePacket(firstPart); sendMessage(getLastColorCode(firstPart) + message.substring(end)); } else { int end = message.length(); if (message.charAt(end - 1) == '\u00a7') { end--; } sendMessagePacket(message.substring(0, end)); } } } private void sendMessagePacket(String message) throws IOException { if (message.length() > MESSAGE_SIZE) { println("Invalid message size: " + message); return; } if (message.length() > 0) { write((byte) 0x03); write(message); packetFinished(); } } private void packetFinished() throws IOException { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.packetFinished(); outputDumper.packetFinished(); } } private void flushAll() throws IOException { try { ((OutputStream) out).flush(); } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.flush(); } } } private final class Tunneler extends Thread { @Override public void run() { try { while (run) { lastRead = System.currentTimeMillis(); try { handlePacket(); if (isServerTunnel) { while (player.hasMessages()) { sendMessage(player.getMessage()); } } else { while (player.hasForwardMessages()) { sendMessage(player.getForwardMessage()); } } flushAll(); } catch (IOException e) { if (run && !player.isRobot()) { println(e); print(streamType + " error handling traffic for " + player.getIPAddress()); if (lastPacket != null) { System.out.print(" (" + Integer.toHexString(lastPacket) + ")"); } System.out.println(); } break; } } try { if (player.isKicked()) { kick(player.getKickMsg()); } flushAll(); } catch (IOException e) { } } finally { if (EXPENSIVE_DEBUG_LOGGING) { inputDumper.cleanup(); outputDumper.cleanup(); } } } } }
false
true
private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readFloat())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1b: // Steer Vehicle write(packetId); write(in.readFloat()); write(in.readFloat()); write(in.readBoolean()); write(in.readBoolean()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x2c: // Entity Properties write(packetId); write(in.readInt()); write(in.readInt()); write(readUTF16()); write(in.readDouble()); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); short chunkCount = in.readShort(); int dataLength = in.readInt(); write(chunkCount); write(dataLength); write(in.readBoolean()); copyNBytes(chunkCount * 12 + dataLength); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x3f: // particle write(packetId); write(readUTF16()); // name of particle write(in.readFloat()); // x write(in.readFloat()); // y write(in.readFloat()); // z write(in.readFloat()); // offset x write(in.readFloat()); // offset y write(in.readFloat()); // offset z write(in.readFloat()); // particle speed write(in.readInt()); // num of particles break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String title = readUTF16(); byte number = in.readByte(); boolean provided = in.readBoolean(); int unknown = in.readInt(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); title = t("Open Chest"); } else { title = server.data.chests.chestName(player.openedChest()); } } else { title = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); title = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(title); write(number); write(provided); write(unknown); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); copyNBytes(length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); write(in.readInt()); write(in.readInt()); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readFloat()); write(in.readFloat()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xce: // scoreboard objectives write(packetId); write(readUTF16()); write(readUTF16()); write(in.readByte()); break; case (byte) 0xcf: // update score write(packetId); write(readUTF16()); byte updateRemove = in.readByte(); write(updateRemove); if (updateRemove != 1) { write(readUTF16()); write(in.readInt()); } break; case (byte) 0xd0: // display scoreboard write(packetId); write(in.readByte()); write(readUTF16()); break; case (byte) 0xd1: // teams write(packetId); write(readUTF16()); byte mode = in.readByte(); short playerCount = -1; write(mode); if (mode == 0 || mode == 2) { write(readUTF16()); // team display name write(readUTF16()); // team prefix write(readUTF16()); // team suffix write(in.readByte()); // friendly fire } // only ran if 0,3,4 if (mode == 0 || mode == 3 || mode == 4) { playerCount = in.readShort(); write(playerCount); if (playerCount != -1) { for (int i = 0; i < playerCount; i++) { write(readUTF16()); } } } break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; }
private void handlePacket() throws IOException { Byte packetId = in.readByte(); // System.out.println((isServerTunnel ? "server " : "client ") + // String.format("%02x", packetId)); int x; byte y; int z; byte dimension; Coordinate coordinate; switch (packetId) { case 0x00: // Keep Alive write(packetId); write(in.readInt()); // random number that is returned from server break; case 0x01: // Login Request/Response write(packetId); if (!isServerTunnel) { write(in.readInt()); write(readUTF16()); copyNBytes(5); break; } player.setEntityId(write(in.readInt())); write(readUTF16()); write(in.readByte()); dimension = in.readByte(); if (isServerTunnel) { player.setDimension(Dimension.get(dimension)); } write(dimension); write(in.readByte()); write(in.readByte()); if (isServerTunnel) { in.readByte(); write((byte) server.config.properties.getInt("maxPlayers")); } else { write(in.readByte()); } break; case 0x02: // Handshake byte version = in.readByte(); String name = readUTF16(); boolean nameSet = false; if (name.contains(";")) { name = name.substring(0, name.indexOf(";")); } if (name.equals("Player") || !server.authenticator.isMinecraftUp) { AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress()); if (req != null) { name = req.playerName; nameSet = server.authenticator.completeLogin(req, player); } if (req == null || !nameSet) { if (!name.equals("Player")) { player.addTMessage(Color.RED, "Login verification failed."); player.addTMessage(Color.RED, "You were logged in as guest."); } name = server.authenticator.getFreeGuestName(); player.setGuest(true); nameSet = player.setName(name); } } else { nameSet = player.setName(name); if (nameSet) { player.updateRealName(name); } } if (player.isGuest() && !server.authenticator.allowGuestJoin()) { player.kick(t("Failed to login: User not authenticated")); nameSet = false; } tunneler.setName(streamType + "-" + player.getName()); write(packetId); write(version); write(player.getName()); write(readUTF16()); write(in.readInt()); break; case 0x03: // Chat Message String message = readUTF16(); Matcher joinMatcher = JOIN_PATTERN.matcher(message); if (isServerTunnel && joinMatcher.find()) { if (server.bots.ninja(joinMatcher.group(1))) { break; } if (message.contains("join")) { player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1)); } else { player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1)); } break; } if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) { if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) { break; } Matcher colorMatcher = COLOR_PATTERN.matcher(message); String cleanMessage = colorMatcher.replaceAll(""); Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage); if (messageMatcher.find()) { } else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) { break; } if (server.config.properties.getBoolean("msgWrap")) { sendMessage(message); } else { if (message.length() > MAXIMUM_MESSAGE_SIZE) { message = message.substring(0, MAXIMUM_MESSAGE_SIZE); } write(packetId); write(message); } } else if (!isServerTunnel) { if (player.isMuted() && !message.startsWith("/") && !message.startsWith("!")) { player.addTMessage(Color.RED, "You are muted! You may not send messages to all players."); break; } if (message.charAt(0) == commandPrefix) { message = player.parseCommand(message, false); if (message == null) { break; } write(packetId); write(message); return; } player.sendMessage(message); } break; case 0x04: // Time Update write(packetId); write(in.readLong()); long time = in.readLong(); server.setTime(time); write(time); break; case 0x05: // Player Inventory write(packetId); write(in.readInt()); write(in.readShort()); copyItem(); break; case 0x06: // Spawn Position write(packetId); copyNBytes(12); if (server.options.getBoolean("enableEvents")) { server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null); } break; case 0x07: // Use Entity int user = in.readInt(); int target = in.readInt(); Player targetPlayer = server.playerList.findPlayer(target); if (targetPlayer != null) { if (targetPlayer.godModeEnabled()) { in.readBoolean(); break; } } write(packetId); write(user); write(target); copyNBytes(1); break; case 0x08: // Update Health write(packetId); player.updateHealth(write(in.readFloat())); player.getHealth(); write(in.readShort()); write(in.readFloat()); break; case 0x09: // Respawn write(packetId); if (!isServerTunnel) { break; } player.setDimension(Dimension.get(write(in.readInt()))); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(readUTF16()); // Added in 1.1 (level type) if (server.options.getBoolean("enableEvents") && isServerTunnel) { server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null); } break; case 0x0a: // Player write(packetId); copyNBytes(1); if (!inGame && !isServerTunnel) { player.sendMOTD(); if (server.config.properties.getBoolean("showListOnConnect")) { // display player list if enabled in config player.execute(PlayerListCommand.class); } inGame = true; } break; case 0x0b: // Player Position write(packetId); copyPlayerLocation(); copyNBytes(1); break; case 0x0c: // Player Look write(packetId); copyPlayerLook(); copyNBytes(1); break; case 0x0d: // Player Position & Look write(packetId); copyPlayerLocation(); copyPlayerLook(); copyNBytes(1); break; case 0x0e: // Player Digging if (!isServerTunnel) { byte status = in.readByte(); x = in.readInt(); y = in.readByte(); z = in.readInt(); byte face = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (!player.getGroup().ignoreAreas) { BlockPermission perm = server.config.blockPermission(player, coordinate); if (!perm.use && status == 0) { player.addTMessage(Color.RED, "You can not use this block here!"); break; } if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) { player.addTMessage(Color.RED, "You can not destroy this block!"); break; } } boolean locked = server.data.chests.isLocked(coordinate); if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) { if (locked && status == BLOCK_DESTROYED_STATUS) { server.data.chests.releaseLock(coordinate); server.data.save(); } write(packetId); write(status); write(x); write(y); write(z); write(face); if (player.instantDestroyEnabled()) { packetFinished(); write(packetId); write(BLOCK_DESTROYED_STATUS); write(x); write(y); write(z); write(face); } if (status == BLOCK_DESTROYED_STATUS) { player.destroyedBlock(); } } } else { write(packetId); copyNBytes(11); } break; case 0x0f: // Player Block Placement x = in.readInt(); y = in.readByte(); z = in.readInt(); coordinate = new Coordinate(x, y, z, player); final byte direction = in.readByte(); final short dropItem = in.readShort(); byte itemCount = 0; short uses = 0; byte[] data = null; if (dropItem != -1) { itemCount = in.readByte(); uses = in.readShort(); short dataLength = in.readShort(); if (dataLength != -1) { data = new byte[dataLength]; in.readFully(data); } } byte blockX = in.readByte(); byte blockY = in.readByte(); byte blockZ = in.readByte(); boolean writePacket = true; boolean drop = false; BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem); if (server.options.getBoolean("enableEvents")) { player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0))); } if (isServerTunnel || server.data.chests.isChest(coordinate)) { // continue } else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) { if (!perm.use) { player.addTMessage(Color.RED, "You can not use this block here!"); } else { player.addTMessage(Color.RED, "You can not place this block here!"); } writePacket = false; drop = true; } else if (dropItem == 54) { int xPosition = x; byte yPosition = y; int zPosition = z; switch (direction) { case 0: --yPosition; break; case 1: ++yPosition; break; case 2: --zPosition; break; case 3: ++zPosition; break; case 4: --xPosition; break; case 5: ++xPosition; break; } Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player); Chest adjacentChest = server.data.chests.adjacentChest(targetBlock); if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) { player.addTMessage(Color.RED, "The adjacent chest is locked!"); writePacket = false; drop = true; } else { player.placingChest(targetBlock); } } if (writePacket) { write(packetId); write(x); write(y); write(z); write(direction); write(dropItem); if (dropItem != -1) { write(itemCount); write(uses); if (data != null) { write((short) data.length); out.write(data); } else { write((short) -1); } if (dropItem <= 94 && direction >= 0) { player.placedBlock(); } } write(blockX); write(blockY); write(blockZ); player.openingChest(coordinate); } else if (drop) { // Drop the item in hand. This keeps the client state in-sync with the // server. This generally prevents empty-hand clicks by the client // from placing blocks the server thinks the client has in hand. write((byte) 0x0e); write((byte) 0x04); write(x); write(y); write(z); write(direction); } break; case 0x10: // Holding Change write(packetId); copyNBytes(2); break; case 0x11: // Use Bed write(packetId); copyNBytes(14); break; case 0x12: // Animation write(packetId); copyNBytes(5); break; case 0x13: // Entity Action write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); break; case 0x14: // Named Entity Spawn int eid = in.readInt(); name = readUTF16(); if (!server.bots.ninja(name)) { write(packetId); write(eid); write(name); copyNBytes(16); copyUnknownBlob(); } else { skipNBytes(16); skipUnknownBlob(); } break; case 0x16: // Collect Item write(packetId); copyNBytes(8); break; case 0x17: // Add Object/Vehicle write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); int flag = in.readInt(); write(flag); if (flag > 0) { write(in.readShort()); write(in.readShort()); write(in.readShort()); } break; case 0x18: // Mob Spawn write(packetId); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readShort()); write(in.readShort()); write(in.readShort()); copyUnknownBlob(); break; case 0x19: // Entity: Painting write(packetId); write(in.readInt()); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); break; case 0x1a: // Experience Orb write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readShort()); break; case 0x1b: // Steer Vehicle write(packetId); write(in.readFloat()); write(in.readFloat()); write(in.readBoolean()); write(in.readBoolean()); break; case 0x1c: // Entity Velocity write(packetId); copyNBytes(10); break; case 0x1d: // Destroy Entity write(packetId); byte destoryCount = write(in.readByte()); if (destoryCount > 0) { copyNBytes(destoryCount * 4); } break; case 0x1e: // Entity write(packetId); copyNBytes(4); break; case 0x1f: // Entity Relative Move write(packetId); copyNBytes(7); break; case 0x20: // Entity Look write(packetId); copyNBytes(6); break; case 0x21: // Entity Look and Relative Move write(packetId); copyNBytes(9); break; case 0x22: // Entity Teleport write(packetId); copyNBytes(18); break; case 0x23: // Entitiy Look write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x26: // Entity Status write(packetId); copyNBytes(5); break; case 0x27: // Attach Entity write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); break; case 0x28: // Entity Metadata write(packetId); write(in.readInt()); copyUnknownBlob(); break; case 0x29: // Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); write(in.readByte()); write(in.readShort()); break; case 0x2a: // Remove Entity Effect write(packetId); write(in.readInt()); write(in.readByte()); break; case 0x2b: // Experience write(packetId); player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort())); break; case 0x2c: // Entity Properties write(packetId); write(in.readInt()); write(in.readInt()); write(readUTF16()); write(in.readDouble()); break; case 0x33: // Map Chunk write(packetId); write(in.readInt()); write(in.readInt()); write(in.readBoolean()); write(in.readShort()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x34: // Multi Block Change write(packetId); write(in.readInt()); write(in.readInt()); write(in.readShort()); copyNBytes(write(in.readInt())); break; case 0x35: // Block Change write(packetId); x = in.readInt(); y = in.readByte(); z = in.readInt(); short blockType = in.readShort(); byte metadata = in.readByte(); coordinate = new Coordinate(x, y, z, player); if (blockType == 54 && player.placedChest(coordinate)) { lockChest(coordinate); player.placingChest(null); } write(x); write(y); write(z); write(blockType); write(metadata); break; case 0x36: // Block Action write(packetId); copyNBytes(14); break; case 0x37: // Mining progress write(packetId); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x38: // Chunk Bulk write(packetId); short chunkCount = in.readShort(); int dataLength = in.readInt(); write(chunkCount); write(dataLength); write(in.readBoolean()); copyNBytes(chunkCount * 12 + dataLength); break; case 0x3c: // Explosion write(packetId); copyNBytes(28); int recordCount = in.readInt(); write(recordCount); copyNBytes(recordCount * 3); write(in.readFloat()); write(in.readFloat()); write(in.readFloat()); break; case 0x3d: // Sound/Particle Effect write(packetId); write(in.readInt()); write(in.readInt()); write(in.readByte()); write(in.readInt()); write(in.readInt()); write(in.readByte()); break; case 0x3e: // Named Sound/Particle Effect write(packetId); write(readUTF16()); write(in.readInt()); write(in.readInt()); write(in.readInt()); write(in.readFloat()); write(in.readByte()); break; case 0x3f: // particle write(packetId); write(readUTF16()); // name of particle write(in.readFloat()); // x write(in.readFloat()); // y write(in.readFloat()); // z write(in.readFloat()); // offset x write(in.readFloat()); // offset y write(in.readFloat()); // offset z write(in.readFloat()); // particle speed write(in.readInt()); // num of particles break; case 0x46: // New/Invalid State write(packetId); write(in.readByte()); write(in.readByte()); break; case 0x47: // Thunderbolt write(packetId); copyNBytes(17); break; case 0x64: // Open Window boolean allow = true; byte id = in.readByte(); byte invtype = in.readByte(); String title = readUTF16(); byte number = in.readByte(); boolean provided = in.readBoolean(); if (invtype == 0) { Chest adjacent = server.data.chests.adjacentChest(player.openedChest()); if (!server.data.chests.isChest(player.openedChest())) { if (adjacent == null) { server.data.chests.addOpenChest(player.openedChest()); } else { server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name); } server.data.save(); } if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) { player.addTMessage(Color.RED, "You can't use chests here"); allow = false; } else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) { if (server.data.chests.isLocked(player.openedChest())) { if (player.isAttemptingUnlock()) { server.data.chests.unlock(player.openedChest()); server.data.save(); player.setAttemptedAction(null); player.addTMessage(Color.RED, "This chest is no longer locked!"); title = t("Open Chest"); } else { title = server.data.chests.chestName(player.openedChest()); } } else { title = t("Open Chest"); if (player.isAttemptLock()) { lockChest(player.openedChest()); title = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName(); } } } else { player.addTMessage(Color.RED, "This chest is locked!"); allow = false; } } if (!allow) { write((byte) 0x65); write(id); } else { write(packetId); write(id); write(invtype); write(title); write(number); write(provided); } break; case 0x65: // Close Window write(packetId); write(in.readByte()); break; case 0x66: // Window Click write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); write(in.readShort()); write(in.readByte()); copyItem(); break; case 0x67: // Set Slot write(packetId); write(in.readByte()); write(in.readShort()); copyItem(); break; case 0x68: // Window Items write(packetId); write(in.readByte()); short count = write(in.readShort()); for (int c = 0; c < count; ++c) { copyItem(); } break; case 0x69: // Update Window Property write(packetId); write(in.readByte()); write(in.readShort()); write(in.readShort()); break; case 0x6a: // Transaction write(packetId); write(in.readByte()); write(in.readShort()); write(in.readByte()); break; case 0x6b: // Creative Inventory Action write(packetId); write(in.readShort()); copyItem(); break; case 0x6c: // Enchant Item write(packetId); write(in.readByte()); write(in.readByte()); break; case (byte) 0x82: // Update Sign write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(readUTF16()); write(readUTF16()); write(readUTF16()); write(readUTF16()); break; case (byte) 0x83: // Item Data write(packetId); write(in.readShort()); write(in.readShort()); short length = in.readShort(); write(length); copyNBytes(length); break; case (byte) 0x84: // added in 12w06a write(packetId); write(in.readInt()); write(in.readShort()); write(in.readInt()); write(in.readByte()); short nbtLength = write(in.readShort()); if (nbtLength > 0) { copyNBytes(nbtLength); } break; case (byte) 0xc3: // BukkitContrib write(packetId); write(in.readInt()); copyNBytes(write(in.readInt())); break; case (byte) 0xc8: // Increment Statistic write(packetId); write(in.readInt()); write(in.readInt()); break; case (byte) 0xc9: // Player List Item write(packetId); write(readUTF16()); write(in.readByte()); write(in.readShort()); break; case (byte) 0xca: // Player Abilities write(packetId); write(in.readByte()); write(in.readFloat()); write(in.readFloat()); break; case (byte) 0xcb: // Tab-Completion write(packetId); write(readUTF16()); break; case (byte) 0xcc: // Locale and View Distance write(packetId); write(readUTF16()); write(in.readByte()); write(in.readByte()); write(in.readByte()); write(in.readBoolean()); break; case (byte) 0xcd: // Login & Respawn write(packetId); write(in.readByte()); break; case (byte) 0xce: // scoreboard objectives write(packetId); write(readUTF16()); write(readUTF16()); write(in.readByte()); break; case (byte) 0xcf: // update score write(packetId); write(readUTF16()); byte updateRemove = in.readByte(); write(updateRemove); if (updateRemove != 1) { write(readUTF16()); write(in.readInt()); } break; case (byte) 0xd0: // display scoreboard write(packetId); write(in.readByte()); write(readUTF16()); break; case (byte) 0xd1: // teams write(packetId); write(readUTF16()); byte mode = in.readByte(); short playerCount = -1; write(mode); if (mode == 0 || mode == 2) { write(readUTF16()); // team display name write(readUTF16()); // team prefix write(readUTF16()); // team suffix write(in.readByte()); // friendly fire } // only ran if 0,3,4 if (mode == 0 || mode == 3 || mode == 4) { playerCount = in.readShort(); write(playerCount); if (playerCount != -1) { for (int i = 0; i < playerCount; i++) { write(readUTF16()); } } } break; case (byte) 0xd3: // Red Power (mod by Eloraam) write(packetId); copyNBytes(1); copyVLC(); copyVLC(); copyVLC(); copyNBytes((int) copyVLC()); break; case (byte) 0xe6: // ModLoaderMP by SDK write(packetId); write(in.readInt()); // mod write(in.readInt()); // packet id copyNBytes(write(in.readInt()) * 4); // ints copyNBytes(write(in.readInt()) * 4); // floats copyNBytes(write(in.readInt()) * 8); // doubles int sizeString = write(in.readInt()); // strings for (int i = 0; i < sizeString; i++) { copyNBytes(write(in.readInt())); } break; case (byte) 0xfa: // Plugin Message write(packetId); write(readUTF16()); copyNBytes(write(in.readShort())); break; case (byte) 0xfc: // Encryption Key Response byte[] sharedKey = new byte[in.readShort()]; in.readFully(sharedKey); byte[] challengeTokenResponse = new byte[in.readShort()]; in.readFully(challengeTokenResponse); if (!isServerTunnel) { if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) { player.kick("Invalid client response"); break; } player.clientEncryption.setEncryptedSharedKey(sharedKey); sharedKey = player.serverEncryption.getEncryptedSharedKey(); } if (!isServerTunnel && server.authenticator.useCustAuth(player) && !server.authenticator.onlineAuthenticate(player)) { player.kick(t("%s Failed to login: User not premium", "[CustAuth]")); break; } write(packetId); write((short) sharedKey.length); write(sharedKey); challengeTokenResponse = player.serverEncryption.encryptChallengeToken(); write((short) challengeTokenResponse.length); write(challengeTokenResponse); if (isServerTunnel) { in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream))); } else { in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream))); out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream))); } break; case (byte) 0xfd: // Encryption Key Request (server -> client) tunneler.setName(streamType + "-" + player.getName()); write(packetId); String serverId = readUTF16(); if (!server.authenticator.useCustAuth(player)) { serverId = "-"; } else { serverId = player.getConnectionHash(); } write(serverId); byte[] keyBytes = new byte[in.readShort()]; in.readFully(keyBytes); byte[] challengeToken = new byte[in.readShort()]; in.readFully(challengeToken); player.serverEncryption.setPublicKey(keyBytes); byte[] key = player.clientEncryption.getPublicKey(); write((short) key.length); write(key); write((short) challengeToken.length); write(challengeToken); player.serverEncryption.setChallengeToken(challengeToken); player.clientEncryption.setChallengeToken(challengeToken); break; case (byte) 0xfe: // Server List Ping write(packetId); write(in.readByte()); break; case (byte) 0xff: // Disconnect/Kick write(packetId); String reason = readUTF16(); if (reason.startsWith("\u00a71")) { reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s", Main.protocolVersion, Main.minecraftVersion, server.config.properties.get("serverDescription"), server.playerList.size(), server.config.properties.getInt("maxPlayers")); } write(reason); if (reason.startsWith("Took too long")) { server.addRobot(player); } player.close(); break; default: if (EXPENSIVE_DEBUG_LOGGING) { while (true) { skipNBytes(1); flushAll(); } } else { if (lastPacket != null) { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName() + " (after 0x" + Integer.toHexString(lastPacket)); } else { throw new IOException("Unable to parse unknown " + streamType + " packet 0x" + Integer.toHexString(packetId) + " for player " + player.getName()); } } } packetFinished(); lastPacket = (packetId == 0x00) ? lastPacket : packetId; }
diff --git a/src/ojc/ahni/util/ParameterTuner.java b/src/ojc/ahni/util/ParameterTuner.java index c963ddc7..7e9b8f9a 100644 --- a/src/ojc/ahni/util/ParameterTuner.java +++ b/src/ojc/ahni/util/ParameterTuner.java @@ -1,215 +1,215 @@ package ojc.ahni.util; import java.lang.management.ManagementFactory; import java.util.Arrays; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import ojc.ahni.hyperneat.Properties; import ojc.ahni.hyperneat.Run; /** * <p> * Attempts to fine tune one or more parameters for an experiment described by a Properties file. Parameters are * adjusted iteratively, with each parameter adjusted in turn each iteration. The underlying assumption is that the * fitness landscape represented by the parameters to adjust is unimodal. It is currently assumed that all parameters * are represented by floating point numbers. * </p> * <p> * For each parameter for each iteration the fitness value is calculated by adjusting the parameter up or down by a * multiplicative factor and running the experiment. If either of these adjustments results in a higher fitness then the * adjusted value will be adopted (at least until the next iteration when a new value may be adopted). * </p> * <p> * The default initial multiplicative factor is 2 (thus the initial downward adjustment of a parameter p is p/2 and the * upward adjustment is p*2). A different initial multiplicative factor may be specified in the Properties file. For each * iteration in which no parameter adjustments are adopted the multiplicative factor is halved. * </p> * <p> * If fitness was not increased by adjusting a parameter in the previous iteration then it will not be adjusted in the * current iteration to save time. If adjusting the parameter in the next iteration still doesn't yield an increase in * fitness then the parameter will be ignored for the next two iterations, and so on. * </p> * <p> * The following properties may be specified in the Properties file: * <dl> * <dt>parametertuner.totune</dt> * <dd>A comma separated list of property keys corresponding to the parameters to tune</dd> * <dt>parametertuner.initialvalues</dt> * <dd>A comma separated list of the initial values to use for the parameters, in the same order as that given in * <em>parametertuner.totune</em>.</dd> * <dt>parametertuner.minvalues</dt> * <dd>A comma separated list of the minimum values to use for the parameters, in the same order as that given in * <em>parametertuner.totune</em>. Optional.</dd> * <dt>parametertuner.maxvalues</dt> * <dd>A comma separated list of the maximum values to use for the parameters, in the same order as that given in * <em>parametertuner.totune</em>. Optional.</dd> * <dt>parametertuner.maxiterations</dt> * <dd>The maximum number of iterations to perform. Default is 100.</dd> * <dt>parametertuner.initialvalueadjustfactor</dt> * <dd>The initial multiplicative factor</dd> * <dt>parametertuner.numruns</dt> * <dd>The number of runs to perform when determining fitness for a set of parameter values. Default is 50, which is probably about the safest minimum.</dd> * </dl> * </p> */ public class ParameterTuner { public static double significanceFactor = 1.01; public static void main(String[] args) { if (args.length == 0) { usage(); System.exit(-1); } try { Properties props = new Properties(args[0]); String[] propsToTune = props.getProperty("parametertuner.totune").replaceAll("\\s", "").split(","); int propCount = propsToTune.length; double[] currentBestVals = props.getDoubleArrayProperty("parametertuner.initialvalues"); double[] minValues = props.getDoubleArrayProperty("parametertuner.minvalues", ArrayUtil.newArray(propCount, -Double.MAX_VALUE)); double[] maxValues = props.getDoubleArrayProperty("parametertuner.maxvalues", ArrayUtil.newArray(propCount, Double.MAX_VALUE)); int maxIterations = props.getIntProperty("parametertuner.maxiterations", 100); double valAdjustFactor = props.getDoubleProperty("parametertuner.initialvalueadjustfactor", 2); int numRuns = props.getIntProperty("parametertuner.numruns", 30); props.setProperty("num.runs", "1"); // We'll calculate our own average so we can report progress as we go. props.setProperty("log4j.rootLogger", "OFF"); // Suppress logging. Logger.getRootLogger().setLevel(Level.OFF); props.remove("random.seed"); // Make sure the runs are randomised. int[] adjustIneffectiveCount = new int[propCount]; int[] adjustCountDown = new int[propCount]; double adjustDownFitness = 0, adjustUpFitness = 0; double adjustDownVal = 0, adjustUpVal = 0; System.out.println("Determining initial fitness."); double bestFitness = doRuns(props, args, numRuns); System.out.println("Initial fitness: " + bestFitness); for (int i = 0; i < maxIterations; i++) { System.out.println("Start iteration " + i); boolean adjustedAnyParams = false; boolean adjustCountDownZeroExists = false; // Indicates if any parameters are due to be adjusted this iteration. // Adjust each parameter in turn. for (int p = 0; p < propCount; p++) { String propKey = propsToTune[p]; // Sample fitness either side of current parameter value. if (adjustCountDown[p] == 0) { System.out.println("\tTuning " + propKey + " (current value is " + currentBestVals[p] + ")."); double newVal = currentBestVals[p]; double newBestFitness = bestFitness; adjustDownVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] / valAdjustFactor)); if (adjustDownVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustDownVal); adjustDownFitness = doRuns(props, args, numRuns); boolean better = adjustDownFitness > bestFitness * significanceFactor; System.out.println("\t\tValue " + adjustDownVal + " gave fitness of " + adjustDownFitness + " (" + (!better ? "not significantly " : "") + "greater than current best)."); if (better) { newBestFitness = adjustDownFitness; newVal = adjustDownVal; } } adjustUpVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] * valAdjustFactor)); if (adjustUpVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustUpVal); adjustUpFitness = doRuns(props, args, numRuns); boolean better = adjustUpFitness > bestFitness * significanceFactor && adjustUpFitness > adjustDownFitness; System.out.println("\t\tValue " + adjustUpVal + " gave fitness of " + adjustUpFitness + " (" + (!better ? "not significantly " : "") + "greater than current best and/or downward adjustment)."); if (better) { newBestFitness = adjustUpFitness; newVal = adjustUpVal; } } // If the fitness was increased by an adjustment. if (currentBestVals[p] != newVal) { adjustIneffectiveCount[p] = 0; currentBestVals[p] = newVal; adjustedAnyParams = true; bestFitness = newBestFitness; } else { // If the fitness did not improve by adjusting this parameter then hold off adjusting it // for a few iterations (dependent on how many times adjusting it has been ineffective in // previous generations). adjustIneffectiveCount[p]++; adjustCountDown[p] = adjustIneffectiveCount[p]; } // Set parameter to current best value. props.setProperty(propKey, "" + currentBestVals[p]); } else { adjustCountDown[p]--; System.out.println("\tSkipping " + propKey + " for " + adjustCountDown[p] + " more iterations."); } adjustCountDownZeroExists |= adjustCountDown[p] == 0; } System.out.println("Finished iteration. Current best values are:\n" + Arrays.toString(currentBestVals)); if (!adjustedAnyParams) { - valAdjustFactor /= 2; + valAdjustFactor = (valAdjustFactor-1)/2+1; System.out.println("Value adjust factor is now " + valAdjustFactor); } // Make sure that at least one parameter is due to be adjusted. while (!adjustCountDownZeroExists) { for (int p = 0; p < propCount; p++) { if (adjustCountDown[p] > 0) adjustCountDown[p]--; adjustCountDownZeroExists |= adjustCountDown[p] == 0; } } } System.out.println("Finished adjusting parameters."); System.out.println("Final best parameter values were:"); for (int p = 0; p < propCount; p++) { System.out.println(propsToTune[p] + " = " + currentBestVals[p]); } } catch (Exception e) { e.printStackTrace(); } } private static double doRuns(Properties props, String[] args, int numRuns) throws Exception { double sumFitness = 0; System.out.print("\t\tStarting " + numRuns + " runs: "); for (int r = 0; r < numRuns; r++) { System.out.print(r + " "); Run runner = new Run(props); runner.noOutput = true; runner.run(); double[] fitness = runner.fitness[0]; double fs = 0; // Get average of last 10 fitness evaluations, in case fitness function is very stochastic. // (Generally speaking, the fitness function should not be very stochastic, but in some cases can be). for (int g = fitness.length-10; g < fitness.length; g++) { fs += fitness[g]; } sumFitness += fs / 10; } float memHeap = (float) (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() / 1048576d); float memNonHeap = (float) (ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed() / 1048576d); System.out.println(" Finished runs, memory usage (heap / non-heap / total MB): " + memHeap + " / " + memNonHeap + " / " + (memHeap + memNonHeap)); return sumFitness / numRuns; } /** * command line usage */ private static void usage() { System.out.println("Usage:\n" + "Parameter tuning can be run with:\n <cmd> <properties-file>"); } }
true
true
public static void main(String[] args) { if (args.length == 0) { usage(); System.exit(-1); } try { Properties props = new Properties(args[0]); String[] propsToTune = props.getProperty("parametertuner.totune").replaceAll("\\s", "").split(","); int propCount = propsToTune.length; double[] currentBestVals = props.getDoubleArrayProperty("parametertuner.initialvalues"); double[] minValues = props.getDoubleArrayProperty("parametertuner.minvalues", ArrayUtil.newArray(propCount, -Double.MAX_VALUE)); double[] maxValues = props.getDoubleArrayProperty("parametertuner.maxvalues", ArrayUtil.newArray(propCount, Double.MAX_VALUE)); int maxIterations = props.getIntProperty("parametertuner.maxiterations", 100); double valAdjustFactor = props.getDoubleProperty("parametertuner.initialvalueadjustfactor", 2); int numRuns = props.getIntProperty("parametertuner.numruns", 30); props.setProperty("num.runs", "1"); // We'll calculate our own average so we can report progress as we go. props.setProperty("log4j.rootLogger", "OFF"); // Suppress logging. Logger.getRootLogger().setLevel(Level.OFF); props.remove("random.seed"); // Make sure the runs are randomised. int[] adjustIneffectiveCount = new int[propCount]; int[] adjustCountDown = new int[propCount]; double adjustDownFitness = 0, adjustUpFitness = 0; double adjustDownVal = 0, adjustUpVal = 0; System.out.println("Determining initial fitness."); double bestFitness = doRuns(props, args, numRuns); System.out.println("Initial fitness: " + bestFitness); for (int i = 0; i < maxIterations; i++) { System.out.println("Start iteration " + i); boolean adjustedAnyParams = false; boolean adjustCountDownZeroExists = false; // Indicates if any parameters are due to be adjusted this iteration. // Adjust each parameter in turn. for (int p = 0; p < propCount; p++) { String propKey = propsToTune[p]; // Sample fitness either side of current parameter value. if (adjustCountDown[p] == 0) { System.out.println("\tTuning " + propKey + " (current value is " + currentBestVals[p] + ")."); double newVal = currentBestVals[p]; double newBestFitness = bestFitness; adjustDownVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] / valAdjustFactor)); if (adjustDownVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustDownVal); adjustDownFitness = doRuns(props, args, numRuns); boolean better = adjustDownFitness > bestFitness * significanceFactor; System.out.println("\t\tValue " + adjustDownVal + " gave fitness of " + adjustDownFitness + " (" + (!better ? "not significantly " : "") + "greater than current best)."); if (better) { newBestFitness = adjustDownFitness; newVal = adjustDownVal; } } adjustUpVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] * valAdjustFactor)); if (adjustUpVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustUpVal); adjustUpFitness = doRuns(props, args, numRuns); boolean better = adjustUpFitness > bestFitness * significanceFactor && adjustUpFitness > adjustDownFitness; System.out.println("\t\tValue " + adjustUpVal + " gave fitness of " + adjustUpFitness + " (" + (!better ? "not significantly " : "") + "greater than current best and/or downward adjustment)."); if (better) { newBestFitness = adjustUpFitness; newVal = adjustUpVal; } } // If the fitness was increased by an adjustment. if (currentBestVals[p] != newVal) { adjustIneffectiveCount[p] = 0; currentBestVals[p] = newVal; adjustedAnyParams = true; bestFitness = newBestFitness; } else { // If the fitness did not improve by adjusting this parameter then hold off adjusting it // for a few iterations (dependent on how many times adjusting it has been ineffective in // previous generations). adjustIneffectiveCount[p]++; adjustCountDown[p] = adjustIneffectiveCount[p]; } // Set parameter to current best value. props.setProperty(propKey, "" + currentBestVals[p]); } else { adjustCountDown[p]--; System.out.println("\tSkipping " + propKey + " for " + adjustCountDown[p] + " more iterations."); } adjustCountDownZeroExists |= adjustCountDown[p] == 0; } System.out.println("Finished iteration. Current best values are:\n" + Arrays.toString(currentBestVals)); if (!adjustedAnyParams) { valAdjustFactor /= 2; System.out.println("Value adjust factor is now " + valAdjustFactor); } // Make sure that at least one parameter is due to be adjusted. while (!adjustCountDownZeroExists) { for (int p = 0; p < propCount; p++) { if (adjustCountDown[p] > 0) adjustCountDown[p]--; adjustCountDownZeroExists |= adjustCountDown[p] == 0; } } } System.out.println("Finished adjusting parameters."); System.out.println("Final best parameter values were:"); for (int p = 0; p < propCount; p++) { System.out.println(propsToTune[p] + " = " + currentBestVals[p]); } } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { if (args.length == 0) { usage(); System.exit(-1); } try { Properties props = new Properties(args[0]); String[] propsToTune = props.getProperty("parametertuner.totune").replaceAll("\\s", "").split(","); int propCount = propsToTune.length; double[] currentBestVals = props.getDoubleArrayProperty("parametertuner.initialvalues"); double[] minValues = props.getDoubleArrayProperty("parametertuner.minvalues", ArrayUtil.newArray(propCount, -Double.MAX_VALUE)); double[] maxValues = props.getDoubleArrayProperty("parametertuner.maxvalues", ArrayUtil.newArray(propCount, Double.MAX_VALUE)); int maxIterations = props.getIntProperty("parametertuner.maxiterations", 100); double valAdjustFactor = props.getDoubleProperty("parametertuner.initialvalueadjustfactor", 2); int numRuns = props.getIntProperty("parametertuner.numruns", 30); props.setProperty("num.runs", "1"); // We'll calculate our own average so we can report progress as we go. props.setProperty("log4j.rootLogger", "OFF"); // Suppress logging. Logger.getRootLogger().setLevel(Level.OFF); props.remove("random.seed"); // Make sure the runs are randomised. int[] adjustIneffectiveCount = new int[propCount]; int[] adjustCountDown = new int[propCount]; double adjustDownFitness = 0, adjustUpFitness = 0; double adjustDownVal = 0, adjustUpVal = 0; System.out.println("Determining initial fitness."); double bestFitness = doRuns(props, args, numRuns); System.out.println("Initial fitness: " + bestFitness); for (int i = 0; i < maxIterations; i++) { System.out.println("Start iteration " + i); boolean adjustedAnyParams = false; boolean adjustCountDownZeroExists = false; // Indicates if any parameters are due to be adjusted this iteration. // Adjust each parameter in turn. for (int p = 0; p < propCount; p++) { String propKey = propsToTune[p]; // Sample fitness either side of current parameter value. if (adjustCountDown[p] == 0) { System.out.println("\tTuning " + propKey + " (current value is " + currentBestVals[p] + ")."); double newVal = currentBestVals[p]; double newBestFitness = bestFitness; adjustDownVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] / valAdjustFactor)); if (adjustDownVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustDownVal); adjustDownFitness = doRuns(props, args, numRuns); boolean better = adjustDownFitness > bestFitness * significanceFactor; System.out.println("\t\tValue " + adjustDownVal + " gave fitness of " + adjustDownFitness + " (" + (!better ? "not significantly " : "") + "greater than current best)."); if (better) { newBestFitness = adjustDownFitness; newVal = adjustDownVal; } } adjustUpVal = Math.min(maxValues[p], Math.max(minValues[p], currentBestVals[p] * valAdjustFactor)); if (adjustUpVal != currentBestVals[p]) { props.setProperty(propKey, "" + adjustUpVal); adjustUpFitness = doRuns(props, args, numRuns); boolean better = adjustUpFitness > bestFitness * significanceFactor && adjustUpFitness > adjustDownFitness; System.out.println("\t\tValue " + adjustUpVal + " gave fitness of " + adjustUpFitness + " (" + (!better ? "not significantly " : "") + "greater than current best and/or downward adjustment)."); if (better) { newBestFitness = adjustUpFitness; newVal = adjustUpVal; } } // If the fitness was increased by an adjustment. if (currentBestVals[p] != newVal) { adjustIneffectiveCount[p] = 0; currentBestVals[p] = newVal; adjustedAnyParams = true; bestFitness = newBestFitness; } else { // If the fitness did not improve by adjusting this parameter then hold off adjusting it // for a few iterations (dependent on how many times adjusting it has been ineffective in // previous generations). adjustIneffectiveCount[p]++; adjustCountDown[p] = adjustIneffectiveCount[p]; } // Set parameter to current best value. props.setProperty(propKey, "" + currentBestVals[p]); } else { adjustCountDown[p]--; System.out.println("\tSkipping " + propKey + " for " + adjustCountDown[p] + " more iterations."); } adjustCountDownZeroExists |= adjustCountDown[p] == 0; } System.out.println("Finished iteration. Current best values are:\n" + Arrays.toString(currentBestVals)); if (!adjustedAnyParams) { valAdjustFactor = (valAdjustFactor-1)/2+1; System.out.println("Value adjust factor is now " + valAdjustFactor); } // Make sure that at least one parameter is due to be adjusted. while (!adjustCountDownZeroExists) { for (int p = 0; p < propCount; p++) { if (adjustCountDown[p] > 0) adjustCountDown[p]--; adjustCountDownZeroExists |= adjustCountDown[p] == 0; } } } System.out.println("Finished adjusting parameters."); System.out.println("Final best parameter values were:"); for (int p = 0; p < propCount; p++) { System.out.println(propsToTune[p] + " = " + currentBestVals[p]); } } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/org/fao/geonet/kernel/schema/SchemaLoader.java b/src/org/fao/geonet/kernel/schema/SchemaLoader.java index 67754f1148..b5ef3bdf25 100644 --- a/src/org/fao/geonet/kernel/schema/SchemaLoader.java +++ b/src/org/fao/geonet/kernel/schema/SchemaLoader.java @@ -1,1108 +1,1118 @@ //============================================================================== //=== //=== SchemaLoader //=== //============================================================================== //=== Copyright (C) 2001-2007 Food and Agriculture Organization of the //=== United Nations (FAO-UN), United Nations World Food Programme (WFP) //=== and United Nations Environment Programme (UNEP) //=== //=== 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 St, Fifth Floor, Boston, MA 02110-1301, USA //=== //=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2, //=== Rome - Italy. email: [email protected] //============================================================================== package org.fao.geonet.kernel.schema; import java.util.*; import org.jdom.*; import java.io.File; import jeeves.utils.Xml; import org.fao.geonet.constants.Edit; //============================================================================== public class SchemaLoader { private Element elRoot; private HashMap hmElements = new HashMap(); private HashMap hmTypes = new HashMap(); private HashMap hmAttrGrp = new HashMap(); private HashMap hmAttrGpEn = new HashMap(); private HashMap hmAbsElems = new HashMap(); private HashMap hmSubsGrp = new HashMap(); private HashMap hmSubsLink = new HashMap(); private HashMap hmSubsNames = new HashMap(); private HashMap hmAttribs = new HashMap(); private HashMap hmAllAttrs = new HashMap(); private HashMap hmGroups = new HashMap(); private HashMap hmNameSpaces = new HashMap(); private SchemaSubstitutions ssOverRides; private String targetNS; private String targetNSPrefix; /** Restrictions for simple types (element restriction) */ private HashMap hmElemRestr = new HashMap(); /** Restrictions for simple types (type restriction) */ private HashMap hmTypeRestr = new HashMap(); //--------------------------------------------------------------------------- //--- //--- Constructor //--- //--------------------------------------------------------------------------- public SchemaLoader() {} //--------------------------------------------------------------------------- //--- //--- API methods //--- //--------------------------------------------------------------------------- public MetadataSchema load(String xmlSchemaFile, String schemaId, String xmlSubstitutionsFile) throws Exception { ssOverRides = new SchemaSubstitutions(xmlSubstitutionsFile); if (xmlSchemaFile.startsWith("_")) return new MetadataSchema(new Element("root")); //--- PHASE 1 : pre-processing //--- //--- the xml file is parsed and simplified. Xml schema subtrees are //--- wrapped in some classes ArrayList alElementFiles = loadFile(xmlSchemaFile, new HashSet()); parseElements(alElementFiles); //--- PHASE 2 : resolve abstract elements for(Iterator i=hmSubsGrp.keySet().iterator(); i.hasNext();) { String elem = (String) i.next(); ArrayList elements = (ArrayList) hmSubsGrp.get(elem); ArrayList subsNames = new ArrayList(); hmSubsNames.put(elem,subsNames); for(int j=0; j<elements.size(); j++) { ElementEntry ee = (ElementEntry) elements.get(j); if (ee.type == null) { ee.type = (String) hmAbsElems.get(elem); if (ee.type == null) { // If we don't have a type then insert with null and fix // when all elements have been added to hmElements Logger.log("Type is null for 'element' : "+ee.name+" which is part of substitution group with head element "+elem); } } hmElements.put(ee.name, ee.type); subsNames.add(ee.name); } } //--- PHASE 3 : add namespaces and elements MetadataSchema mds = new MetadataSchema(elRoot); for (int j = 0;j < alElementFiles.size();j++) { ElementInfo ei = (ElementInfo) alElementFiles.get(j); mds.addNS(ei.targetNSPrefix,ei.targetNS); } for(Iterator i=hmElements.keySet().iterator(); i.hasNext();) { String elem = (String) i.next(); String type = (String) hmElements.get(elem); // fix any null types by back tracking through substitution links // until we get a concrete type or die trying :-) if (type == null) { Logger.log("Searching for type for element "+elem); type = recurseOnSubstitutionLinks(elem); if (type == null) { System.out.println("WARNING: Cannot find type for " +elem+": assuming string"); type="string"; } else { Logger.log("-- Recursive search returned "+type+" for element "+elem); } } ArrayList elemRestr = (ArrayList) hmElemRestr.get(elem); ArrayList typeRestr = (ArrayList) hmTypeRestr.get(type); if (elemRestr == null) elemRestr = new ArrayList(); if (typeRestr != null) elemRestr.addAll(typeRestr); ArrayList elemSubs = (ArrayList) hmSubsNames.get(elem); if (elemSubs == null) elemSubs = new ArrayList(); String elemSubsLink = (String) hmSubsLink.get(elem); if (elemSubsLink == null) elemSubsLink = ""; mds.addElement(elem, type, elemRestr, elemSubs, elemSubsLink); } //--- PHASE 4 : resolve references in attribute groups for (Iterator i=hmAttrGpEn.values().iterator();i.hasNext();) { AttributeGroupEntry age = (AttributeGroupEntry) i.next(); for (int k=0;k<age.alAttrs.size();k++) { AttributeEntry attr = (AttributeEntry)age.alAttrs.get(k); if (attr.name != null) hmAllAttrs.put(attr.name,attr); } ArrayList attrs = resolveNestedAttributeGroups(age); hmAttrGrp.put(age.name,attrs); } //--- PHASE 5 : check attributes to see whether they should be qualified HashMap hmAttrChk = new HashMap(); for(Iterator i=hmAllAttrs.values().iterator(); i.hasNext();) { AttributeEntry attr = (AttributeEntry) i.next(); AttributeEntry attrPrev = (AttributeEntry) hmAttrChk.get(attr.unqualifiedName); if (attrPrev != null) { attr.form = "qualified"; attrPrev.form = "qualified"; } else { hmAttrChk.put(attr.unqualifiedName,attr); } } //--- PHASE 6 : post-processing //--- //--- resolve type inheritance and elements ArrayList alTypes = new ArrayList(hmTypes.values()); for(ListIterator i=alTypes.listIterator(); i.hasNext();) { ComplexTypeEntry cte = (ComplexTypeEntry) i.next(); MetadataType mdt = new MetadataType(); mdt.setOrType(cte.isOrType); //--- resolve element and attribute inheritance from complexContent if (cte.complexContent != null) { if (cte.complexContent.base != null) { //--- add elements cte.alElements = resolveInheritance(cte); //--- add attribs (if any) ArrayList complexContentAttribs = resolveAttributeInheritance(cte); for(int j=0; j<complexContentAttribs.size(); j++) { AttributeEntry ae = (AttributeEntry) complexContentAttribs.get(j); mdt.addAttribute(buildMetadataAttrib(ae)); } //--- if the base type is an ortype then we need to make this an //--- or type as well ComplexTypeEntry baseCTE = (ComplexTypeEntry)hmTypes.get(cte.complexContent.base); if (baseCTE.isOrType) { cte.isOrType = true; mdt.setOrType(true); Logger.log("Setting "+cte.name+" to isOrType"); } } else { throw new IllegalArgumentException("base not defined for complexContent in "+cte.name); } //--- resolve attribute inheritance from simpleContent } else if (cte.simpleContent != null) { ArrayList simpleContentAttribs = resolveAttributeInheritanceFromSimpleContent(cte); for(int j=0; j<simpleContentAttribs.size(); j++) { AttributeEntry ae = (AttributeEntry) simpleContentAttribs.get(j); mdt.addAttribute(buildMetadataAttrib(ae)); } //--- otherwise process the attributes and attribute groups for this type } else { for(int j=0; j<cte.alAttribs.size(); j++) { AttributeEntry ae = (AttributeEntry) cte.alAttribs.get(j); mdt.addAttribute(buildMetadataAttrib(ae)); } for (int k=0;k < cte.alAttribGroups.size();k++) { String attribGroup = (String)cte.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) { AttributeEntry ae = (AttributeEntry) al.get(j); mdt.addAttribute(buildMetadataAttrib(ae)); } } } //--- now add the elements belonging to this complex type to the mdt for(int j=0; j<cte.alElements.size(); j++) { ElementEntry ee = (ElementEntry) cte.alElements.get(j); // Three situations: // 1. element is a container element - group, choice or sequence - so recurse // and get elements from any containers nested inside this container - // we generate a name to use from the cte.name and element position if ( ee.groupElem || ee.choiceElem || ee.sequenceElem ) { Integer baseNr = j; String baseName = cte.name; String extension; ArrayList elements; if (ee.choiceElem) { extension = Edit.RootChild.CHOICE; elements = ee.alContainerElems; } else if (ee.groupElem) { extension = Edit.RootChild.GROUP; GroupEntry group = (GroupEntry)hmGroups.get(ee.ref); elements = group.alElements; } else { extension = Edit.RootChild.SEQUENCE; elements = ee.alContainerElems; } String type = ee.name = baseName+extension+baseNr; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId, mds,elements, baseName,extension,baseNr); if (newCtes.size() != 0) { for (int ctCntr = 0;ctCntr < newCtes.size();ctCntr++) { ComplexTypeEntry newCte = (ComplexTypeEntry)newCtes.get(ctCntr); i.add(newCte); i.previous(); } } mds.addElement(ee.name, type, new ArrayList(), new ArrayList(), ""); mdt.addElementWithType(ee.name, type, ee.min, ee.max); // 2. element is a reference to a global element so check if abstract or // if the type needs to be turned into a choice ie. it has one element // which is the head of a substitution group or a new choice type // is created for the element or just add it if none of // the above } else if (ee.ref != null) { boolean choiceType = (cte.alElements.size() == 1); handleRefElement(j,schemaId,cte.name,choiceType,ee,mdt,mds); // 3. element is a local element so get type or process local complex/simpleType// and add to the ListIterator if complex } else if (ee.name != null) { ComplexTypeEntry newCte = handleLocalElement(j,schemaId,cte.name,ee,mdt,mds); if (newCte != null) { i.add(newCte); i.previous(); } } else { throw new IllegalArgumentException("Unknown element type at position "+j+" in complexType "+cte.name); } } mds.addType(cte.name, mdt); } return mds; } //--------------------------------------------------------------------------- //--- //--- Recurse on substitution links until we get a type that we can use //--- //--------------------------------------------------------------------------- private String recurseOnSubstitutionLinks(String elemName) { String elemLinkName = (String) hmSubsLink.get(elemName); if (elemLinkName != null) { String elemLinkType = (String) hmElements.get(elemLinkName); if (elemLinkType != null) return elemLinkType; // found concrete type! else recurseOnSubstitutionLinks(elemLinkName); // keep trying } return null; // Cannot find a type so return null } //--------------------------------------------------------------------------- //--- //--- Build a local element into the MetadataType and Schema //--- //--------------------------------------------------------------------------- private ComplexTypeEntry handleLocalElement(Integer elementNr,String schemaId,String baseName,ElementEntry ee,MetadataType mdt,MetadataSchema mds) { ComplexTypeEntry cteInt = null; ArrayList elemRestr = new ArrayList(); if (ee.type == null) { if (ee.complexType != null) { cteInt = ee.complexType; ee.type = cteInt.name = ee.name+"HSI"+elementNr+ getUnqualifiedName(baseName); } else if (ee.simpleType != null) { ee.type = "string"; if (ee.simpleType.alEnum != null) // add enumerations if any elemRestr.add(ee.simpleType.alEnum); } else { System.out.println("WARNING: Could not find type for "+ee.name+" - assuming string"); ee.type = "string"; } } mds.addElement(ee.name, ee.type, elemRestr, new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); return(cteInt); } //--------------------------------------------------------------------------- //--- //--- Return list of substitutes if we want to override those derived //--- from the schema XSDs - this is schema dependent and defined in //--- the schema-substitutes files and is used for elements such as //--- gco:CharacterString in the iso19139 schema //--- //--- returns null if there are no user defined substitutes, //--- OR an empty list if removal of all schema substitutes is required //--- OR a list of ElementEntry objects to use as substitutes //--- //--------------------------------------------------------------------------- private ArrayList getOverRideSubstitutes(String elementName) { ArrayList subs = (ArrayList)hmSubsGrp.get(elementName); ArrayList ssOs = ssOverRides.getSubstitutes(elementName); if (ssOs != null && subs != null) { ArrayList results = new ArrayList(); ArrayList validSubs = (ArrayList)hmSubsNames.get(elementName); for (int i = 0;i < ssOs.size();i++) { String altSub = (String)ssOs.get(i); if (validSubs != null && !validSubs.contains(altSub)) { System.out.println("WARNING: schema-substitutions.xml specified "+altSub+" for element "+elementName+" but the schema does not define this as a valid substitute"); } for (int k = 0;k < subs.size();k++) { ElementEntry ee = (ElementEntry)subs.get(k); if (ee.name.equals(altSub)) { results.add(ee); } } } if (results.size() == 0 && validSubs != null) { System.out.println("WARNING: schema-substitutions.xml has wiped out XSD substitution list for "+elementName); } return results; } return null; } //--------------------------------------------------------------------------- //--- //--- Build a reference to a global element into the MetadataType and Schema //--- //--------------------------------------------------------------------------- private void handleRefElement(Integer elementNr,String schemaId,String baseName,boolean choiceType,ElementEntry ee,MetadataType mdt,MetadataSchema mds) { String type = (String) hmElements.get(ee.ref); boolean isAbstract = hmAbsElems.containsKey(ee.ref); // If we have user specified substitutions then use them otherwise // use those from the schema boolean doSubs = true; ArrayList al = getOverRideSubstitutes(ee.ref); if (al == null) al = (ArrayList)hmSubsGrp.get(ee.ref); else doSubs = false; if ((al != null && al.size() > 0) || isAbstract ) { if (choiceType) { // The complex type has only one element then make it a choice type if // there are concrete elements in the substitution group Integer elementsAdded = assembleChoiceElements(mdt,al,doSubs); if (!isAbstract && doSubs) { /* * Control of substitution lists is via the schema-substitutions.xml * file because some profiles do not mandate substitutions of this * kind eg. wmo * if (elementsAdded == 1 && (getPrefix(mdt.getElementAt(0)).equals(getProfile(schemaId))) && schemaId.startsWith("iso19139")) { Logger.log("Sticking with "+mdt.toString()+" for "+ee.ref); } else { * */ mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); elementsAdded++; /*}*/ } mdt.setOrType(elementsAdded > 1); } else { // The complex type has real elements and/or attributes so make a new // choice element with type and replace this element with it MetadataType mdtc = new MetadataType(); Integer elementsAdded = assembleChoiceElements(mdtc,al,doSubs); if (!isAbstract && doSubs) { mdtc.addRefElementWithType(ee.ref,ee.type,ee.min,ee.max); elementsAdded++; } mdtc.setOrType(elementsAdded > 1); type = ee.ref+Edit.RootChild.CHOICE+elementNr; String name = type; mds.addType(type,mdtc); mds.addElement(name,type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(name,type,ee.min,ee.max); } } else if (!isAbstract) { mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); } else { System.out.println("WARNING: element "+ee.ref+" from "+baseName+" has fallen through the logic (abstract: "+isAbstract+") - ignoring"); } } //--------------------------------------------------------------------------- //--- //--- Recurse on attributeGroups to build a list of AttributeEntry objects //--- //--------------------------------------------------------------------------- private ArrayList resolveNestedAttributeGroups(AttributeGroupEntry age) { ArrayList attrs = new ArrayList(); if (age.alAttrGrps.size() > 0) { for (int i=0;i<age.alAttrGrps.size();i++) { AttributeGroupEntry ageInternal = (AttributeGroupEntry)age.alAttrGrps.get(i); AttributeGroupEntry ageRef = (AttributeGroupEntry)hmAttrGpEn.get(ageInternal.ref); if (ageRef == null) throw new IllegalArgumentException ("ERROR: cannot find attributeGroup with ref "+ageInternal.ref); attrs.addAll(resolveNestedAttributeGroups(ageRef)); } } attrs.addAll(age.alAttrs); return attrs; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with nested containers //--- //--------------------------------------------------------------------------- private ArrayList createTypeAndResolveNestedContainers(String schemaId, MetadataSchema mds,ArrayList al,String baseName, String extension,Integer baseNr) { ArrayList complexTypes = new ArrayList(); Integer oldBaseNr = baseNr; if (al == null) return complexTypes; MetadataType mdt = new MetadataType(); if (extension.contains(Edit.RootChild.CHOICE)) mdt.setOrType(true); for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); baseNr++; // CHOICE if (ee.choiceElem) { String newExtension = Edit.RootChild.CHOICE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // GROUP } else if (ee.groupElem) { String newExtension = Edit.RootChild.GROUP; if (ee.ref != null) { GroupEntry group = (GroupEntry) hmGroups.get(ee.ref); ArrayList alGroupElements = group.alElements; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,alGroupElements,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); } else { System.out.println("WARNING: group element ref is NULL in "+baseName+extension+baseNr); } // SEQUENCE } else if (ee.sequenceElem) { String newExtension = Edit.RootChild.SEQUENCE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // ELEMENT } else { if (ee.name != null) { ComplexTypeEntry newCte = handleLocalElement(k,schemaId,baseName,ee,mdt,mds); if (newCte != null) complexTypes.add(newCte); } else { handleRefElement(k,schemaId,baseName,false,ee,mdt,mds); } } } mds.addType(baseName+extension+oldBaseNr,mdt); return complexTypes; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with abstract elements //--- //--------------------------------------------------------------------------- private int assembleChoiceElements(MetadataType mdt,ArrayList al,boolean doSubs) { int number = 0; if (al == null) return number; for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); if (ee.abstrElem) { Integer numberRecursed = assembleChoiceElements(mdt,(ArrayList) hmSubsGrp.get(ee.name),doSubs); number = number + numberRecursed; } else { number++; mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // Also add any elements that substitute for this one so that we can // complete the list of choices if required if (doSubs) { ArrayList elemSubs = (ArrayList)hmSubsGrp.get(ee.name); if (elemSubs != null) { for (int j = 0;j < elemSubs.size();j++) { ElementEntry eeSub = (ElementEntry)elemSubs.get(j); mdt.addElementWithType(eeSub.name,eeSub.type,eeSub.min,eeSub.max); number++; } } } } } return number; } //--------------------------------------------------------------------------- //--- //--- PHASE 1 : Schema loading //--- //--------------------------------------------------------------------------- /** Loads the xml-schema file, removes annotations and resolve imports/includes */ private ArrayList loadFile(String xmlSchemaFile, HashSet loadedFiles) throws Exception { loadedFiles.add(new File(xmlSchemaFile).getCanonicalPath()); String path = new File(xmlSchemaFile).getParent() + "/"; //--- load xml-schema elRoot = Xml.loadFile(xmlSchemaFile); // change target namespace String oldtargetNS = targetNS; String oldtargetNSPrefix = targetNSPrefix; targetNS = elRoot.getAttributeValue("targetNamespace"); targetNSPrefix = null; if (targetNS != null) { for (Iterator i = elRoot.getAdditionalNamespaces().iterator(); i.hasNext(); ) { Namespace ns = (Namespace)i.next(); if (targetNS.equals(ns.getURI())) { targetNSPrefix = ns.getPrefix(); break; } } if ("".equals(targetNSPrefix)) targetNSPrefix = null; } // This is a bug in jdom - seems that if the namespace prefix is xml: and // namespace is as shown in the if statement then getAdditionalNamespaces // doesn't return the namespaces and we can't get a prefix - this fix gets // around that bug if (xmlSchemaFile.contains("xml.xsd") && targetNS.equals("http://www.w3.org/XML/1998/namespace")) targetNSPrefix="xml"; List children = elRoot.getChildren(); //--- collect elements into an array because we have to add elements //--- when we encounter the "import" element ArrayList alElementFiles = new ArrayList(); for(int i=0; i<children.size(); i++) { Element elChild = (Element) children.get(i); String name = elChild.getName(); if (name.equals("annotation")) ; else if (name.equals("import") || name.equals("include")) { String schemaLoc = elChild.getAttributeValue("schemaLocation"); //--- we must prevent imports from the web if (schemaLoc.startsWith("http:")) { int lastSlash = schemaLoc.lastIndexOf("/"); schemaLoc = schemaLoc.substring(lastSlash +1); } if (!loadedFiles.contains(new File(path + schemaLoc).getCanonicalPath())) alElementFiles.addAll(loadFile(path + schemaLoc, loadedFiles)); } else alElementFiles.add(new ElementInfo(elChild, xmlSchemaFile, targetNS, targetNSPrefix)); } // restore target namespace targetNS = oldtargetNS; targetNSPrefix = oldtargetNSPrefix; return alElementFiles; } //--------------------------------------------------------------------------- //--- //--- PHASE 2 : Parse elements building intermediate data structures //--- //--------------------------------------------------------------------------- private void parseElements(ArrayList alElementFiles) throws JDOMException { //--- clear some structures hmElements .clear(); hmTypes .clear(); hmAttrGrp .clear(); hmAbsElems .clear(); hmSubsGrp .clear(); hmSubsLink .clear(); hmElemRestr.clear(); hmTypeRestr.clear(); hmAttribs .clear(); hmAllAttrs .clear(); hmGroups .clear(); for(int i=0; i<alElementFiles.size(); i++) { ElementInfo ei = (ElementInfo) alElementFiles.get(i); Element elChild = ei.element; String name = elChild.getName(); if (name.equals("element")) buildGlobalElement(ei); else if (name.equals("complexType")) buildComplexType(ei); else if (name.equals("simpleType")) buildSimpleType(ei); else if (name.equals("attribute")) buildGlobalAttrib(ei); else if (name.equals("group")) buildGlobalGroup(ei); else if (name.equals("attributeGroup")) buildGlobalAttributeGroup(ei); else Logger.log("Unknown global element : " + elChild.getName(), ei); } } //--------------------------------------------------------------------------- private void buildGlobalElement(ElementInfo ei) { ElementEntry ee = new ElementEntry(ei); if (ee.name == null) throw new IllegalArgumentException("Name is null for element : " + ee.name); if (ee.substGroup != null) { ArrayList al = (ArrayList) hmSubsGrp.get(ee.substGroup); if (al == null) { al = new ArrayList(); hmSubsGrp.put(ee.substGroup, al); } al.add(ee); if (hmSubsLink.get(ee.name) != null) { throw new IllegalArgumentException("Substitution link collision for : "+ee.name+" link to "+ee.substGroup); } else { hmSubsLink.put(ee.name,ee.substGroup); } } if (ee.abstrElem) { if (hmAbsElems.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmAbsElems.put(ee.name, ee.type); return; } if (ee.complexType != null) { String type = ee.name+"HSI"; ee.complexType.name = type; ee.type = type; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmElements.put(ee.name, type); hmTypes.put(type, ee.complexType); } else if (ee.simpleType != null) { String type = ee.name; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); ee.type = "string"; hmElements .put(ee.name, ee.type); hmElemRestr.put(ee.name, ee.simpleType.alEnum); } else { if (ee.type == null && ee.substGroup == null) { System.out.println("WARNING: "+ee.name+" is a global element without a type - assuming a string"); ee.type ="string"; } hmElements.put(ee.name, ee.type); } if (ee.name.contains("SensorML")) { Logger.log("SensorML element detected "+ee.name+" "+ee.complexType.name); } } //--------------------------------------------------------------------------- private void buildComplexType(ElementInfo ei) { ComplexTypeEntry ct = new ComplexTypeEntry(ei); if (hmTypes.containsKey(ct.name)) throw new IllegalArgumentException("Namespace collision for : " + ct.name); hmTypes.put(ct.name, ct); } //--------------------------------------------------------------------------- private void buildSimpleType(ElementInfo ei) { SimpleTypeEntry st = new SimpleTypeEntry(ei); if (hmTypeRestr.containsKey(st.name)) throw new IllegalArgumentException("Namespace collision for : " + st.name); hmTypeRestr.put(st.name, st.alEnum); } //--------------------------------------------------------------------------- private void buildGlobalAttrib(ElementInfo ei) { AttributeEntry at = new AttributeEntry(ei); if (hmAttribs.containsKey(at.name)) throw new IllegalArgumentException("Namespace collision for : " + at.name); hmAttribs.put(at.name, at); hmAllAttrs.put(at.name, at); } //--------------------------------------------------------------------------- private void buildGlobalGroup(ElementInfo ei) { GroupEntry ge = new GroupEntry(ei); if (hmGroups.containsKey(ge.name)) throw new IllegalArgumentException("Namespace collision for : " + ge.name); hmGroups.put(ge.name, ge); } //--------------------------------------------------------------------------- private void buildGlobalAttributeGroup(ElementInfo ei) { AttributeGroupEntry age = new AttributeGroupEntry(ei); if (hmAttrGpEn.containsKey(age.name)) throw new IllegalArgumentException("Namespace collision for : " + age.name); hmAttrGpEn.put(age.name, age); } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with SimpleContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritanceFromSimpleContent(ComplexTypeEntry cte) { ArrayList result = new ArrayList(); if (cte.simpleContent == null) { throw new IllegalArgumentException("SimpleContent must be present in base type of the SimpleContent in "+cte.name); } else { // recurse if we need to follow the base type String baseType = cte.simpleContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE != null) result = new ArrayList(resolveAttributeInheritanceFromSimpleContent(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.simpleContent.restriction) { ArrayList adds = (ArrayList)cte.simpleContent.alAttribs.clone(); for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these else result.addAll((ArrayList)cte.simpleContent.alAttribs.clone()); // No one seems clear on what to do with attributeGroups so treat them // as an extension if (cte.simpleContent.alAttribGroups != null) { for (int k=0;k<cte.simpleContent.alAttribGroups.size();k++) { String attribGroup = (String)cte.simpleContent.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } } return result; } /** function to test whether two AttributeEntry objects have the same name */ boolean eqAttribs(AttributeEntry attribOther,AttributeEntry attrib) { if (attribOther.name != null) { if (attrib.name != null) { if (attribOther.name.equals(attrib.name)) return true; } else { if (attribOther.name.equals(attrib.reference)) return true; } } else { if (attrib.name != null) { if (attribOther.reference.equals(attrib.name)) return true; } else { if (attribOther.reference.equals(attrib.reference)) return true; } } return false; } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with ComplexContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritance(ComplexTypeEntry cte) { if (cte.complexContent == null) return cte.alAttribs; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); ArrayList result = new ArrayList(resolveAttributeInheritance(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.complexContent.restriction) { ArrayList adds = (ArrayList)cte.complexContent.alAttribs; for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these - else + else { result.addAll((ArrayList)cte.complexContent.alAttribs); + if (cte.complexContent.alAttribGroups != null) { + for (int k=0;k<cte.complexContent.alAttribGroups.size();k++) { + String attribGroup = (String)cte.complexContent.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); + if (al == null) + throw new IllegalArgumentException("Attribute group not found : " + attribGroup); + for(int j=0; j<al.size(); j++) + result.add(al.get(j)); + } + } + } // No one seems clear on what to do with attributeGroups so treat them // as an extension if (baseCTE.alAttribGroups != null) { for (int k=0;k<baseCTE.alAttribGroups.size();k++) { String attribGroup = (String)baseCTE.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } return result; } //--------------------------------------------------------------------------- //--- //--- Add in elements to complexType that come from base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveInheritance(ComplexTypeEntry cte) { if (cte == null || cte.complexContent == null) return cte.alElements; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); // skip over the elements in the base type of a restricted complex type // by ending the recursion ArrayList result = new ArrayList(); if (!cte.complexContent.restriction) result = new ArrayList(resolveInheritance(baseCTE)); result.addAll((ArrayList)cte.complexContent.alElements); return result; } //--------------------------------------------------------------------------- private MetadataAttribute buildMetadataAttrib(AttributeEntry ae) { String name = ae.name; String ref = ae.reference; String value = ae.defValue; boolean overRequired = ae.required; MetadataAttribute ma = new MetadataAttribute(); if (ref != null) { ae = (AttributeEntry) hmAttribs.get(ref); if (ae == null) throw new IllegalArgumentException("Reference '"+ref+"' not found for attrib : " +name); } if (ref != null && ref.contains(":")) ma.name = ref; else ma.name = ae.unqualifiedName; if (value != null) ma.defValue = value; else ma.defValue = ae.defValue; ma.required = overRequired; for(int k=0; k<ae.alValues.size(); k++) ma.values.add(ae.alValues.get(k)); return ma; } //--------------------------------------------------------------------------- private String getPrefix(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return ""; else return qname.substring(0, pos); } //-------------------------------------------------------------------------- public String getUnqualifiedName(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return qname; else return qname.substring(pos + 1); } //--------------------------------------------------------------------------- private String getProfile(String name) { int pos = name.indexOf("."); if (pos < 0) return ""; else return name.substring(pos+1); } } //============================================================================== class ElementInfo { public Element element; public String file; public String targetNS; public String targetNSPrefix; //--------------------------------------------------------------------------- public ElementInfo(Element e, String f, String tns, String tnsp) { element = e; file = f; targetNS = tns; targetNSPrefix = tnsp; } } //==============================================================================
false
true
private void handleRefElement(Integer elementNr,String schemaId,String baseName,boolean choiceType,ElementEntry ee,MetadataType mdt,MetadataSchema mds) { String type = (String) hmElements.get(ee.ref); boolean isAbstract = hmAbsElems.containsKey(ee.ref); // If we have user specified substitutions then use them otherwise // use those from the schema boolean doSubs = true; ArrayList al = getOverRideSubstitutes(ee.ref); if (al == null) al = (ArrayList)hmSubsGrp.get(ee.ref); else doSubs = false; if ((al != null && al.size() > 0) || isAbstract ) { if (choiceType) { // The complex type has only one element then make it a choice type if // there are concrete elements in the substitution group Integer elementsAdded = assembleChoiceElements(mdt,al,doSubs); if (!isAbstract && doSubs) { /* * Control of substitution lists is via the schema-substitutions.xml * file because some profiles do not mandate substitutions of this * kind eg. wmo * if (elementsAdded == 1 && (getPrefix(mdt.getElementAt(0)).equals(getProfile(schemaId))) && schemaId.startsWith("iso19139")) { Logger.log("Sticking with "+mdt.toString()+" for "+ee.ref); } else { * */ mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); elementsAdded++; /*}*/ } mdt.setOrType(elementsAdded > 1); } else { // The complex type has real elements and/or attributes so make a new // choice element with type and replace this element with it MetadataType mdtc = new MetadataType(); Integer elementsAdded = assembleChoiceElements(mdtc,al,doSubs); if (!isAbstract && doSubs) { mdtc.addRefElementWithType(ee.ref,ee.type,ee.min,ee.max); elementsAdded++; } mdtc.setOrType(elementsAdded > 1); type = ee.ref+Edit.RootChild.CHOICE+elementNr; String name = type; mds.addType(type,mdtc); mds.addElement(name,type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(name,type,ee.min,ee.max); } } else if (!isAbstract) { mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); } else { System.out.println("WARNING: element "+ee.ref+" from "+baseName+" has fallen through the logic (abstract: "+isAbstract+") - ignoring"); } } //--------------------------------------------------------------------------- //--- //--- Recurse on attributeGroups to build a list of AttributeEntry objects //--- //--------------------------------------------------------------------------- private ArrayList resolveNestedAttributeGroups(AttributeGroupEntry age) { ArrayList attrs = new ArrayList(); if (age.alAttrGrps.size() > 0) { for (int i=0;i<age.alAttrGrps.size();i++) { AttributeGroupEntry ageInternal = (AttributeGroupEntry)age.alAttrGrps.get(i); AttributeGroupEntry ageRef = (AttributeGroupEntry)hmAttrGpEn.get(ageInternal.ref); if (ageRef == null) throw new IllegalArgumentException ("ERROR: cannot find attributeGroup with ref "+ageInternal.ref); attrs.addAll(resolveNestedAttributeGroups(ageRef)); } } attrs.addAll(age.alAttrs); return attrs; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with nested containers //--- //--------------------------------------------------------------------------- private ArrayList createTypeAndResolveNestedContainers(String schemaId, MetadataSchema mds,ArrayList al,String baseName, String extension,Integer baseNr) { ArrayList complexTypes = new ArrayList(); Integer oldBaseNr = baseNr; if (al == null) return complexTypes; MetadataType mdt = new MetadataType(); if (extension.contains(Edit.RootChild.CHOICE)) mdt.setOrType(true); for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); baseNr++; // CHOICE if (ee.choiceElem) { String newExtension = Edit.RootChild.CHOICE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // GROUP } else if (ee.groupElem) { String newExtension = Edit.RootChild.GROUP; if (ee.ref != null) { GroupEntry group = (GroupEntry) hmGroups.get(ee.ref); ArrayList alGroupElements = group.alElements; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,alGroupElements,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); } else { System.out.println("WARNING: group element ref is NULL in "+baseName+extension+baseNr); } // SEQUENCE } else if (ee.sequenceElem) { String newExtension = Edit.RootChild.SEQUENCE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // ELEMENT } else { if (ee.name != null) { ComplexTypeEntry newCte = handleLocalElement(k,schemaId,baseName,ee,mdt,mds); if (newCte != null) complexTypes.add(newCte); } else { handleRefElement(k,schemaId,baseName,false,ee,mdt,mds); } } } mds.addType(baseName+extension+oldBaseNr,mdt); return complexTypes; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with abstract elements //--- //--------------------------------------------------------------------------- private int assembleChoiceElements(MetadataType mdt,ArrayList al,boolean doSubs) { int number = 0; if (al == null) return number; for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); if (ee.abstrElem) { Integer numberRecursed = assembleChoiceElements(mdt,(ArrayList) hmSubsGrp.get(ee.name),doSubs); number = number + numberRecursed; } else { number++; mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // Also add any elements that substitute for this one so that we can // complete the list of choices if required if (doSubs) { ArrayList elemSubs = (ArrayList)hmSubsGrp.get(ee.name); if (elemSubs != null) { for (int j = 0;j < elemSubs.size();j++) { ElementEntry eeSub = (ElementEntry)elemSubs.get(j); mdt.addElementWithType(eeSub.name,eeSub.type,eeSub.min,eeSub.max); number++; } } } } } return number; } //--------------------------------------------------------------------------- //--- //--- PHASE 1 : Schema loading //--- //--------------------------------------------------------------------------- /** Loads the xml-schema file, removes annotations and resolve imports/includes */ private ArrayList loadFile(String xmlSchemaFile, HashSet loadedFiles) throws Exception { loadedFiles.add(new File(xmlSchemaFile).getCanonicalPath()); String path = new File(xmlSchemaFile).getParent() + "/"; //--- load xml-schema elRoot = Xml.loadFile(xmlSchemaFile); // change target namespace String oldtargetNS = targetNS; String oldtargetNSPrefix = targetNSPrefix; targetNS = elRoot.getAttributeValue("targetNamespace"); targetNSPrefix = null; if (targetNS != null) { for (Iterator i = elRoot.getAdditionalNamespaces().iterator(); i.hasNext(); ) { Namespace ns = (Namespace)i.next(); if (targetNS.equals(ns.getURI())) { targetNSPrefix = ns.getPrefix(); break; } } if ("".equals(targetNSPrefix)) targetNSPrefix = null; } // This is a bug in jdom - seems that if the namespace prefix is xml: and // namespace is as shown in the if statement then getAdditionalNamespaces // doesn't return the namespaces and we can't get a prefix - this fix gets // around that bug if (xmlSchemaFile.contains("xml.xsd") && targetNS.equals("http://www.w3.org/XML/1998/namespace")) targetNSPrefix="xml"; List children = elRoot.getChildren(); //--- collect elements into an array because we have to add elements //--- when we encounter the "import" element ArrayList alElementFiles = new ArrayList(); for(int i=0; i<children.size(); i++) { Element elChild = (Element) children.get(i); String name = elChild.getName(); if (name.equals("annotation")) ; else if (name.equals("import") || name.equals("include")) { String schemaLoc = elChild.getAttributeValue("schemaLocation"); //--- we must prevent imports from the web if (schemaLoc.startsWith("http:")) { int lastSlash = schemaLoc.lastIndexOf("/"); schemaLoc = schemaLoc.substring(lastSlash +1); } if (!loadedFiles.contains(new File(path + schemaLoc).getCanonicalPath())) alElementFiles.addAll(loadFile(path + schemaLoc, loadedFiles)); } else alElementFiles.add(new ElementInfo(elChild, xmlSchemaFile, targetNS, targetNSPrefix)); } // restore target namespace targetNS = oldtargetNS; targetNSPrefix = oldtargetNSPrefix; return alElementFiles; } //--------------------------------------------------------------------------- //--- //--- PHASE 2 : Parse elements building intermediate data structures //--- //--------------------------------------------------------------------------- private void parseElements(ArrayList alElementFiles) throws JDOMException { //--- clear some structures hmElements .clear(); hmTypes .clear(); hmAttrGrp .clear(); hmAbsElems .clear(); hmSubsGrp .clear(); hmSubsLink .clear(); hmElemRestr.clear(); hmTypeRestr.clear(); hmAttribs .clear(); hmAllAttrs .clear(); hmGroups .clear(); for(int i=0; i<alElementFiles.size(); i++) { ElementInfo ei = (ElementInfo) alElementFiles.get(i); Element elChild = ei.element; String name = elChild.getName(); if (name.equals("element")) buildGlobalElement(ei); else if (name.equals("complexType")) buildComplexType(ei); else if (name.equals("simpleType")) buildSimpleType(ei); else if (name.equals("attribute")) buildGlobalAttrib(ei); else if (name.equals("group")) buildGlobalGroup(ei); else if (name.equals("attributeGroup")) buildGlobalAttributeGroup(ei); else Logger.log("Unknown global element : " + elChild.getName(), ei); } } //--------------------------------------------------------------------------- private void buildGlobalElement(ElementInfo ei) { ElementEntry ee = new ElementEntry(ei); if (ee.name == null) throw new IllegalArgumentException("Name is null for element : " + ee.name); if (ee.substGroup != null) { ArrayList al = (ArrayList) hmSubsGrp.get(ee.substGroup); if (al == null) { al = new ArrayList(); hmSubsGrp.put(ee.substGroup, al); } al.add(ee); if (hmSubsLink.get(ee.name) != null) { throw new IllegalArgumentException("Substitution link collision for : "+ee.name+" link to "+ee.substGroup); } else { hmSubsLink.put(ee.name,ee.substGroup); } } if (ee.abstrElem) { if (hmAbsElems.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmAbsElems.put(ee.name, ee.type); return; } if (ee.complexType != null) { String type = ee.name+"HSI"; ee.complexType.name = type; ee.type = type; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmElements.put(ee.name, type); hmTypes.put(type, ee.complexType); } else if (ee.simpleType != null) { String type = ee.name; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); ee.type = "string"; hmElements .put(ee.name, ee.type); hmElemRestr.put(ee.name, ee.simpleType.alEnum); } else { if (ee.type == null && ee.substGroup == null) { System.out.println("WARNING: "+ee.name+" is a global element without a type - assuming a string"); ee.type ="string"; } hmElements.put(ee.name, ee.type); } if (ee.name.contains("SensorML")) { Logger.log("SensorML element detected "+ee.name+" "+ee.complexType.name); } } //--------------------------------------------------------------------------- private void buildComplexType(ElementInfo ei) { ComplexTypeEntry ct = new ComplexTypeEntry(ei); if (hmTypes.containsKey(ct.name)) throw new IllegalArgumentException("Namespace collision for : " + ct.name); hmTypes.put(ct.name, ct); } //--------------------------------------------------------------------------- private void buildSimpleType(ElementInfo ei) { SimpleTypeEntry st = new SimpleTypeEntry(ei); if (hmTypeRestr.containsKey(st.name)) throw new IllegalArgumentException("Namespace collision for : " + st.name); hmTypeRestr.put(st.name, st.alEnum); } //--------------------------------------------------------------------------- private void buildGlobalAttrib(ElementInfo ei) { AttributeEntry at = new AttributeEntry(ei); if (hmAttribs.containsKey(at.name)) throw new IllegalArgumentException("Namespace collision for : " + at.name); hmAttribs.put(at.name, at); hmAllAttrs.put(at.name, at); } //--------------------------------------------------------------------------- private void buildGlobalGroup(ElementInfo ei) { GroupEntry ge = new GroupEntry(ei); if (hmGroups.containsKey(ge.name)) throw new IllegalArgumentException("Namespace collision for : " + ge.name); hmGroups.put(ge.name, ge); } //--------------------------------------------------------------------------- private void buildGlobalAttributeGroup(ElementInfo ei) { AttributeGroupEntry age = new AttributeGroupEntry(ei); if (hmAttrGpEn.containsKey(age.name)) throw new IllegalArgumentException("Namespace collision for : " + age.name); hmAttrGpEn.put(age.name, age); } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with SimpleContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritanceFromSimpleContent(ComplexTypeEntry cte) { ArrayList result = new ArrayList(); if (cte.simpleContent == null) { throw new IllegalArgumentException("SimpleContent must be present in base type of the SimpleContent in "+cte.name); } else { // recurse if we need to follow the base type String baseType = cte.simpleContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE != null) result = new ArrayList(resolveAttributeInheritanceFromSimpleContent(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.simpleContent.restriction) { ArrayList adds = (ArrayList)cte.simpleContent.alAttribs.clone(); for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these else result.addAll((ArrayList)cte.simpleContent.alAttribs.clone()); // No one seems clear on what to do with attributeGroups so treat them // as an extension if (cte.simpleContent.alAttribGroups != null) { for (int k=0;k<cte.simpleContent.alAttribGroups.size();k++) { String attribGroup = (String)cte.simpleContent.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } } return result; } /** function to test whether two AttributeEntry objects have the same name */ boolean eqAttribs(AttributeEntry attribOther,AttributeEntry attrib) { if (attribOther.name != null) { if (attrib.name != null) { if (attribOther.name.equals(attrib.name)) return true; } else { if (attribOther.name.equals(attrib.reference)) return true; } } else { if (attrib.name != null) { if (attribOther.reference.equals(attrib.name)) return true; } else { if (attribOther.reference.equals(attrib.reference)) return true; } } return false; } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with ComplexContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritance(ComplexTypeEntry cte) { if (cte.complexContent == null) return cte.alAttribs; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); ArrayList result = new ArrayList(resolveAttributeInheritance(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.complexContent.restriction) { ArrayList adds = (ArrayList)cte.complexContent.alAttribs; for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these else result.addAll((ArrayList)cte.complexContent.alAttribs); // No one seems clear on what to do with attributeGroups so treat them // as an extension if (baseCTE.alAttribGroups != null) { for (int k=0;k<baseCTE.alAttribGroups.size();k++) { String attribGroup = (String)baseCTE.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } return result; } //--------------------------------------------------------------------------- //--- //--- Add in elements to complexType that come from base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveInheritance(ComplexTypeEntry cte) { if (cte == null || cte.complexContent == null) return cte.alElements; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); // skip over the elements in the base type of a restricted complex type // by ending the recursion ArrayList result = new ArrayList(); if (!cte.complexContent.restriction) result = new ArrayList(resolveInheritance(baseCTE)); result.addAll((ArrayList)cte.complexContent.alElements); return result; } //--------------------------------------------------------------------------- private MetadataAttribute buildMetadataAttrib(AttributeEntry ae) { String name = ae.name; String ref = ae.reference; String value = ae.defValue; boolean overRequired = ae.required; MetadataAttribute ma = new MetadataAttribute(); if (ref != null) { ae = (AttributeEntry) hmAttribs.get(ref); if (ae == null) throw new IllegalArgumentException("Reference '"+ref+"' not found for attrib : " +name); } if (ref != null && ref.contains(":")) ma.name = ref; else ma.name = ae.unqualifiedName; if (value != null) ma.defValue = value; else ma.defValue = ae.defValue; ma.required = overRequired; for(int k=0; k<ae.alValues.size(); k++) ma.values.add(ae.alValues.get(k)); return ma; } //--------------------------------------------------------------------------- private String getPrefix(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return ""; else return qname.substring(0, pos); } //-------------------------------------------------------------------------- public String getUnqualifiedName(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return qname; else return qname.substring(pos + 1); } //--------------------------------------------------------------------------- private String getProfile(String name) { int pos = name.indexOf("."); if (pos < 0) return ""; else return name.substring(pos+1); } }
private void handleRefElement(Integer elementNr,String schemaId,String baseName,boolean choiceType,ElementEntry ee,MetadataType mdt,MetadataSchema mds) { String type = (String) hmElements.get(ee.ref); boolean isAbstract = hmAbsElems.containsKey(ee.ref); // If we have user specified substitutions then use them otherwise // use those from the schema boolean doSubs = true; ArrayList al = getOverRideSubstitutes(ee.ref); if (al == null) al = (ArrayList)hmSubsGrp.get(ee.ref); else doSubs = false; if ((al != null && al.size() > 0) || isAbstract ) { if (choiceType) { // The complex type has only one element then make it a choice type if // there are concrete elements in the substitution group Integer elementsAdded = assembleChoiceElements(mdt,al,doSubs); if (!isAbstract && doSubs) { /* * Control of substitution lists is via the schema-substitutions.xml * file because some profiles do not mandate substitutions of this * kind eg. wmo * if (elementsAdded == 1 && (getPrefix(mdt.getElementAt(0)).equals(getProfile(schemaId))) && schemaId.startsWith("iso19139")) { Logger.log("Sticking with "+mdt.toString()+" for "+ee.ref); } else { * */ mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); elementsAdded++; /*}*/ } mdt.setOrType(elementsAdded > 1); } else { // The complex type has real elements and/or attributes so make a new // choice element with type and replace this element with it MetadataType mdtc = new MetadataType(); Integer elementsAdded = assembleChoiceElements(mdtc,al,doSubs); if (!isAbstract && doSubs) { mdtc.addRefElementWithType(ee.ref,ee.type,ee.min,ee.max); elementsAdded++; } mdtc.setOrType(elementsAdded > 1); type = ee.ref+Edit.RootChild.CHOICE+elementNr; String name = type; mds.addType(type,mdtc); mds.addElement(name,type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(name,type,ee.min,ee.max); } } else if (!isAbstract) { mdt.addRefElementWithType(ee.ref,type,ee.min,ee.max); } else { System.out.println("WARNING: element "+ee.ref+" from "+baseName+" has fallen through the logic (abstract: "+isAbstract+") - ignoring"); } } //--------------------------------------------------------------------------- //--- //--- Recurse on attributeGroups to build a list of AttributeEntry objects //--- //--------------------------------------------------------------------------- private ArrayList resolveNestedAttributeGroups(AttributeGroupEntry age) { ArrayList attrs = new ArrayList(); if (age.alAttrGrps.size() > 0) { for (int i=0;i<age.alAttrGrps.size();i++) { AttributeGroupEntry ageInternal = (AttributeGroupEntry)age.alAttrGrps.get(i); AttributeGroupEntry ageRef = (AttributeGroupEntry)hmAttrGpEn.get(ageInternal.ref); if (ageRef == null) throw new IllegalArgumentException ("ERROR: cannot find attributeGroup with ref "+ageInternal.ref); attrs.addAll(resolveNestedAttributeGroups(ageRef)); } } attrs.addAll(age.alAttrs); return attrs; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with nested containers //--- //--------------------------------------------------------------------------- private ArrayList createTypeAndResolveNestedContainers(String schemaId, MetadataSchema mds,ArrayList al,String baseName, String extension,Integer baseNr) { ArrayList complexTypes = new ArrayList(); Integer oldBaseNr = baseNr; if (al == null) return complexTypes; MetadataType mdt = new MetadataType(); if (extension.contains(Edit.RootChild.CHOICE)) mdt.setOrType(true); for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); baseNr++; // CHOICE if (ee.choiceElem) { String newExtension = Edit.RootChild.CHOICE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // GROUP } else if (ee.groupElem) { String newExtension = Edit.RootChild.GROUP; if (ee.ref != null) { GroupEntry group = (GroupEntry) hmGroups.get(ee.ref); ArrayList alGroupElements = group.alElements; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,alGroupElements,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); } else { System.out.println("WARNING: group element ref is NULL in "+baseName+extension+baseNr); } // SEQUENCE } else if (ee.sequenceElem) { String newExtension = Edit.RootChild.SEQUENCE; ArrayList newCtes = createTypeAndResolveNestedContainers(schemaId,mds,ee.alContainerElems,baseName,newExtension,baseNr); if (newCtes.size() > 0) complexTypes.addAll(newCtes); ee.name = ee.type = baseName+newExtension+baseNr; mds.addElement(ee.name,ee.type,new ArrayList(),new ArrayList(), ""); mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // ELEMENT } else { if (ee.name != null) { ComplexTypeEntry newCte = handleLocalElement(k,schemaId,baseName,ee,mdt,mds); if (newCte != null) complexTypes.add(newCte); } else { handleRefElement(k,schemaId,baseName,false,ee,mdt,mds); } } } mds.addType(baseName+extension+oldBaseNr,mdt); return complexTypes; } //--------------------------------------------------------------------------- //--- //--- Descend recursively to deal with abstract elements //--- //--------------------------------------------------------------------------- private int assembleChoiceElements(MetadataType mdt,ArrayList al,boolean doSubs) { int number = 0; if (al == null) return number; for(int k=0; k<al.size(); k++) { ElementEntry ee = (ElementEntry) al.get(k); if (ee.abstrElem) { Integer numberRecursed = assembleChoiceElements(mdt,(ArrayList) hmSubsGrp.get(ee.name),doSubs); number = number + numberRecursed; } else { number++; mdt.addElementWithType(ee.name, ee.type, ee.min, ee.max); // Also add any elements that substitute for this one so that we can // complete the list of choices if required if (doSubs) { ArrayList elemSubs = (ArrayList)hmSubsGrp.get(ee.name); if (elemSubs != null) { for (int j = 0;j < elemSubs.size();j++) { ElementEntry eeSub = (ElementEntry)elemSubs.get(j); mdt.addElementWithType(eeSub.name,eeSub.type,eeSub.min,eeSub.max); number++; } } } } } return number; } //--------------------------------------------------------------------------- //--- //--- PHASE 1 : Schema loading //--- //--------------------------------------------------------------------------- /** Loads the xml-schema file, removes annotations and resolve imports/includes */ private ArrayList loadFile(String xmlSchemaFile, HashSet loadedFiles) throws Exception { loadedFiles.add(new File(xmlSchemaFile).getCanonicalPath()); String path = new File(xmlSchemaFile).getParent() + "/"; //--- load xml-schema elRoot = Xml.loadFile(xmlSchemaFile); // change target namespace String oldtargetNS = targetNS; String oldtargetNSPrefix = targetNSPrefix; targetNS = elRoot.getAttributeValue("targetNamespace"); targetNSPrefix = null; if (targetNS != null) { for (Iterator i = elRoot.getAdditionalNamespaces().iterator(); i.hasNext(); ) { Namespace ns = (Namespace)i.next(); if (targetNS.equals(ns.getURI())) { targetNSPrefix = ns.getPrefix(); break; } } if ("".equals(targetNSPrefix)) targetNSPrefix = null; } // This is a bug in jdom - seems that if the namespace prefix is xml: and // namespace is as shown in the if statement then getAdditionalNamespaces // doesn't return the namespaces and we can't get a prefix - this fix gets // around that bug if (xmlSchemaFile.contains("xml.xsd") && targetNS.equals("http://www.w3.org/XML/1998/namespace")) targetNSPrefix="xml"; List children = elRoot.getChildren(); //--- collect elements into an array because we have to add elements //--- when we encounter the "import" element ArrayList alElementFiles = new ArrayList(); for(int i=0; i<children.size(); i++) { Element elChild = (Element) children.get(i); String name = elChild.getName(); if (name.equals("annotation")) ; else if (name.equals("import") || name.equals("include")) { String schemaLoc = elChild.getAttributeValue("schemaLocation"); //--- we must prevent imports from the web if (schemaLoc.startsWith("http:")) { int lastSlash = schemaLoc.lastIndexOf("/"); schemaLoc = schemaLoc.substring(lastSlash +1); } if (!loadedFiles.contains(new File(path + schemaLoc).getCanonicalPath())) alElementFiles.addAll(loadFile(path + schemaLoc, loadedFiles)); } else alElementFiles.add(new ElementInfo(elChild, xmlSchemaFile, targetNS, targetNSPrefix)); } // restore target namespace targetNS = oldtargetNS; targetNSPrefix = oldtargetNSPrefix; return alElementFiles; } //--------------------------------------------------------------------------- //--- //--- PHASE 2 : Parse elements building intermediate data structures //--- //--------------------------------------------------------------------------- private void parseElements(ArrayList alElementFiles) throws JDOMException { //--- clear some structures hmElements .clear(); hmTypes .clear(); hmAttrGrp .clear(); hmAbsElems .clear(); hmSubsGrp .clear(); hmSubsLink .clear(); hmElemRestr.clear(); hmTypeRestr.clear(); hmAttribs .clear(); hmAllAttrs .clear(); hmGroups .clear(); for(int i=0; i<alElementFiles.size(); i++) { ElementInfo ei = (ElementInfo) alElementFiles.get(i); Element elChild = ei.element; String name = elChild.getName(); if (name.equals("element")) buildGlobalElement(ei); else if (name.equals("complexType")) buildComplexType(ei); else if (name.equals("simpleType")) buildSimpleType(ei); else if (name.equals("attribute")) buildGlobalAttrib(ei); else if (name.equals("group")) buildGlobalGroup(ei); else if (name.equals("attributeGroup")) buildGlobalAttributeGroup(ei); else Logger.log("Unknown global element : " + elChild.getName(), ei); } } //--------------------------------------------------------------------------- private void buildGlobalElement(ElementInfo ei) { ElementEntry ee = new ElementEntry(ei); if (ee.name == null) throw new IllegalArgumentException("Name is null for element : " + ee.name); if (ee.substGroup != null) { ArrayList al = (ArrayList) hmSubsGrp.get(ee.substGroup); if (al == null) { al = new ArrayList(); hmSubsGrp.put(ee.substGroup, al); } al.add(ee); if (hmSubsLink.get(ee.name) != null) { throw new IllegalArgumentException("Substitution link collision for : "+ee.name+" link to "+ee.substGroup); } else { hmSubsLink.put(ee.name,ee.substGroup); } } if (ee.abstrElem) { if (hmAbsElems.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmAbsElems.put(ee.name, ee.type); return; } if (ee.complexType != null) { String type = ee.name+"HSI"; ee.complexType.name = type; ee.type = type; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); hmElements.put(ee.name, type); hmTypes.put(type, ee.complexType); } else if (ee.simpleType != null) { String type = ee.name; if (hmElements.containsKey(ee.name)) throw new IllegalArgumentException("Namespace collision for : " + ee.name); ee.type = "string"; hmElements .put(ee.name, ee.type); hmElemRestr.put(ee.name, ee.simpleType.alEnum); } else { if (ee.type == null && ee.substGroup == null) { System.out.println("WARNING: "+ee.name+" is a global element without a type - assuming a string"); ee.type ="string"; } hmElements.put(ee.name, ee.type); } if (ee.name.contains("SensorML")) { Logger.log("SensorML element detected "+ee.name+" "+ee.complexType.name); } } //--------------------------------------------------------------------------- private void buildComplexType(ElementInfo ei) { ComplexTypeEntry ct = new ComplexTypeEntry(ei); if (hmTypes.containsKey(ct.name)) throw new IllegalArgumentException("Namespace collision for : " + ct.name); hmTypes.put(ct.name, ct); } //--------------------------------------------------------------------------- private void buildSimpleType(ElementInfo ei) { SimpleTypeEntry st = new SimpleTypeEntry(ei); if (hmTypeRestr.containsKey(st.name)) throw new IllegalArgumentException("Namespace collision for : " + st.name); hmTypeRestr.put(st.name, st.alEnum); } //--------------------------------------------------------------------------- private void buildGlobalAttrib(ElementInfo ei) { AttributeEntry at = new AttributeEntry(ei); if (hmAttribs.containsKey(at.name)) throw new IllegalArgumentException("Namespace collision for : " + at.name); hmAttribs.put(at.name, at); hmAllAttrs.put(at.name, at); } //--------------------------------------------------------------------------- private void buildGlobalGroup(ElementInfo ei) { GroupEntry ge = new GroupEntry(ei); if (hmGroups.containsKey(ge.name)) throw new IllegalArgumentException("Namespace collision for : " + ge.name); hmGroups.put(ge.name, ge); } //--------------------------------------------------------------------------- private void buildGlobalAttributeGroup(ElementInfo ei) { AttributeGroupEntry age = new AttributeGroupEntry(ei); if (hmAttrGpEn.containsKey(age.name)) throw new IllegalArgumentException("Namespace collision for : " + age.name); hmAttrGpEn.put(age.name, age); } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with SimpleContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritanceFromSimpleContent(ComplexTypeEntry cte) { ArrayList result = new ArrayList(); if (cte.simpleContent == null) { throw new IllegalArgumentException("SimpleContent must be present in base type of the SimpleContent in "+cte.name); } else { // recurse if we need to follow the base type String baseType = cte.simpleContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE != null) result = new ArrayList(resolveAttributeInheritanceFromSimpleContent(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.simpleContent.restriction) { ArrayList adds = (ArrayList)cte.simpleContent.alAttribs.clone(); for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these else result.addAll((ArrayList)cte.simpleContent.alAttribs.clone()); // No one seems clear on what to do with attributeGroups so treat them // as an extension if (cte.simpleContent.alAttribGroups != null) { for (int k=0;k<cte.simpleContent.alAttribGroups.size();k++) { String attribGroup = (String)cte.simpleContent.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } } return result; } /** function to test whether two AttributeEntry objects have the same name */ boolean eqAttribs(AttributeEntry attribOther,AttributeEntry attrib) { if (attribOther.name != null) { if (attrib.name != null) { if (attribOther.name.equals(attrib.name)) return true; } else { if (attribOther.name.equals(attrib.reference)) return true; } } else { if (attrib.name != null) { if (attribOther.reference.equals(attrib.name)) return true; } else { if (attribOther.reference.equals(attrib.reference)) return true; } } return false; } //--------------------------------------------------------------------------- //--- //--- Add in attributes from complexType with ComplexContent that restricts //--- or extends a base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveAttributeInheritance(ComplexTypeEntry cte) { if (cte.complexContent == null) return cte.alAttribs; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); ArrayList result = new ArrayList(resolveAttributeInheritance(baseCTE)); // if the base type was a restriction then replace the attributes we got // from the restriction with these if (cte.complexContent.restriction) { ArrayList adds = (ArrayList)cte.complexContent.alAttribs; for (int i = 0;i < result.size();i++) { AttributeEntry attrib = (AttributeEntry)result.get(i); for (int j = 0;j < adds.size();j++) { AttributeEntry attribOther = (AttributeEntry)adds.get(j); boolean eqAttrib = eqAttribs(attribOther,attrib); if (eqAttrib) { result.set(i,attribOther); } } } } // otherwise base type was an extension so add the attributes we got // from the extension to these else { result.addAll((ArrayList)cte.complexContent.alAttribs); if (cte.complexContent.alAttribGroups != null) { for (int k=0;k<cte.complexContent.alAttribGroups.size();k++) { String attribGroup = (String)cte.complexContent.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } } // No one seems clear on what to do with attributeGroups so treat them // as an extension if (baseCTE.alAttribGroups != null) { for (int k=0;k<baseCTE.alAttribGroups.size();k++) { String attribGroup = (String)baseCTE.alAttribGroups.get(k); ArrayList al = (ArrayList) hmAttrGrp.get(attribGroup); if (al == null) throw new IllegalArgumentException("Attribute group not found : " + attribGroup); for(int j=0; j<al.size(); j++) result.add(al.get(j)); } } return result; } //--------------------------------------------------------------------------- //--- //--- Add in elements to complexType that come from base type (if any) //--- //--------------------------------------------------------------------------- private ArrayList resolveInheritance(ComplexTypeEntry cte) { if (cte == null || cte.complexContent == null) return cte.alElements; String baseType = cte.complexContent.base; ComplexTypeEntry baseCTE = (ComplexTypeEntry) hmTypes.get(baseType); if (baseCTE == null) throw new IllegalArgumentException("Base type not found for : " + baseType); // skip over the elements in the base type of a restricted complex type // by ending the recursion ArrayList result = new ArrayList(); if (!cte.complexContent.restriction) result = new ArrayList(resolveInheritance(baseCTE)); result.addAll((ArrayList)cte.complexContent.alElements); return result; } //--------------------------------------------------------------------------- private MetadataAttribute buildMetadataAttrib(AttributeEntry ae) { String name = ae.name; String ref = ae.reference; String value = ae.defValue; boolean overRequired = ae.required; MetadataAttribute ma = new MetadataAttribute(); if (ref != null) { ae = (AttributeEntry) hmAttribs.get(ref); if (ae == null) throw new IllegalArgumentException("Reference '"+ref+"' not found for attrib : " +name); } if (ref != null && ref.contains(":")) ma.name = ref; else ma.name = ae.unqualifiedName; if (value != null) ma.defValue = value; else ma.defValue = ae.defValue; ma.required = overRequired; for(int k=0; k<ae.alValues.size(); k++) ma.values.add(ae.alValues.get(k)); return ma; } //--------------------------------------------------------------------------- private String getPrefix(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return ""; else return qname.substring(0, pos); } //-------------------------------------------------------------------------- public String getUnqualifiedName(String qname) { int pos = qname.indexOf(":"); if (pos < 0) return qname; else return qname.substring(pos + 1); } //--------------------------------------------------------------------------- private String getProfile(String name) { int pos = name.indexOf("."); if (pos < 0) return ""; else return name.substring(pos+1); } }
diff --git a/src/ibis/ipl/impl/Ibis.java b/src/ibis/ipl/impl/Ibis.java index 14e0c2d5..33bccac8 100644 --- a/src/ibis/ipl/impl/Ibis.java +++ b/src/ibis/ipl/impl/Ibis.java @@ -1,550 +1,550 @@ /* $Id$ */ package ibis.ipl.impl; import ibis.io.IbisIOException; import ibis.ipl.IbisCapabilities; import ibis.ipl.IbisConfigurationException; import ibis.ipl.IbisProperties; import ibis.ipl.MessageUpcall; import ibis.ipl.NoSuchPropertyException; import ibis.ipl.PortType; import ibis.ipl.ReceivePortConnectUpcall; import ibis.ipl.RegistryEventHandler; import ibis.ipl.SendPortDisconnectUpcall; import ibis.util.TypedProperties; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; /** * This implementation of the {@link ibis.ipl.Ibis} interface is a base class, * to be extended by specific Ibis implementations. */ public abstract class Ibis implements ibis.ipl.Ibis { /** Debugging output. */ private static final Logger logger = Logger.getLogger("ibis.ipl.impl.Ibis"); /** The IbisCapabilities as specified by the user. */ public final IbisCapabilities capabilities; /** List of port types given by the user */ public final PortType[] portTypes; /** * Properties, as given to * {@link ibis.ipl.IbisFactory#createIbis(IbisCapabilities, Properties, * boolean, RegistryEventHandler, PortType...)}. */ protected TypedProperties properties; /** The Ibis registry. */ private final Registry registry; /** Identifies this Ibis instance in the registry. */ public final IbisIdentifier ident; /** Set when {@link #end()} is called. */ private boolean ended = false; /** The receiveports running on this Ibis instance. */ private HashMap<String, ReceivePort> receivePorts; /** The sendports running on this Ibis instance. */ private HashMap<String, SendPort> sendPorts; /** Counter for allocating names for anonymous sendports. */ private static int send_counter = 0; /** Counter for allocating names for anonymous receiveports. */ private static int receive_counter = 0; /** Total number of messages send by closed send ports */ private long outgoingMessageCount = 0; /** Total number of messages received by closed receive ports */ private long incomingMessageCount = 0; /** Total number of bytes written to messages closed send ports */ private long bytesWritten = 0; /** Total number of bytes send by closed send ports */ private long bytesSend = 0; /** Total number of bytes read by closed receive ports */ private long bytesReceived = 0; /** Total number of bytes read from messages (for closed received ports) */ private long bytesRead = 0; /** * Constructs an <code>Ibis</code> instance with the specified parameters. * * @param registryHandler * the registryHandler. * @param capabilities * the capabilities. * @param portTypes * the port types requested for this ibis implementation. * @param userProperties * the properties as provided by the Ibis factory. */ protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, PortType[] portTypes, Properties userProperties) { this.capabilities = capabilities; this.portTypes = portTypes; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); Class<? extends Ibis> thisClass = this.getClass(); Package thisPackage = thisClass.getPackage(); String implementationVersionString; // Did we manage to get a package? if (null != thisPackage) { implementationVersionString = "Class: " + thisClass.getName() + "." + thisPackage.getName() + " Build: " + thisPackage.getImplementationVersion(); } else { - implementationVersionString = "Class: " + thisClass.getName(); + implementationVersionString = "Class: " + thisClass.getName(); } try { registry = Registry.createRegistry(capabilities, registryHandler, properties, getData(), implementationVersionString); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisConfigurationException("Could not create registry", e); } ident = registry.getIbisIdentifier(); } public Registry registry() { return registry; } public ibis.ipl.IbisIdentifier identifier() { return ident; } public Properties properties() { return new Properties(properties); } /** * Returns the current Ibis version. * * @return the ibis version. */ public String getVersion() { InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("VERSION"); String version = "Unknown Ibis Version ID"; if (in != null) { BufferedReader bIn = new BufferedReader(new InputStreamReader(in)); try { version = "Ibis Version ID " + bIn.readLine(); bIn.close(); } catch (Exception e) { // Ignored } } return version + ", implementation = " + this.getClass().getName(); } public void end() throws IOException { synchronized (this) { if (ended) { return; } ended = true; } try { registry.leave(); } catch (Throwable e) { throw new IbisIOException("Registry: leave failed ", e); } quit(); } public void poll() { // Default has empty implementation. } synchronized void register(ReceivePort p) throws IOException { if (receivePorts.get(p.name) != null) { throw new IOException("Multiple instances of receiveport named " + p.name); } receivePorts.put(p.name, p); } synchronized void deRegister(ReceivePort p) { if (receivePorts.remove(p.name) != null) { // add statistics for this receive port to "total" statistics incomingMessageCount += p.getMessageCount(); bytesReceived += p.getBytesReceived(); bytesRead += p.getBytesRead(); } } synchronized void register(SendPort p) throws IOException { if (sendPorts.get(p.name) != null) { throw new IOException("Multiple instances of sendport named " + p.name); } sendPorts.put(p.name, p); } synchronized void deRegister(SendPort p) { if (sendPorts.remove(p.name) != null) { // add statistics for this sendport to "total" statistics outgoingMessageCount += p.getMessageCount(); bytesSend += p.getBytesSend(); bytesWritten += p.getBytesWritten(); } } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Public methods, may called by Ibis implementations. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * Returns the receiveport with the specified name, or <code>null</code> * if not present. * * @param name * the name of the receiveport. * @return the receiveport. */ public synchronized ReceivePort findReceivePort(String name) { return receivePorts.get(name); } /** * Returns the sendport with the specified name, or <code>null</code> if * not present. * * @param name * the name of the sendport. * @return the sendport. */ public synchronized SendPort findSendPort(String name) { return sendPorts.get(name); } public ReceivePortIdentifier createReceivePortIdentifier(String name, IbisIdentifier id) { return new ReceivePortIdentifier(name, id); } public SendPortIdentifier createSendPortIdentifier(String name, IbisIdentifier id) { return new SendPortIdentifier(name, id); } // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Protected methods, to be implemented by Ibis implementations. // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * Implementation-dependent part of the {@link #end()} implementation. */ protected abstract void quit(); /** * This method should provide the implementation-dependent data of the Ibis * identifier for this Ibis instance. This method gets called from the Ibis * constructor. * * @exception IOException * may be thrown in case of trouble. * @return the implementation-dependent data, as a byte array. */ protected abstract byte[] getData() throws IOException; public ibis.ipl.SendPort createSendPort(PortType tp) throws IOException { return createSendPort(tp, null, null, null); } public ibis.ipl.SendPort createSendPort(PortType tp, String name) throws IOException { return createSendPort(tp, name, null, null); } private void matchPortType(PortType tp) { boolean matched = false; for (PortType p : portTypes) { if (tp.equals(p)) { matched = true; } } if (!matched) { throw new IbisConfigurationException("PortType " + tp + " not specified when creating this Ibis instance"); } } public ibis.ipl.SendPort createSendPort(PortType tp, String name, SendPortDisconnectUpcall cU, Properties properties) throws IOException { if (cU != null) { if (!tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "no connection upcalls requested for this port type"); } } if (name == null) { synchronized (this.getClass()) { name = "anonymous send port " + send_counter++; } } matchPortType(tp); return doCreateSendPort(tp, name, cU, properties); } /** * Creates a {@link ibis.ipl.SendPort} of the specified port type. * * @param tp * the port type. * @param name * the name of this sendport. * @param cU * object implementing the * {@link SendPortDisconnectUpcall#lostConnection(ibis.ipl.SendPort, * ReceivePortIdentifier, Throwable)} method. * @param properties * the port properties. * @return the new sendport. * @exception java.io.IOException * is thrown when the port could not be created. */ protected abstract ibis.ipl.SendPort doCreateSendPort(PortType tp, String name, SendPortDisconnectUpcall cU, Properties properties) throws IOException; public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name) throws IOException { return createReceivePort(tp, name, null, null, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, MessageUpcall u) throws IOException { return createReceivePort(tp, name, u, null, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, ReceivePortConnectUpcall cU) throws IOException { return createReceivePort(tp, name, null, cU, null); } public ibis.ipl.ReceivePort createReceivePort(PortType tp, String name, MessageUpcall u, ReceivePortConnectUpcall cU, Properties properties) throws IOException { if (cU != null) { if (!tp.hasCapability(PortType.CONNECTION_UPCALLS)) { throw new IbisConfigurationException( "no connection upcalls requested for this port type"); } } if (u != null) { if (!tp.hasCapability(PortType.RECEIVE_AUTO_UPCALLS) && !tp.hasCapability(PortType.RECEIVE_POLL_UPCALLS)) { throw new IbisConfigurationException( "no message upcalls requested for this port type"); } } else { if (!tp.hasCapability(PortType.RECEIVE_EXPLICIT)) { throw new IbisConfigurationException( "no explicit receive requested for this port type"); } } if (name == null) { synchronized (this.getClass()) { name = "anonymous receive port " + receive_counter++; } } matchPortType(tp); return doCreateReceivePort(tp, name, u, cU, properties); } /** * Creates a named {@link ibis.ipl.ReceivePort} of the specified port type, * with upcall based communication. New connections will not be accepted * until {@link ibis.ipl.ReceivePort#enableConnections()} is invoked. This * is done to avoid upcalls during initialization. When a new connection * request arrives, or when a connection is lost, a ConnectUpcall is * performed. * * @param tp * the port type. * @param name * the name of this receiveport. * @param u * the upcall handler. * @param cU * object implementing <code>gotConnection</code>() and * <code>lostConnection</code>() upcalls. * @param properties * the port properties. * @return the new receiveport. * @exception java.io.IOException * is thrown when the port could not be created. */ protected abstract ibis.ipl.ReceivePort doCreateReceivePort(PortType tp, String name, MessageUpcall u, ReceivePortConnectUpcall cU, Properties properties) throws IOException; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Protected management methods, can be overriden/used in implementations // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public String getManagementProperty(String key) throws NoSuchPropertyException { String result = managementProperties().get(key); if (result == null) { throw new NoSuchPropertyException("property \"" + key + "\" not found"); } return result; } private synchronized long outgoingMessageCount() { long outgoingMessageCount = this.outgoingMessageCount; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { outgoingMessageCount += sendPort.getMessageCount(); } return outgoingMessageCount; } private synchronized long bytesSend() { long bytesSend = this.bytesSend; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { bytesSend += sendPort.getBytesSend(); } return bytesSend; } private synchronized long bytesWritten() { long bytesWritten = this.bytesWritten; // also add numbers for current send ports for (SendPort sendPort : sendPorts.values()) { bytesWritten += sendPort.getBytesWritten(); } return bytesWritten; } private synchronized long incomingMessageCount() { long incomingMessageCount = this.incomingMessageCount; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { incomingMessageCount += receivePort.getMessageCount(); } return incomingMessageCount; } private synchronized long bytesReceived() { long bytesReceived = this.bytesReceived; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { bytesReceived += receivePort.getBytesReceived(); } return bytesReceived; } private synchronized long bytesRead() { long bytesRead = this.bytesRead; // also add numbers for current receive ports for (ReceivePort receivePort : receivePorts.values()) { bytesRead += receivePort.getBytesReceived(); } return bytesRead; } public synchronized Map<String, String> managementProperties() { Map<String, String> result = new HashMap<String, String>(); // put gathered statistics in the map result.put("outgoingMessageCount", "" + outgoingMessageCount()); result.put("bytesWritten", "" + bytesWritten()); result.put("bytesSend", "" + bytesSend()); result.put("incomingMessageCount", "" + incomingMessageCount()); result.put("bytesReceived", "" + bytesReceived()); result.put("bytesRead", "" + bytesRead()); return result; } public void printManagementProperties(PrintStream stream) { stream.format("Messages Send: %d\n", outgoingMessageCount()); double mbWritten = (double) bytesWritten() / 1024.0 / 1024.0; stream.format("Data written to messages: %.2f Mb\n", mbWritten); double mbSend = (double) bytesSend() / 1024.0 / 1024.0; stream.format("Data send out on network: %.2f Mb\n", mbSend); stream.format("Messages Received: %d\n", incomingMessageCount()); double mbReceived = (double) bytesReceived() / 1024.0 / 1024.0; stream.format("Data received from network: %.2f Mb\n", mbReceived); double mbRead = (double) bytesRead() / 1024.0 / 1024.0; stream.format("Data read from messages: %.2f Mb\n", mbRead); stream.flush(); } public void setManagementProperties(Map<String, String> properties) throws NoSuchPropertyException { // override if an Ibis _can_ set properties throw new NoSuchPropertyException("cannot set any properties"); } public void setManagementProperty(String key, String value) throws NoSuchPropertyException { // override if an Ibis _can_ set properties throw new NoSuchPropertyException("cannot set any properties"); } }
true
true
protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, PortType[] portTypes, Properties userProperties) { this.capabilities = capabilities; this.portTypes = portTypes; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); Class<? extends Ibis> thisClass = this.getClass(); Package thisPackage = thisClass.getPackage(); String implementationVersionString; // Did we manage to get a package? if (null != thisPackage) { implementationVersionString = "Class: " + thisClass.getName() + "." + thisPackage.getName() + " Build: " + thisPackage.getImplementationVersion(); } else { implementationVersionString = "Class: " + thisClass.getName(); } try { registry = Registry.createRegistry(capabilities, registryHandler, properties, getData(), implementationVersionString); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisConfigurationException("Could not create registry", e); } ident = registry.getIbisIdentifier(); }
protected Ibis(RegistryEventHandler registryHandler, IbisCapabilities capabilities, PortType[] portTypes, Properties userProperties) { this.capabilities = capabilities; this.portTypes = portTypes; this.properties = new TypedProperties(); // bottom up add properties, starting with hard coded ones properties.addProperties(IbisProperties.getHardcodedProperties()); properties.addProperties(userProperties); if (logger.isDebugEnabled()) { logger.debug("Ibis constructor: properties = " + properties); } receivePorts = new HashMap<String, ReceivePort>(); sendPorts = new HashMap<String, SendPort>(); Class<? extends Ibis> thisClass = this.getClass(); Package thisPackage = thisClass.getPackage(); String implementationVersionString; // Did we manage to get a package? if (null != thisPackage) { implementationVersionString = "Class: " + thisClass.getName() + "." + thisPackage.getName() + " Build: " + thisPackage.getImplementationVersion(); } else { implementationVersionString = "Class: " + thisClass.getName(); } try { registry = Registry.createRegistry(capabilities, registryHandler, properties, getData(), implementationVersionString); } catch (IbisConfigurationException e) { throw e; } catch (Throwable e) { throw new IbisConfigurationException("Could not create registry", e); } ident = registry.getIbisIdentifier(); }
diff --git a/packages/SystemUI/src/com/android/systemui/SearchPanelView.java b/packages/SystemUI/src/com/android/systemui/SearchPanelView.java index df8175e6..6c9a616d 100644 --- a/packages/SystemUI/src/com/android/systemui/SearchPanelView.java +++ b/packages/SystemUI/src/com/android/systemui/SearchPanelView.java @@ -1,645 +1,645 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.systemui; import android.animation.LayoutTransition; import android.app.ActivityOptions; import android.app.AlertDialog; import android.app.Dialog; import android.app.KeyguardManager; import android.app.SearchManager; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.ActivityManagerNative; import android.app.IActivityManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.res.Configuration; import android.content.Context; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.res.Resources; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.ActivityInfo; import android.content.pm.ActivityInfo; import android.content.ServiceConnection; import android.database.ContentObserver; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.StateListDrawable; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.Vibrator; import android.os.Handler; import android.os.IBinder; import android.os.SystemClock; import android.os.PowerManager; import android.os.Process; import android.os.ServiceManager; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.os.ServiceManager; import android.os.UserHandle; import android.os.Vibrator; import android.provider.Settings; import android.text.TextUtils; import android.util.AttributeSet; import android.util.ExtendedPropertiesUtils; import android.util.Slog; import android.util.Log; import android.view.HapticFeedbackConstants; import android.view.IWindowManager; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnPreDrawListener; import android.widget.FrameLayout; import android.widget.RelativeLayout; import android.widget.Toast; import static com.android.internal.util.aokp.AwesomeConstants.*; import com.android.internal.util.aokp.NavRingHelpers; import com.android.internal.widget.multiwaveview.GlowPadView; import com.android.internal.widget.multiwaveview.GlowPadView.OnTriggerListener; import com.android.internal.widget.multiwaveview.TargetDrawable; import com.android.systemui.R; import com.android.systemui.recent.StatusBarTouchProxy; import com.android.systemui.statusbar.BaseStatusBar; import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.phone.PhoneStatusBar; import com.android.systemui.statusbar.tablet.StatusBarPanel; import com.android.systemui.statusbar.tablet.TabletStatusBar; import com.android.systemui.aokp.AwesomeAction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.net.URISyntaxException; public class SearchPanelView extends FrameLayout implements StatusBarPanel, ActivityOptions.OnAnimationStartedListener { private static final int SEARCH_PANEL_HOLD_DURATION = 0; static final String TAG = "SearchPanelView"; static final boolean DEBUG = TabletStatusBar.DEBUG || PhoneStatusBar.DEBUG || false; private final Context mContext; private BaseStatusBar mBar; private StatusBarTouchProxy mStatusBarTouchProxy; private boolean mShowing; private View mSearchTargetsContainer; private GlowPadView mGlowPadView; private IWindowManager mWm; private PackageManager mPackageManager; private Resources mResources; private SettingsObserver mSettingsObserver; private TargetObserver mTargetObserver; private ContentResolver mContentResolver; private String[] targetActivities = new String[5]; private String[] longActivities = new String[5]; private String[] customIcons = new String[5]; private int startPosOffset; private int mNavRingAmount; private boolean mLefty; private boolean mBoolLongPress; private boolean mSearchPanelLock; private int mTarget; private boolean mLongPress = false; public int mSystemUiLayout = ExtendedPropertiesUtils.getActualProperty("com.android.systemui.layout"); //need to make an intent list and an intent counter String[] intent; ArrayList<String> intentList = new ArrayList<String>(); ArrayList<String> longList = new ArrayList<String>(); public SearchPanelView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SearchPanelView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); mPackageManager = mContext.getPackageManager(); mResources = mContext.getResources(); mContentResolver = mContext.getContentResolver(); mSettingsObserver = new SettingsObserver(new Handler()); updateSettings(); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mSettingsObserver.observe(); updateSettings(); } @Override protected void onDetachedFromWindow() { mContentResolver.unregisterContentObserver(mSettingsObserver); super.onDetachedFromWindow(); } private void startAssistActivity() { if (!mBar.isDeviceProvisioned()) return; // Close Recent Apps if needed mBar.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_SEARCH_PANEL); boolean isKeyguardShowing = false; try { isKeyguardShowing = mWm.isKeyguardLocked(); } catch (RemoteException e) { } if (isKeyguardShowing) { // Have keyguard show the bouncer and launch the activity if the user succeeds. try { mWm.showAssistant(); } catch (RemoteException e) { // too bad, so sad... } onAnimationStarted(); } else { // Otherwise, keyguard isn't showing so launch it from here. Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE)) .getAssistIntent(mContext, UserHandle.USER_CURRENT); if (intent == null) return; try { ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity(); } catch (RemoteException e) { // too bad, so sad... } try { ActivityOptions opts = ActivityOptions.makeCustomAnimation(mContext, R.anim.search_launch_enter, R.anim.search_launch_exit, getHandler(), this); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivityAsUser(intent, opts.toBundle(), new UserHandle(UserHandle.USER_CURRENT)); } catch (ActivityNotFoundException e) { Slog.w(TAG, "Activity not found for " + intent.getAction()); onAnimationStarted(); } } } private class H extends Handler { public void handleMessage(Message m) { switch (m.what) { } } } private H mHandler = new H(); class GlowPadTriggerListener implements GlowPadView.OnTriggerListener { boolean mWaitingForLaunch; final Runnable SetLongPress = new Runnable () { public void run() { if (!mSearchPanelLock) { mLongPress = true; Log.d(TAG,"LongPress!"); mBar.hideSearchPanel(); maybeSkipKeyguard(); AwesomeAction.launchAction(mContext, longList.get(mTarget)); mSearchPanelLock = true; } } }; public void onGrabbed(View v, int handle) { mSearchPanelLock = false; } public void onReleased(View v, int handle) { } public void onTargetChange(View v, final int target) { if (target == -1) { mHandler.removeCallbacks(SetLongPress); mLongPress = false; } else { if (mBoolLongPress && !TextUtils.isEmpty(longList.get(target)) && !longList.get(target).equals(AwesomeConstant.ACTION_NULL.value())) { mTarget = target; mHandler.postDelayed(SetLongPress, ViewConfiguration.getLongPressTimeout()); } } } public void onGrabbedStateChange(View v, int handle) { if (!mWaitingForLaunch && OnTriggerListener.NO_HANDLE == handle) { mBar.hideSearchPanel(); mHandler.removeCallbacks(SetLongPress); mLongPress = false; } } public void onTrigger(View v, final int target) { mTarget = target; if (!mLongPress) { if (AwesomeConstant.ACTION_ASSIST.equals(intentList.get(target))) { startAssistActivity(); } else { maybeSkipKeyguard(); AwesomeAction.launchAction(mContext, intentList.get(target)); } mHandler.removeCallbacks(SetLongPress); } } public void onFinishFinalAnimation() { } } final GlowPadTriggerListener mGlowPadViewListener = new GlowPadTriggerListener(); @Override public void onAnimationStarted() { postDelayed(new Runnable() { public void run() { mGlowPadViewListener.mWaitingForLaunch = false; mBar.hideSearchPanel(); } }, SEARCH_PANEL_HOLD_DURATION); } @Override protected void onFinishInflate() { super.onFinishInflate(); mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSearchTargetsContainer = findViewById(R.id.search_panel_container); mStatusBarTouchProxy = (StatusBarTouchProxy) findViewById(R.id.status_bar_touch_proxy); // TODO: fetch views mGlowPadView = (GlowPadView) findViewById(R.id.glow_pad_view); mGlowPadView.setOnTriggerListener(mGlowPadViewListener); updateSettings(); setDrawables(); } private void maybeSkipKeyguard() { try { if (mWm.isKeyguardLocked() && !mWm.isKeyguardSecure()) { ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity(); } } catch (RemoteException ignored) { } } private void setDrawables() { mLongPress = false; mSearchPanelLock = false; String target3 = Settings.System.getString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0]); if (target3 == null || target3.equals("")) { Settings.System.putString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0], AwesomeConstant.ACTION_ASSIST.value()); } // Custom Targets ArrayList<TargetDrawable> storedDraw = new ArrayList<TargetDrawable>(); int endPosOffset = 0; int middleBlanks = 0; if (mSystemUiLayout >= 1000) { // Tablet UI if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = (mNavRingAmount) + 1; endPosOffset = (mNavRingAmount * 2) + 1; } else { // righty... (Ring actually on left side of tablet) startPosOffset = 1; endPosOffset = (mNavRingAmount * 3) + 1; } } else if (mSystemUiLayout >= 600) { // Phablet UI - Search Ring stays at bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else { // Phone UI if (isScreenPortrait()) { // NavRing on Bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = 1 - (mNavRingAmount % 2); middleBlanks = mNavRingAmount + 2; endPosOffset = 0; } else { // righty... (Ring actually on left side of tablet) startPosOffset = (Math.min(1,mNavRingAmount / 2)) + 2; endPosOffset = startPosOffset - 1; } } intentList.clear(); longList.clear(); int middleStart = mNavRingAmount; int tqty = middleStart; int middleFinish = 0; if (middleBlanks > 0) { middleStart = (tqty/2) + (tqty%2); middleFinish = (tqty/2); } // Add Initial Place Holder Targets for (int i = 0; i < startPosOffset; i++) { - storedDraw.add(getTargetDrawable("")); - intentList.add(mEmpty); - longList.add(mEmpty); + storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); + intentList.add(AwesomeConstant.ACTION_NULL.value()); + longList.add(AwesomeConstant.ACTION_NULL.value()); } // Add User Targets for (int i = 0; i < middleStart; i++) { intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add middle Place Holder Targets for (int j = 0; j < middleBlanks; j++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } // Add Rest of User Targets for leftys for (int j = 0; j < middleFinish; j++) { int i = j + middleStart; intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add End Place Holder Targets for (int i = 0; i < endPosOffset; i++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } mGlowPadView.setTargetResources(storedDraw); } private void maybeSwapSearchIcon() { Intent intent = ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE)) .getAssistIntent(mContext, UserHandle.USER_CURRENT); if (intent != null) { ComponentName component = intent.getComponent(); if (component == null || !mGlowPadView.replaceTargetDrawablesIfPresent(component, ASSIST_ICON_METADATA_NAME, com.android.internal.R.drawable.ic_action_assist_generic)) { if (DEBUG) Slog.v(TAG, "Couldn't grab icon for component " + component); } } } private boolean pointInside(int x, int y, View v) { final int l = v.getLeft(); final int r = v.getRight(); final int t = v.getTop(); final int b = v.getBottom(); return x >= l && x < r && y >= t && y < b; } public boolean isInContentArea(int x, int y) { if (pointInside(x, y, mSearchTargetsContainer)) { return true; } else if (mStatusBarTouchProxy != null && pointInside(x, y, mStatusBarTouchProxy)) { return true; } else { return false; } } private final OnPreDrawListener mPreDrawListener = new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { getViewTreeObserver().removeOnPreDrawListener(this); mGlowPadView.resumeAnimations(); return false; } }; private void vibrate() { Context context = getContext(); if (Settings.System.getIntForUser(context.getContentResolver(), Settings.System.HAPTIC_FEEDBACK_ENABLED, 1, UserHandle.USER_CURRENT) != 0) { Resources res = context.getResources(); Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(res.getInteger(R.integer.config_search_panel_view_vibration_duration)); } } private boolean hasValidTargets() { for (String target : targetActivities) { if (!TextUtils.isEmpty(target) && !target.equals(AwesomeConstant.ACTION_NULL.value())) { return true; } } return false; } public void show(final boolean show, boolean animate) { if (!show) { final LayoutTransition transitioner = animate ? createLayoutTransitioner() : null; ((ViewGroup) mSearchTargetsContainer).setLayoutTransition(transitioner); } mShowing = show; if (show && hasValidTargets()) { maybeSwapSearchIcon(); if (getVisibility() != View.VISIBLE) { setVisibility(View.VISIBLE); // Don't start the animation until we've created the layer, which is done // right before we are drawn mGlowPadView.suspendAnimations(); mGlowPadView.ping(); getViewTreeObserver().addOnPreDrawListener(mPreDrawListener); vibrate(); } setFocusable(true); setFocusableInTouchMode(true); requestFocus(); } else { setVisibility(View.INVISIBLE); } } public void hide(boolean animate) { if (mBar != null) { // This will indirectly cause show(false, ...) to get called mBar.animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE); } else { setVisibility(View.INVISIBLE); } } /** * We need to be aligned at the bottom. LinearLayout can't do this, so instead, * let LinearLayout do all the hard work, and then shift everything down to the bottom. */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); // setPanelHeight(mSearchTargetsContainer.getHeight()); } @Override public boolean dispatchHoverEvent(MotionEvent event) { // Ignore hover events outside of this panel bounds since such events // generate spurious accessibility events with the panel content when // tapping outside of it, thus confusing the user. final int x = (int) event.getX(); final int y = (int) event.getY(); if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { return super.dispatchHoverEvent(event); } return true; } /** * Whether the panel is showing, or, if it's animating, whether it will be * when the animation is done. */ public boolean isShowing() { return mShowing; } public void setBar(BaseStatusBar bar) { mBar = bar; } public void setStatusBarView(final View statusBarView) { if (mStatusBarTouchProxy != null) { mStatusBarTouchProxy.setStatusBar(statusBarView); // mGlowPadView.setOnTouchListener(new OnTouchListener() { // public boolean onTouch(View v, MotionEvent event) { // return statusBarView.onTouchEvent(event); // } // }); } } private LayoutTransition createLayoutTransitioner() { LayoutTransition transitioner = new LayoutTransition(); transitioner.setDuration(200); transitioner.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0); transitioner.setAnimator(LayoutTransition.DISAPPEARING, null); return transitioner; } public boolean isAssistantAvailable() { return ((SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE)) .getAssistIntent(mContext, UserHandle.USER_CURRENT) != null; } public int screenLayout() { final int screenSize = Resources.getSystem().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; return screenSize; } public boolean isScreenPortrait() { return mResources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT; } public class TargetObserver extends ContentObserver { public TargetObserver(Handler handler) { super(handler); } @Override public boolean deliverSelfNotifications() { return super.deliverSelfNotifications(); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); setDrawables(); updateSettings(); } } class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.NAVIGATION_BAR_LEFTY_MODE), false, this); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SYSTEMUI_NAVRING_AMOUNT), false, this); resolver.registerContentObserver(Settings.System.getUriFor( Settings.System.SYSTEMUI_NAVRING_LONG_ENABLE), false, this); for (int i = 0; i < 5; i++) { resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.SYSTEMUI_NAVRING[i]), false, this); resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.SYSTEMUI_NAVRING_LONG[i]), false, this); resolver.registerContentObserver( Settings.System.getUriFor(Settings.System.SYSTEMUI_NAVRING_ICON[i]), false, this); } } void unobserve() { mContext.getContentResolver().unregisterContentObserver(this); } @Override public void onChange(boolean selfChange) { updateSettings(); setDrawables(); } } public void updateSettings() { for (int i = 0; i < 5; i++) { targetActivities[i] = Settings.System.getString( mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[i]); longActivities[i] = Settings.System.getString( mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING_LONG[i]); customIcons[i] = Settings.System.getString( mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING_ICON[i]); } mLefty = (Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.NAVIGATION_BAR_LEFTY_MODE, false)); mBoolLongPress = (Settings.System.getBoolean(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING_LONG_ENABLE, false)); mNavRingAmount = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING_AMOUNT, 1); } }
true
true
private void setDrawables() { mLongPress = false; mSearchPanelLock = false; String target3 = Settings.System.getString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0]); if (target3 == null || target3.equals("")) { Settings.System.putString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0], AwesomeConstant.ACTION_ASSIST.value()); } // Custom Targets ArrayList<TargetDrawable> storedDraw = new ArrayList<TargetDrawable>(); int endPosOffset = 0; int middleBlanks = 0; if (mSystemUiLayout >= 1000) { // Tablet UI if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = (mNavRingAmount) + 1; endPosOffset = (mNavRingAmount * 2) + 1; } else { // righty... (Ring actually on left side of tablet) startPosOffset = 1; endPosOffset = (mNavRingAmount * 3) + 1; } } else if (mSystemUiLayout >= 600) { // Phablet UI - Search Ring stays at bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else { // Phone UI if (isScreenPortrait()) { // NavRing on Bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = 1 - (mNavRingAmount % 2); middleBlanks = mNavRingAmount + 2; endPosOffset = 0; } else { // righty... (Ring actually on left side of tablet) startPosOffset = (Math.min(1,mNavRingAmount / 2)) + 2; endPosOffset = startPosOffset - 1; } } intentList.clear(); longList.clear(); int middleStart = mNavRingAmount; int tqty = middleStart; int middleFinish = 0; if (middleBlanks > 0) { middleStart = (tqty/2) + (tqty%2); middleFinish = (tqty/2); } // Add Initial Place Holder Targets for (int i = 0; i < startPosOffset; i++) { storedDraw.add(getTargetDrawable("")); intentList.add(mEmpty); longList.add(mEmpty); } // Add User Targets for (int i = 0; i < middleStart; i++) { intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add middle Place Holder Targets for (int j = 0; j < middleBlanks; j++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } // Add Rest of User Targets for leftys for (int j = 0; j < middleFinish; j++) { int i = j + middleStart; intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add End Place Holder Targets for (int i = 0; i < endPosOffset; i++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } mGlowPadView.setTargetResources(storedDraw); }
private void setDrawables() { mLongPress = false; mSearchPanelLock = false; String target3 = Settings.System.getString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0]); if (target3 == null || target3.equals("")) { Settings.System.putString(mContext.getContentResolver(), Settings.System.SYSTEMUI_NAVRING[0], AwesomeConstant.ACTION_ASSIST.value()); } // Custom Targets ArrayList<TargetDrawable> storedDraw = new ArrayList<TargetDrawable>(); int endPosOffset = 0; int middleBlanks = 0; if (mSystemUiLayout >= 1000) { // Tablet UI if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = (mNavRingAmount) + 1; endPosOffset = (mNavRingAmount * 2) + 1; } else { // righty... (Ring actually on left side of tablet) startPosOffset = 1; endPosOffset = (mNavRingAmount * 3) + 1; } } else if (mSystemUiLayout >= 600) { // Phablet UI - Search Ring stays at bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else { // Phone UI if (isScreenPortrait()) { // NavRing on Bottom startPosOffset = 1; endPosOffset = (mNavRingAmount) + 1; } else if (mLefty) { // either lefty or... (Ring is actually on right side of screen) startPosOffset = 1 - (mNavRingAmount % 2); middleBlanks = mNavRingAmount + 2; endPosOffset = 0; } else { // righty... (Ring actually on left side of tablet) startPosOffset = (Math.min(1,mNavRingAmount / 2)) + 2; endPosOffset = startPosOffset - 1; } } intentList.clear(); longList.clear(); int middleStart = mNavRingAmount; int tqty = middleStart; int middleFinish = 0; if (middleBlanks > 0) { middleStart = (tqty/2) + (tqty%2); middleFinish = (tqty/2); } // Add Initial Place Holder Targets for (int i = 0; i < startPosOffset; i++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } // Add User Targets for (int i = 0; i < middleStart; i++) { intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add middle Place Holder Targets for (int j = 0; j < middleBlanks; j++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } // Add Rest of User Targets for leftys for (int j = 0; j < middleFinish; j++) { int i = j + middleStart; intentList.add(targetActivities[i]); longList.add(longActivities[i]); if (!TextUtils.isEmpty(customIcons[i])) { storedDraw.add(NavRingHelpers.getCustomDrawable(mContext, customIcons[i])); } else { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, targetActivities[i])); } } // Add End Place Holder Targets for (int i = 0; i < endPosOffset; i++) { storedDraw.add(NavRingHelpers.getTargetDrawable(mContext, null)); intentList.add(AwesomeConstant.ACTION_NULL.value()); longList.add(AwesomeConstant.ACTION_NULL.value()); } mGlowPadView.setTargetResources(storedDraw); }
diff --git a/ide/eclipse/registry/org.wso2.developerstudio.eclipse.artifact.registry/src/org/wso2/developerstudio/eclipse/artifact/registry/project/export/RegistryArtifactHandler.java b/ide/eclipse/registry/org.wso2.developerstudio.eclipse.artifact.registry/src/org/wso2/developerstudio/eclipse/artifact/registry/project/export/RegistryArtifactHandler.java index fb869f345..b059d05bc 100755 --- a/ide/eclipse/registry/org.wso2.developerstudio.eclipse.artifact.registry/src/org/wso2/developerstudio/eclipse/artifact/registry/project/export/RegistryArtifactHandler.java +++ b/ide/eclipse/registry/org.wso2.developerstudio.eclipse.artifact.registry/src/org/wso2/developerstudio/eclipse/artifact/registry/project/export/RegistryArtifactHandler.java @@ -1,151 +1,154 @@ /* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.artifact.registry.project.export; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.NullProgressMonitor; import org.wso2.developerstudio.eclipse.artifact.registry.Activator; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; import org.wso2.developerstudio.eclipse.platform.core.project.export.ProjectArtifactHandler; import org.wso2.developerstudio.eclipse.platform.core.utils.XMLUtil; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; public class RegistryArtifactHandler extends ProjectArtifactHandler { private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); public static final String ARTIFACT_XML = "artifact.xml"; public static final String GENERAL_PROJECT_NATURE = "org.wso2.developerstudio.eclipse.general.project.nature"; List<IResource> exportResources = new ArrayList<IResource>(); public List<IResource> exportArtifact(IProject project) throws Exception { if (project.hasNature(GENERAL_PROJECT_NATURE)) { NullProgressMonitor nullProgressMonitor = new NullProgressMonitor(); project.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor); IFile RegistryResourceFile = project.getFile(ARTIFACT_XML); IFolder binaries = project.getFolder("target"); if (!binaries.exists()) { binaries.create(true, true, nullProgressMonitor); binaries.setHidden(true); } else{ clearTarget(project); } + project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); IFolder registryResources = binaries.getFolder("registry_resources"); if (registryResources.exists()) { FileUtils.deleteDirectories(registryResources.getLocation().toFile()); } registryResources.create(false, true, nullProgressMonitor); project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); if (RegistryResourceFile.exists()) { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( RegistryResourceFile.getContents()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); Iterator artifacts = documentElement.getChildElements(); while (artifacts.hasNext()) { Object o = artifacts.next(); if (o instanceof OMElement) { OMElement artifact = (OMElement) o; if ("artifact".equals(artifact.getLocalName())) { String name = artifact.getAttributeValue(new QName("name")); String version = artifact.getAttributeValue(new QName("version")); String type = artifact.getAttributeValue(new QName("type")); if ("registry/resource".equals(type)) { IFolder resourceArtifact = registryResources.getFolder(String .format("%s_%s", name, version)); resourceArtifact.create(true, true, nullProgressMonitor); IFolder resourcesDir = resourceArtifact.getFolder("resources"); resourcesDir.create(true, true, nullProgressMonitor); OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement resourcesEl = factory.createOMElement(new QName( "resources")); Iterator items = artifact.getChildElements(); while (items.hasNext()) { Object obj = items.next(); if (obj instanceof OMElement) { OMElement item = (OMElement) obj; if ("item".equals(item.getLocalName()) || "dump".equals(item.getLocalName())) { OMElement fileEl = item.getFirstChildWithName(new QName("file")); String fileName = fileEl.getText(); IFile regItem = project.getFile(fileName); if (regItem.exists()) { FileUtils.copy(regItem.getLocation().toFile(), new File(resourcesDir.getLocation() .toFile(), regItem.getName())); } fileEl.setText(regItem.getName()); resourcesEl.addChild(item); } else if ("collection".equals(item.getLocalName())) { OMElement collectionEl = item.getFirstChildWithName( new QName("directory")); String dir = collectionEl.getText(); IFolder regCollection = project.getFolder(dir); if (regCollection.exists()) { FileUtils.copyDirectory(regCollection .getLocation().toFile(), new File(resourcesDir .getLocation().toFile(),regCollection.getName())); } collectionEl.setText(regCollection.getName()); resourcesEl.addChild(item); } else{ log.warn("unknown resource type '" + item.getLocalName() + "'; skipping"); } } } IFile registryInfo = resourceArtifact .getFile("registry-info.xml"); - XMLUtil.prettify(resourcesEl, new FileOutputStream(registryInfo - .getLocation().toFile())); + FileOutputStream out = new FileOutputStream(registryInfo + .getLocation().toFile()); + XMLUtil.prettify(resourcesEl, out); + out.close(); exportResources.add((IResource) resourceArtifact); } } } project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); } builder.close(); parser.close(); } } return exportResources; } }
false
true
public List<IResource> exportArtifact(IProject project) throws Exception { if (project.hasNature(GENERAL_PROJECT_NATURE)) { NullProgressMonitor nullProgressMonitor = new NullProgressMonitor(); project.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor); IFile RegistryResourceFile = project.getFile(ARTIFACT_XML); IFolder binaries = project.getFolder("target"); if (!binaries.exists()) { binaries.create(true, true, nullProgressMonitor); binaries.setHidden(true); } else{ clearTarget(project); } IFolder registryResources = binaries.getFolder("registry_resources"); if (registryResources.exists()) { FileUtils.deleteDirectories(registryResources.getLocation().toFile()); } registryResources.create(false, true, nullProgressMonitor); project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); if (RegistryResourceFile.exists()) { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( RegistryResourceFile.getContents()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); Iterator artifacts = documentElement.getChildElements(); while (artifacts.hasNext()) { Object o = artifacts.next(); if (o instanceof OMElement) { OMElement artifact = (OMElement) o; if ("artifact".equals(artifact.getLocalName())) { String name = artifact.getAttributeValue(new QName("name")); String version = artifact.getAttributeValue(new QName("version")); String type = artifact.getAttributeValue(new QName("type")); if ("registry/resource".equals(type)) { IFolder resourceArtifact = registryResources.getFolder(String .format("%s_%s", name, version)); resourceArtifact.create(true, true, nullProgressMonitor); IFolder resourcesDir = resourceArtifact.getFolder("resources"); resourcesDir.create(true, true, nullProgressMonitor); OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement resourcesEl = factory.createOMElement(new QName( "resources")); Iterator items = artifact.getChildElements(); while (items.hasNext()) { Object obj = items.next(); if (obj instanceof OMElement) { OMElement item = (OMElement) obj; if ("item".equals(item.getLocalName()) || "dump".equals(item.getLocalName())) { OMElement fileEl = item.getFirstChildWithName(new QName("file")); String fileName = fileEl.getText(); IFile regItem = project.getFile(fileName); if (regItem.exists()) { FileUtils.copy(regItem.getLocation().toFile(), new File(resourcesDir.getLocation() .toFile(), regItem.getName())); } fileEl.setText(regItem.getName()); resourcesEl.addChild(item); } else if ("collection".equals(item.getLocalName())) { OMElement collectionEl = item.getFirstChildWithName( new QName("directory")); String dir = collectionEl.getText(); IFolder regCollection = project.getFolder(dir); if (regCollection.exists()) { FileUtils.copyDirectory(regCollection .getLocation().toFile(), new File(resourcesDir .getLocation().toFile(),regCollection.getName())); } collectionEl.setText(regCollection.getName()); resourcesEl.addChild(item); } else{ log.warn("unknown resource type '" + item.getLocalName() + "'; skipping"); } } } IFile registryInfo = resourceArtifact .getFile("registry-info.xml"); XMLUtil.prettify(resourcesEl, new FileOutputStream(registryInfo .getLocation().toFile())); exportResources.add((IResource) resourceArtifact); } } } project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); } builder.close(); parser.close(); } } return exportResources; }
public List<IResource> exportArtifact(IProject project) throws Exception { if (project.hasNature(GENERAL_PROJECT_NATURE)) { NullProgressMonitor nullProgressMonitor = new NullProgressMonitor(); project.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor); IFile RegistryResourceFile = project.getFile(ARTIFACT_XML); IFolder binaries = project.getFolder("target"); if (!binaries.exists()) { binaries.create(true, true, nullProgressMonitor); binaries.setHidden(true); } else{ clearTarget(project); } project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); IFolder registryResources = binaries.getFolder("registry_resources"); if (registryResources.exists()) { FileUtils.deleteDirectories(registryResources.getLocation().toFile()); } registryResources.create(false, true, nullProgressMonitor); project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); if (RegistryResourceFile.exists()) { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( RegistryResourceFile.getContents()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement documentElement = builder.getDocumentElement(); Iterator artifacts = documentElement.getChildElements(); while (artifacts.hasNext()) { Object o = artifacts.next(); if (o instanceof OMElement) { OMElement artifact = (OMElement) o; if ("artifact".equals(artifact.getLocalName())) { String name = artifact.getAttributeValue(new QName("name")); String version = artifact.getAttributeValue(new QName("version")); String type = artifact.getAttributeValue(new QName("type")); if ("registry/resource".equals(type)) { IFolder resourceArtifact = registryResources.getFolder(String .format("%s_%s", name, version)); resourceArtifact.create(true, true, nullProgressMonitor); IFolder resourcesDir = resourceArtifact.getFolder("resources"); resourcesDir.create(true, true, nullProgressMonitor); OMFactory factory = OMAbstractFactory.getOMFactory(); OMElement resourcesEl = factory.createOMElement(new QName( "resources")); Iterator items = artifact.getChildElements(); while (items.hasNext()) { Object obj = items.next(); if (obj instanceof OMElement) { OMElement item = (OMElement) obj; if ("item".equals(item.getLocalName()) || "dump".equals(item.getLocalName())) { OMElement fileEl = item.getFirstChildWithName(new QName("file")); String fileName = fileEl.getText(); IFile regItem = project.getFile(fileName); if (regItem.exists()) { FileUtils.copy(regItem.getLocation().toFile(), new File(resourcesDir.getLocation() .toFile(), regItem.getName())); } fileEl.setText(regItem.getName()); resourcesEl.addChild(item); } else if ("collection".equals(item.getLocalName())) { OMElement collectionEl = item.getFirstChildWithName( new QName("directory")); String dir = collectionEl.getText(); IFolder regCollection = project.getFolder(dir); if (regCollection.exists()) { FileUtils.copyDirectory(regCollection .getLocation().toFile(), new File(resourcesDir .getLocation().toFile(),regCollection.getName())); } collectionEl.setText(regCollection.getName()); resourcesEl.addChild(item); } else{ log.warn("unknown resource type '" + item.getLocalName() + "'; skipping"); } } } IFile registryInfo = resourceArtifact .getFile("registry-info.xml"); FileOutputStream out = new FileOutputStream(registryInfo .getLocation().toFile()); XMLUtil.prettify(resourcesEl, out); out.close(); exportResources.add((IResource) resourceArtifact); } } } project.refreshLocal(IResource.DEPTH_INFINITE, nullProgressMonitor); } builder.close(); parser.close(); } } return exportResources; }
diff --git a/src/com/mojang/mojam/entity/building/CatacombTreasure.java b/src/com/mojang/mojam/entity/building/CatacombTreasure.java index b38d15c2..0ab1d1c4 100644 --- a/src/com/mojang/mojam/entity/building/CatacombTreasure.java +++ b/src/com/mojang/mojam/entity/building/CatacombTreasure.java @@ -1,43 +1,47 @@ package com.mojang.mojam.entity.building; import com.mojang.mojam.entity.mob.Team; import com.mojang.mojam.screen.Art; import com.mojang.mojam.screen.Bitmap; import com.mojang.mojam.screen.Screen; /** * this is the treasure from the center of the map, RailDroids carry * it back to base and the player scores! * this is a building simply so the rail droids can carry it */ public class CatacombTreasure extends Building { /** * Constructor * * @param x Initial X coordinate * @param y Initial Y coordinate */ public CatacombTreasure(double x, double y) { //always Neutral super(x, y, Team.Neutral); + setStartHealth(20); + freezeTime=20; + isImmortal = true; + yOffs=-8; } @Override public void tick() { //do nothing? super.tick(); } @Override public void render(Screen screen) { super.render(screen); } @Override public Bitmap getSprite() { //bullets? really? return Art.bullets[0][0]; } }
true
true
public CatacombTreasure(double x, double y) { //always Neutral super(x, y, Team.Neutral); }
public CatacombTreasure(double x, double y) { //always Neutral super(x, y, Team.Neutral); setStartHealth(20); freezeTime=20; isImmortal = true; yOffs=-8; }
diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java index d511d5a98..ae2ceaf0e 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java @@ -1,589 +1,588 @@ /******************************************************************************* * Copyright (c) 2000, 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 API and implementation *******************************************************************************/ package org.eclipse.jface.internal.text.html; import java.io.IOException; import java.io.StringReader; import java.util.Iterator; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationAdapter; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.TextLayout; import org.eclipse.swt.graphics.TextStyle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.core.runtime.ListenerList; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlExtension; import org.eclipse.jface.text.IInformationControlExtension3; import org.eclipse.jface.text.IInformationControlExtension4; import org.eclipse.jface.text.TextPresentation; /** * Displays textual information in a {@link org.eclipse.swt.browser.Browser} widget. * <p> * Moved into this package from <code>org.eclipse.jface.internal.text.revisions</code>.</p> * <p> * This class may be instantiated; it is not intended to be subclassed.</p> * <p> * Current problems: * <ul> * <li>the size computation is too small</li> * <li>focusLost event is not sent - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532</li> * </ul> * </p> * * @since 3.2 */ public class BrowserInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension3, IInformationControlExtension4, DisposeListener { /** * Tells whether the SWT Browser widget and hence this information * control is available. * * @param parent the parent component used for checking or <code>null</code> if none * @return <code>true</code> if this control is available */ public static boolean isAvailable(Composite parent) { if (!fgAvailabilityChecked) { try { Browser browser= new Browser(parent, SWT.NONE); browser.dispose(); fgIsAvailable= true; } catch (SWTError er) { fgIsAvailable= false; } finally { fgAvailabilityChecked= true; } } return fgIsAvailable; } /** Border thickness in pixels. */ private static final int BORDER= 1; /** * Minimal size constraints. * @since 3.2 */ private static final int MIN_WIDTH= 80; private static final int MIN_HEIGHT= 80; /** * Availability checking cache. */ private static boolean fgIsAvailable= false; private static boolean fgAvailabilityChecked= false; /** The control's shell */ private Shell fShell; /** The control's browser widget */ private Browser fBrowser; /** Tells whether the browser has content */ private boolean fBrowserHasContent; /** The control width constraint */ private int fMaxWidth= SWT.DEFAULT; /** The control height constraint */ private int fMaxHeight= SWT.DEFAULT; private Font fStatusTextFont; private Label fStatusTextField; private String fStatusFieldText; private boolean fHideScrollBars; private Listener fDeactivateListener; private ListenerList fFocusListeners= new ListenerList(); private Label fSeparator; private String fInputText; private TextLayout fTextLayout; private TextStyle fBoldStyle; /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the styled text widget */ public BrowserInformationControl(Shell parent, int shellStyle, int style) { this(parent, shellStyle, style, null); } /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the styled text widget * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden */ public BrowserInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { fStatusFieldText= statusFieldText; fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); - fTextLayout= new TextLayout(display); Composite composite= fShell; GridLayout layout= new GridLayout(1, false); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; layout.marginHeight= border; layout.marginWidth= border; composite.setLayout(layout); if (statusFieldText != null) { composite= new Composite(composite, SWT.NONE); layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; layout.verticalSpacing= 1; layout.horizontalSpacing= 1; composite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } // Browser field fBrowser= new Browser(composite, SWT.NONE); fHideScrollBars= (style & SWT.V_SCROLL) == 0 && (style & SWT.H_SCROLL) == 0; GridData gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fBrowser.setLayoutData(gd); fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fBrowser.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); } public void keyReleased(KeyEvent e) {} }); /* * XXX revisit when the Browser support is better * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=107629. Choosing a link to a * non-available target will show an error dialog behind the ON_TOP shell that seemingly * blocks the workbench. Disable links completely for now. */ fBrowser.addLocationListener(new LocationAdapter() { /* * @see org.eclipse.swt.browser.LocationAdapter#changing(org.eclipse.swt.browser.LocationEvent) */ public void changing(LocationEvent event) { String location= event.location; /* * Using the Browser.setText API triggers a location change to "about:blank" with * the mozilla widget. The Browser on carbon uses yet another kind of special * initialization URLs. * TODO remove this code once https://bugs.eclipse.org/bugs/show_bug.cgi?id=130314 is fixed */ if (!"about:blank".equals(location) && !("carbon".equals(SWT.getPlatform()) && location.startsWith("applewebdata:"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ event.doit= false; } }); // Replace browser's built-in context menu with none fBrowser.setMenu(new Menu(fShell, SWT.NONE)); // Status field if (statusFieldText != null) { fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusTextField= new Label(composite, SWT.RIGHT); fStatusTextField.setText(statusFieldText); Font font= fStatusTextField.getFont(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(fStatusTextField.getDisplay(), fontDatas); fStatusTextField.setFont(fStatusTextFont); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); fStatusTextField.setLayoutData(gd); fStatusTextField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); fStatusTextField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } addDisposeListener(this); createTextLayout(); } /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param style the additional styles for the browser widget */ public BrowserInformationControl(Shell parent,int style) { this(parent, SWT.TOOL | SWT.NO_TRIM, style); } /** * Creates a default information control with the given shell as parent. * No information presenter is used to process the information * to be displayed. No additional styles are applied to the styled text widget. * * @param parent the parent shell */ public BrowserInformationControl(Shell parent) { this(parent, SWT.NONE); } /* * @see IInformationControl#setInformation(String) */ public void setInformation(String content) { fBrowserHasContent= content != null && content.length() > 0; if (!fBrowserHasContent) content= "<html><body ></html>"; //$NON-NLS-1$ fInputText= content; int shellStyle= fShell.getStyle(); boolean RTL= (shellStyle & SWT.RIGHT_TO_LEFT) != 0; String[] styles= null; if (RTL && !fHideScrollBars) styles= new String[] { "direction:rtl;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ else if (RTL && fHideScrollBars) styles= new String[] { "direction:rtl;", "overflow:hidden;", "word-wrap:break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ else if (fHideScrollBars && true) styles= new String[] { "overflow:hidden;", "word-wrap: break-word;" }; //$NON-NLS-1$ //$NON-NLS-2$ if (styles != null) { StringBuffer buffer= new StringBuffer(content); HTMLPrinter.insertStyles(buffer, styles); content= buffer.toString(); } fBrowser.setText(content); } /* * @see org.eclipse.jdt.internal.ui.text.IInformationControlExtension4#setStatusText(java.lang.String) * @since 3.2 */ public void setStatusText(String statusFieldText) { fStatusFieldText= statusFieldText; } /* * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { if (fShell.isVisible() == visible) return; if (visible) { if (fStatusTextField != null) { boolean state= fStatusFieldText != null; if (state) fStatusTextField.setText(fStatusFieldText); fStatusTextField.setVisible(state); fSeparator.setVisible(state); } } fShell.setVisible(visible); if (!visible) setInformation(""); //$NON-NLS-1$ } /** * Creates and initializes the text layout used * to compute the size hint. * * @since 3.2 */ private void createTextLayout() { fTextLayout= new TextLayout(fBrowser.getDisplay()); // Initialize fonts Font font= fBrowser.getFont(); fTextLayout.setFont(font); fTextLayout.setWidth(-1); FontData[] fontData= font.getFontData(); for (int i= 0; i < fontData.length; i++) fontData[i].setStyle(SWT.BOLD); font= new Font(fShell.getDisplay(), fontData); fBoldStyle= new TextStyle(font, null, null); // Compute and set tab width fTextLayout.setText(" "); //$NON-NLS-1$ int tabWidth = fTextLayout.getBounds().width; fTextLayout.setTabs(new int[] {tabWidth}); fTextLayout.setText(""); //$NON-NLS-1$ } /* * @see IInformationControl#dispose() */ public void dispose() { fTextLayout.dispose(); fTextLayout= null; fBoldStyle.font.dispose(); fBoldStyle= null; if (fShell != null && !fShell.isDisposed()) fShell.dispose(); else widgetDisposed(null); } /* * @see org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt.events.DisposeEvent) */ public void widgetDisposed(DisposeEvent event) { if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) fStatusTextFont.dispose(); fShell= null; fBrowser= null; fStatusTextFont= null; } /* * @see IInformationControl#setSize(int, int) */ public void setSize(int width, int height) { fShell.setSize(Math.min(width, fMaxWidth), Math.min(height, fMaxHeight)); } /* * @see IInformationControl#setLocation(Point) */ public void setLocation(Point location) { fShell.setLocation(location); } /* * @see IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { fMaxWidth= maxWidth; fMaxHeight= maxHeight; } /* * @see IInformationControl#computeSizeHint() */ public Point computeSizeHint() { TextPresentation presentation= new TextPresentation(); HTML2TextReader reader= new HTML2TextReader(new StringReader(fInputText), presentation); String text; try { text= reader.getString(); } catch (IOException e) { text= ""; //$NON-NLS-1$ } fTextLayout.setText(text); Iterator iter= presentation.getAllStyleRangeIterator(); while (iter.hasNext()) { StyleRange sr= (StyleRange)iter.next(); if (sr.fontStyle == SWT.BOLD) fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length - 1); } Rectangle bounds= fTextLayout.getBounds(); int width= bounds.width; int height= bounds.height; width += 15; height += 25; if (fStatusFieldText != null && fSeparator != null) { fTextLayout.setText(fStatusFieldText); Rectangle statusBounds= fTextLayout.getBounds(); Rectangle separatorBounds= fSeparator.getBounds(); width= Math.max(width, statusBounds.width); height= height + statusBounds.height + separatorBounds.height; } // Apply size constraints if (fMaxWidth != SWT.DEFAULT) width= Math.min(fMaxWidth, width); if (fMaxHeight != SWT.DEFAULT) height= Math.min(fMaxHeight, height); // Ensure minimal size width= Math.max(MIN_WIDTH, width); height= Math.max(MIN_HEIGHT, height); return new Point(width, height); } /* * @see org.eclipse.jface.text.IInformationControlExtension3#computeTrim() */ public Rectangle computeTrim() { return fShell.computeTrim(0, 0, 0, 0); } /* * @see org.eclipse.jface.text.IInformationControlExtension3#getBounds() */ public Rectangle getBounds() { return fShell.getBounds(); } /* * @see org.eclipse.jface.text.IInformationControlExtension3#restoresLocation() */ public boolean restoresLocation() { return false; } /* * @see org.eclipse.jface.text.IInformationControlExtension3#restoresSize() */ public boolean restoresSize() { return false; } /* * @see IInformationControl#addDisposeListener(DisposeListener) */ public void addDisposeListener(DisposeListener listener) { fShell.addDisposeListener(listener); } /* * @see IInformationControl#removeDisposeListener(DisposeListener) */ public void removeDisposeListener(DisposeListener listener) { fShell.removeDisposeListener(listener); } /* * @see IInformationControl#setForegroundColor(Color) */ public void setForegroundColor(Color foreground) { fBrowser.setForeground(foreground); } /* * @see IInformationControl#setBackgroundColor(Color) */ public void setBackgroundColor(Color background) { fBrowser.setBackground(background); } /* * @see IInformationControl#isFocusControl() */ public boolean isFocusControl() { return fBrowser.isFocusControl(); } /* * @see IInformationControl#setFocus() */ public void setFocus() { fShell.forceFocus(); fBrowser.setFocus(); } /* * @see IInformationControl#addFocusListener(FocusListener) */ public void addFocusListener(final FocusListener listener) { fBrowser.addFocusListener(listener); /* * FIXME: This is a workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532 * (Browser widget does not send focusLost event) */ if (fFocusListeners.isEmpty()) { fDeactivateListener= new Listener() { public void handleEvent(Event event) { Object[] listeners= fFocusListeners.getListeners(); for (int i = 0; i < listeners.length; i++) ((FocusListener)listeners[i]).focusLost(new FocusEvent(event)); } }; fBrowser.getShell().addListener(SWT.Deactivate, fDeactivateListener); } fFocusListeners.add(listener); } /* * @see IInformationControl#removeFocusListener(FocusListener) */ public void removeFocusListener(FocusListener listener) { fBrowser.removeFocusListener(listener); /* * FIXME: This is a workaround for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=84532 * (Browser widget does not send focusLost event) */ fFocusListeners.remove(listener); if (fFocusListeners.isEmpty()) { fBrowser.getShell().removeListener(SWT.Deactivate, fDeactivateListener); fDeactivateListener= null; } } /* * @see IInformationControlExtension#hasContents() */ public boolean hasContents() { return fBrowserHasContent; } }
true
true
public BrowserInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { fStatusFieldText= statusFieldText; fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); fTextLayout= new TextLayout(display); Composite composite= fShell; GridLayout layout= new GridLayout(1, false); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; layout.marginHeight= border; layout.marginWidth= border; composite.setLayout(layout); if (statusFieldText != null) { composite= new Composite(composite, SWT.NONE); layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; layout.verticalSpacing= 1; layout.horizontalSpacing= 1; composite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } // Browser field fBrowser= new Browser(composite, SWT.NONE); fHideScrollBars= (style & SWT.V_SCROLL) == 0 && (style & SWT.H_SCROLL) == 0; GridData gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fBrowser.setLayoutData(gd); fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fBrowser.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); } public void keyReleased(KeyEvent e) {} }); /* * XXX revisit when the Browser support is better * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=107629. Choosing a link to a * non-available target will show an error dialog behind the ON_TOP shell that seemingly * blocks the workbench. Disable links completely for now. */ fBrowser.addLocationListener(new LocationAdapter() { /* * @see org.eclipse.swt.browser.LocationAdapter#changing(org.eclipse.swt.browser.LocationEvent) */ public void changing(LocationEvent event) { String location= event.location; /* * Using the Browser.setText API triggers a location change to "about:blank" with * the mozilla widget. The Browser on carbon uses yet another kind of special * initialization URLs. * TODO remove this code once https://bugs.eclipse.org/bugs/show_bug.cgi?id=130314 is fixed */ if (!"about:blank".equals(location) && !("carbon".equals(SWT.getPlatform()) && location.startsWith("applewebdata:"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ event.doit= false; } }); // Replace browser's built-in context menu with none fBrowser.setMenu(new Menu(fShell, SWT.NONE)); // Status field if (statusFieldText != null) { fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusTextField= new Label(composite, SWT.RIGHT); fStatusTextField.setText(statusFieldText); Font font= fStatusTextField.getFont(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(fStatusTextField.getDisplay(), fontDatas); fStatusTextField.setFont(fStatusTextFont); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); fStatusTextField.setLayoutData(gd); fStatusTextField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); fStatusTextField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } addDisposeListener(this); createTextLayout(); }
public BrowserInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { fStatusFieldText= statusFieldText; fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); Composite composite= fShell; GridLayout layout= new GridLayout(1, false); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; layout.marginHeight= border; layout.marginWidth= border; composite.setLayout(layout); if (statusFieldText != null) { composite= new Composite(composite, SWT.NONE); layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; layout.verticalSpacing= 1; layout.horizontalSpacing= 1; composite.setLayout(layout); GridData gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } // Browser field fBrowser= new Browser(composite, SWT.NONE); fHideScrollBars= (style & SWT.V_SCROLL) == 0 && (style & SWT.H_SCROLL) == 0; GridData gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fBrowser.setLayoutData(gd); fBrowser.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fBrowser.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fBrowser.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); } public void keyReleased(KeyEvent e) {} }); /* * XXX revisit when the Browser support is better * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=107629. Choosing a link to a * non-available target will show an error dialog behind the ON_TOP shell that seemingly * blocks the workbench. Disable links completely for now. */ fBrowser.addLocationListener(new LocationAdapter() { /* * @see org.eclipse.swt.browser.LocationAdapter#changing(org.eclipse.swt.browser.LocationEvent) */ public void changing(LocationEvent event) { String location= event.location; /* * Using the Browser.setText API triggers a location change to "about:blank" with * the mozilla widget. The Browser on carbon uses yet another kind of special * initialization URLs. * TODO remove this code once https://bugs.eclipse.org/bugs/show_bug.cgi?id=130314 is fixed */ if (!"about:blank".equals(location) && !("carbon".equals(SWT.getPlatform()) && location.startsWith("applewebdata:"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ event.doit= false; } }); // Replace browser's built-in context menu with none fBrowser.setMenu(new Menu(fShell, SWT.NONE)); // Status field if (statusFieldText != null) { fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusTextField= new Label(composite, SWT.RIGHT); fStatusTextField.setText(statusFieldText); Font font= fStatusTextField.getFont(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(fStatusTextField.getDisplay(), fontDatas); fStatusTextField.setFont(fStatusTextFont); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); fStatusTextField.setLayoutData(gd); fStatusTextField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); fStatusTextField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } addDisposeListener(this); createTextLayout(); }
diff --git a/com.ibm.wala.core/src/com/ibm/wala/eclipse/util/EclipseProjectPath.java b/com.ibm.wala.core/src/com/ibm/wala/eclipse/util/EclipseProjectPath.java index f4756762d..a33e9acd6 100644 --- a/com.ibm.wala.core/src/com/ibm/wala/eclipse/util/EclipseProjectPath.java +++ b/com.ibm.wala.core/src/com/ibm/wala/eclipse/util/EclipseProjectPath.java @@ -1,364 +1,365 @@ /******************************************************************************* * Copyright (c) 2007 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.eclipse.util; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import java.util.zip.ZipException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.osgi.service.resolver.BundleDescription; import org.eclipse.pde.core.plugin.IPluginModelBase; import org.eclipse.pde.core.plugin.PluginRegistry; import org.eclipse.pde.internal.core.ClasspathUtilCore; import org.eclipse.pde.internal.core.PDEStateHelper; import com.ibm.wala.classLoader.BinaryDirectoryTreeModule; import com.ibm.wala.classLoader.EclipseSourceFileModule; import com.ibm.wala.classLoader.FileModule; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.MapUtil; import com.ibm.wala.util.config.AnalysisScopeReader; import com.ibm.wala.util.debug.Assertions; import com.ibm.wala.util.strings.Atom; /** * Representation of an analysis scope from an Eclipse project. * * We set up classloaders as follows: * <ul> * <li> The project being analyzed is in the Application Loader * <li> Projects on which the main project depends are in the Extension loader * <li> System libraries are in the primordial loader. * <li> Source modules go in a special Source loader. * </ul> * * @author sjfink * @author jdolby (some code moved here from EclipseProjectAnalysisEngine) * @author smarkstr (added support for language file extensions) * */ @SuppressWarnings("restriction") public class EclipseProjectPath { /** * TODO: do we really need this? Why shouldn't source files come from a "normal" class loader like any other resource? */ public static final Atom SOURCE = Atom.findOrCreateUnicodeAtom("Source"); public static final ClassLoaderReference SOURCE_REF = new ClassLoaderReference(EclipseProjectPath.SOURCE, ClassLoaderReference.Java); public enum Loader { APPLICATION(ClassLoaderReference.Application), EXTENSION(ClassLoaderReference.Extension), PRIMORDIAL( ClassLoaderReference.Primordial), SOURCE(SOURCE_REF); private ClassLoaderReference ref; Loader(ClassLoaderReference ref) { this.ref = ref; } }; /** * The project whose path this object represents */ private final IJavaProject project; private final boolean analyzeSource; // names of OSGi bundles already processed. private final Set<String> bundlesProcessed = HashSetFactory.make(); // SJF: Intentionally do not use HashMapFactory, since the Loader keys in the following must use // identityHashCode. TODO: fix this source of non-determinism? private final Map<Loader, List<Module>> binaryModules = new HashMap<Loader, List<Module>>(); private final Map<Loader, List<Module>> sourceModules = new HashMap<Loader, List<Module>>(); private final Collection<IClasspathEntry> alreadyResolved = HashSetFactory.make(); protected EclipseProjectPath(IJavaProject project, boolean analyzeSource) throws IOException, CoreException { this.project = project; this.analyzeSource = analyzeSource; assert project != null; for (Loader loader : Loader.values()) { MapUtil.findOrCreateList(binaryModules, loader); MapUtil.findOrCreateList(sourceModules, loader); } resolveProjectClasspathEntries(); if (isPluginProject(project)) { resolvePluginClassPath(project.getProject()); } } @Deprecated public static EclipseProjectPath make(IPath workspaceRootPath, IJavaProject project) throws IOException, CoreException { return new EclipseProjectPath(project, false); } public static EclipseProjectPath make(IJavaProject project) throws IOException, CoreException { return make(project, false); } public static EclipseProjectPath make(IJavaProject project, boolean analyzeSource) throws IOException, CoreException { return new EclipseProjectPath(project, analyzeSource); } /** * Figure out what a classpath entry means and add it to the appropriate set of modules */ private void resolveClasspathEntry(IClasspathEntry entry, Loader loader) throws JavaModelException, IOException { IClasspathEntry e = JavaCore.getResolvedClasspathEntry(entry); if (alreadyResolved.contains(e)) { return; } else { alreadyResolved.add(e); } if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IClasspathContainer cont = JavaCore.getClasspathContainer(entry.getPath(), project); IClasspathEntry[] entries = cont.getClasspathEntries(); resolveClasspathEntries(entries, cont.getKind() == IClasspathContainer.K_APPLICATION ? loader : Loader.PRIMORDIAL); } else if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { File file = makeAbsolute(e.getPath()).toFile(); JarFile j; try { j = new JarFile(file); } catch (ZipException z) { // a corrupted file. ignore it. return; } catch (FileNotFoundException z) { // should ignore directories as well.. return; } if (isPrimordialJarFile(j)) { List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(file.isDirectory() ? (Module) new BinaryDirectoryTreeModule(file) : (Module) new JarFileModule(j)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) { final File dir = makeAbsolute(e.getPath()).toFile(); final File relDir = e.getPath().removeFirstSegments(1).toFile(); List<Module> s = MapUtil.findOrCreateList(sourceModules, Loader.SOURCE); s.add(new SourceDirectoryTreeModule(dir) { + @Override protected FileModule makeFile(File file) { assert file.toString().startsWith(dir.toString()) : file + " " + dir + " " + relDir; file = new File(file.toString().substring(dir.toString().length())); IFile f = project.getProject().getFile(relDir.toString() + file.toString()); return new EclipseSourceFileModule(f); } }); if (!analyzeSource && e.getOutputLocation() != null) { File output = makeAbsolute(e.getOutputLocation()).toFile(); s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = makeAbsolute(e.getPath()); IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); IProject project = (IProject) root.getContainerForLocation(projectPath); try { if (project.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (isPluginProject(javaProject)) { resolvePluginClassPath(javaProject.getProject()); } else { resolveClasspathEntries(javaProject.getRawClasspath(), loader); if (! analyzeSource) { File output = makeAbsolute(javaProject.getOutputLocation()).toFile(); List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } } } catch (CoreException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } } else { throw new RuntimeException("unexpected entry " + e); } } private void resolvePluginClassPath(IProject p) throws CoreException, IOException { BundleDescription bd = PluginRegistry.findModel(p).getBundleDescription(); resolveBundleDescriptionClassPath(bd, Loader.APPLICATION); } private void resolveBundleDescriptionClassPath(BundleDescription bd, Loader loader) throws CoreException, IOException { assert bd != null; if (alreadyProcessed(bd)) { return; } bundlesProcessed.add(bd.getName()); // handle the classpath entries for bd ArrayList l = new ArrayList(); ClasspathUtilCore.addLibraries(PluginRegistry.findModel(bd), l); IClasspathEntry[] entries = new IClasspathEntry[l.size()]; int i = 0; for (Object o : l) { IClasspathEntry e = (IClasspathEntry) o; entries[i++] = e; } resolveClasspathEntries(entries, loader); // recurse to handle dependencies. put these in the Extension loader for (BundleDescription b : PDEStateHelper.getImportedBundles(bd)) { resolveBundleDescriptionClassPath(b, Loader.EXTENSION); } for (BundleDescription b : bd.getResolvedRequires()) { resolveBundleDescriptionClassPath(b, Loader.EXTENSION); } for (BundleDescription b : bd.getFragments()) { resolveBundleDescriptionClassPath(b, Loader.EXTENSION); } } private boolean alreadyProcessed(BundleDescription bd) { return bundlesProcessed.contains(bd.getName()); } private boolean isPluginProject(IJavaProject javaProject) { IPluginModelBase model = PluginRegistry.findModel(javaProject.getProject()); if (model == null) { return false; } if (model.getPluginBase().getId() == null) { return false; } return true; } /** * @return true if the given jar file should be handled by the Primordial loader. If false, other provisions should be made to add * the jar file to the appropriate component of the AnalysisScope. Subclasses can override this method. */ protected boolean isPrimordialJarFile(JarFile j) { return true; } protected void resolveClasspathEntries(IClasspathEntry[] entries, Loader loader) throws JavaModelException, IOException { for (int i = 0; i < entries.length; i++) { resolveClasspathEntry(entries[i], loader); } } protected IPath makeAbsolute(IPath p) { if (p.toFile().exists()) { return p; } String projectName = p.segment(0); IJavaProject jp = JdtUtil.getJavaProject(projectName); if (jp != null) { if (jp.getProject().getRawLocation() != null) { return jp.getProject().getRawLocation().append(p.removeFirstSegments(1)); } else { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); return workspaceRoot.getLocation().append(p); } } else { Assertions.UNREACHABLE("Unsupported path " + p); return null; } } /** * If file extension is not provided, use system default * * @throws JavaModelException * @throws IOException */ private void resolveProjectClasspathEntries() throws JavaModelException, IOException { resolveClasspathEntries(project.getRawClasspath(), Loader.EXTENSION); } /** * Convert this path to a WALA analysis scope */ public AnalysisScope toAnalysisScope(ClassLoader classLoader, File exclusionsFile) { AnalysisScope scope = AnalysisScopeReader.read(AbstractAnalysisEngine.SYNTHETIC_J2SE_MODEL, exclusionsFile, classLoader); return toAnalysisScope(scope); } public AnalysisScope toAnalysisScope(AnalysisScope scope) { try { List<Module> l = MapUtil.findOrCreateList(binaryModules, Loader.APPLICATION); if (! analyzeSource) { File dir = makeAbsolute(project.getOutputLocation()).toFile(); if (!dir.isDirectory()) { System.err.println("PANIC: project output location is not a directory: " + dir); } else { l.add(new BinaryDirectoryTreeModule(dir)); } } for (Loader loader : Loader.values()) { for (Module m : binaryModules.get(loader)) { scope.addToScope(loader.ref, m); } for (Module m : sourceModules.get(loader)) { scope.addToScope(loader.ref, m); } } return scope; } catch (JavaModelException e) { e.printStackTrace(); Assertions.UNREACHABLE(); return null; } } public AnalysisScope toAnalysisScope(final File exclusionsFile) { return toAnalysisScope(getClass().getClassLoader(), exclusionsFile); } public Collection<Module> getModules(Loader loader, boolean binary) { if (binary) { return Collections.unmodifiableCollection(binaryModules.get(loader)); } else { return Collections.unmodifiableCollection(sourceModules.get(loader)); } } @Override public String toString() { return toAnalysisScope((File)null).toString(); } }
true
true
private void resolveClasspathEntry(IClasspathEntry entry, Loader loader) throws JavaModelException, IOException { IClasspathEntry e = JavaCore.getResolvedClasspathEntry(entry); if (alreadyResolved.contains(e)) { return; } else { alreadyResolved.add(e); } if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IClasspathContainer cont = JavaCore.getClasspathContainer(entry.getPath(), project); IClasspathEntry[] entries = cont.getClasspathEntries(); resolveClasspathEntries(entries, cont.getKind() == IClasspathContainer.K_APPLICATION ? loader : Loader.PRIMORDIAL); } else if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { File file = makeAbsolute(e.getPath()).toFile(); JarFile j; try { j = new JarFile(file); } catch (ZipException z) { // a corrupted file. ignore it. return; } catch (FileNotFoundException z) { // should ignore directories as well.. return; } if (isPrimordialJarFile(j)) { List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(file.isDirectory() ? (Module) new BinaryDirectoryTreeModule(file) : (Module) new JarFileModule(j)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) { final File dir = makeAbsolute(e.getPath()).toFile(); final File relDir = e.getPath().removeFirstSegments(1).toFile(); List<Module> s = MapUtil.findOrCreateList(sourceModules, Loader.SOURCE); s.add(new SourceDirectoryTreeModule(dir) { protected FileModule makeFile(File file) { assert file.toString().startsWith(dir.toString()) : file + " " + dir + " " + relDir; file = new File(file.toString().substring(dir.toString().length())); IFile f = project.getProject().getFile(relDir.toString() + file.toString()); return new EclipseSourceFileModule(f); } }); if (!analyzeSource && e.getOutputLocation() != null) { File output = makeAbsolute(e.getOutputLocation()).toFile(); s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = makeAbsolute(e.getPath()); IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); IProject project = (IProject) root.getContainerForLocation(projectPath); try { if (project.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (isPluginProject(javaProject)) { resolvePluginClassPath(javaProject.getProject()); } else { resolveClasspathEntries(javaProject.getRawClasspath(), loader); if (! analyzeSource) { File output = makeAbsolute(javaProject.getOutputLocation()).toFile(); List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } } } catch (CoreException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } } else { throw new RuntimeException("unexpected entry " + e); } }
private void resolveClasspathEntry(IClasspathEntry entry, Loader loader) throws JavaModelException, IOException { IClasspathEntry e = JavaCore.getResolvedClasspathEntry(entry); if (alreadyResolved.contains(e)) { return; } else { alreadyResolved.add(e); } if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IClasspathContainer cont = JavaCore.getClasspathContainer(entry.getPath(), project); IClasspathEntry[] entries = cont.getClasspathEntries(); resolveClasspathEntries(entries, cont.getKind() == IClasspathContainer.K_APPLICATION ? loader : Loader.PRIMORDIAL); } else if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { File file = makeAbsolute(e.getPath()).toFile(); JarFile j; try { j = new JarFile(file); } catch (ZipException z) { // a corrupted file. ignore it. return; } catch (FileNotFoundException z) { // should ignore directories as well.. return; } if (isPrimordialJarFile(j)) { List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(file.isDirectory() ? (Module) new BinaryDirectoryTreeModule(file) : (Module) new JarFileModule(j)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) { final File dir = makeAbsolute(e.getPath()).toFile(); final File relDir = e.getPath().removeFirstSegments(1).toFile(); List<Module> s = MapUtil.findOrCreateList(sourceModules, Loader.SOURCE); s.add(new SourceDirectoryTreeModule(dir) { @Override protected FileModule makeFile(File file) { assert file.toString().startsWith(dir.toString()) : file + " " + dir + " " + relDir; file = new File(file.toString().substring(dir.toString().length())); IFile f = project.getProject().getFile(relDir.toString() + file.toString()); return new EclipseSourceFileModule(f); } }); if (!analyzeSource && e.getOutputLocation() != null) { File output = makeAbsolute(e.getOutputLocation()).toFile(); s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } else if (e.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = makeAbsolute(e.getPath()); IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); IProject project = (IProject) root.getContainerForLocation(projectPath); try { if (project.hasNature(JavaCore.NATURE_ID)) { IJavaProject javaProject = JavaCore.create(project); if (isPluginProject(javaProject)) { resolvePluginClassPath(javaProject.getProject()); } else { resolveClasspathEntries(javaProject.getRawClasspath(), loader); if (! analyzeSource) { File output = makeAbsolute(javaProject.getOutputLocation()).toFile(); List<Module> s = MapUtil.findOrCreateList(binaryModules, loader); s.add(new BinaryDirectoryTreeModule(output)); } } } } catch (CoreException e1) { e1.printStackTrace(); Assertions.UNREACHABLE(); } } else { throw new RuntimeException("unexpected entry " + e); } }
diff --git a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java index fdb4c53c..8516d1db 100644 --- a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java +++ b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java @@ -1,90 +1,90 @@ /** * DiscoveredServerView.java * * Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com> * This file is part of Gluster Management Console. * * Gluster Management Console 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. * * Gluster Management Console is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.gluster.storage.management.gui.views; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.ViewPart; import com.gluster.storage.management.core.model.Server; import com.gluster.storage.management.core.utils.NumberUtil; import com.gluster.storage.management.gui.utils.GUIHelper; /** * @author root * */ public class DiscoveredServerView extends ViewPart { public static final String ID = DiscoveredServerView.class.getName(); private static final GUIHelper guiHelper = GUIHelper.getInstance(); private final FormToolkit toolkit = new FormToolkit(Display.getCurrent()); private ScrolledForm form; private Server server; /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { if (server == null) { server = (Server) guiHelper.getSelectedEntity(getSite(), Server.class); } createSections(parent); } private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); - toolkit.createLabel(section, "" + (server.getTotalMemory() / 1024), SWT.NONE); + toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024)), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); } private void createSections(Composite parent) { String serverName = server.getName(); form = guiHelper.setupForm(parent, toolkit, "Discovered Server Summary [" + serverName + "]"); createServerSummarySection(); parent.layout(); // IMP: lays out the form properly } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { if (form != null) { form.setFocus(); } } }
true
true
private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); toolkit.createLabel(section, "" + (server.getTotalMemory() / 1024), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); }
private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024)), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); }
diff --git a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java index dec310beb..bb7960b19 100644 --- a/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java +++ b/src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java @@ -1,236 +1,237 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math3.optimization.linear; import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.exception.MaxCountExceededException; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.util.Precision; /** * Solves a linear problem using the Two-Phase Simplex Method. * @version $Id$ * @since 2.0 */ public class SimplexSolver extends AbstractLinearOptimizer { /** Default amount of error to accept for algorithm convergence. */ private static final double DEFAULT_EPSILON = 1.0e-6; /** Default amount of error to accept in floating point comparisons (as ulps). */ private static final int DEFAULT_ULPS = 10; /** Amount of error to accept for algorithm convergence. */ private final double epsilon; /** Amount of error to accept in floating point comparisons (as ulps). */ private final int maxUlps; /** * Build a simplex solver with default settings. */ public SimplexSolver() { this(DEFAULT_EPSILON, DEFAULT_ULPS); } /** * Build a simplex solver with a specified accepted amount of error * @param epsilon the amount of error to accept for algorithm convergence * @param maxUlps amount of error to accept in floating point comparisons */ public SimplexSolver(final double epsilon, final int maxUlps) { this.epsilon = epsilon; this.maxUlps = maxUlps; } /** * Returns the column with the most negative coefficient in the objective function row. * @param tableau simple tableau for the problem * @return column with the most negative coefficient */ private Integer getPivotColumn(SimplexTableau tableau) { double minValue = 0; Integer minPos = null; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) { final double entry = tableau.getEntry(0, i); // check if the entry is strictly smaller than the current minimum // do not use a ulp/epsilon check if (entry < minValue) { minValue = entry; minPos = i; } } return minPos; } /** * Returns the row with the minimum ratio as given by the minimum ratio test (MRT). * @param tableau simple tableau for the problem * @param col the column to test the ratio of. See {@link #getPivotColumn(SimplexTableau)} * @return row with the minimum ratio */ private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); - for (; i < tableau.getWidth() - 1 && minRow != row; i++) { - if (row == tableau.getBasicRow(i)) { + for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) { + Integer basicRow = tableau.getBasicRow(i); + if (basicRow != null && basicRow.equals(row)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); } /** * Runs one iteration of the Simplex method on the given model. * @param tableau simple tableau for the problem * @throws MaxCountExceededException if the maximal iteration count has been exceeded * @throws UnboundedSolutionException if the model is found not to have a bounded solution */ protected void doIteration(final SimplexTableau tableau) throws MaxCountExceededException, UnboundedSolutionException { incrementIterationsCounter(); Integer pivotCol = getPivotColumn(tableau); Integer pivotRow = getPivotRow(tableau, pivotCol); if (pivotRow == null) { throw new UnboundedSolutionException(); } // set the pivot element to 1 double pivotVal = tableau.getEntry(pivotRow, pivotCol); tableau.divideRow(pivotRow, pivotVal); // set the rest of the pivot column to 0 for (int i = 0; i < tableau.getHeight(); i++) { if (i != pivotRow) { final double multiplier = tableau.getEntry(i, pivotCol); tableau.subtractRow(i, pivotRow, multiplier); } } } /** * Solves Phase 1 of the Simplex method. * @param tableau simple tableau for the problem * @throws MaxCountExceededException if the maximal iteration count has been exceeded * @throws UnboundedSolutionException if the model is found not to have a bounded solution * @throws NoFeasibleSolutionException if there is no feasible solution */ protected void solvePhase1(final SimplexTableau tableau) throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException { // make sure we're in Phase 1 if (tableau.getNumArtificialVariables() == 0) { return; } while (!tableau.isOptimal()) { doIteration(tableau); } // if W is not zero then we have no feasible solution if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) { throw new NoFeasibleSolutionException(); } } /** {@inheritDoc} */ @Override public PointValuePair doOptimize() throws MaxCountExceededException, UnboundedSolutionException, NoFeasibleSolutionException { final SimplexTableau tableau = new SimplexTableau(getFunction(), getConstraints(), getGoalType(), restrictToNonNegative(), epsilon, maxUlps); solvePhase1(tableau); tableau.dropPhase1Objective(); while (!tableau.isOptimal()) { doIteration(tableau); } return tableau.getSolution(); } }
true
true
private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && minRow != row; i++) { if (row == tableau.getBasicRow(i)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && !row.equals(minRow); i++) { Integer basicRow = tableau.getBasicRow(i); if (basicRow != null && basicRow.equals(row)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
diff --git a/src/view/GamePanel.java b/src/view/GamePanel.java index f6ef81e..2c12ddc 100644 --- a/src/view/GamePanel.java +++ b/src/view/GamePanel.java @@ -1,297 +1,297 @@ package view; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.BorderFactory; import model.GameModel; import model.geometrical.CollisionBox; import model.geometrical.Position; import model.items.weapons.Projectile; import model.sprites.Enemy; import model.sprites.Player; import model.sprites.Sprite; import model.items.Item; /** * * * @author * */ public class GamePanel extends IGamePanel implements PropertyChangeListener, MouseMotionListener, Runnable { private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); private static final long serialVersionUID = 1L; private GameModel model; private TileView[][] tiles; private List<ObjectRenderer<?>> objects; private Camera camera; private final int SLEEP = 1000 / 60; private volatile boolean paused = false; private volatile boolean isRunning = true; private CustomCursor cursor; /** * Creates a new panel with the specified model and controller. * @param model the model to display. * @param controller the controller to use. */ public GamePanel(GameModel model) { super(); this.model = model; this.addMouseMotionListener(this); this.camera = new Camera(40); this.buildLayout(); this.initObjectList(); this.initTileList(); //Hides the default cursor Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor( new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "blank cursor"); this.setCursor (blankCursor); this.cursor = new CustomCursor(); this.addMouseMotionListener(cursor); } @Override public void run() { while(isRunning) { runThread(); } } private synchronized void runThread(){ if (!paused) { repaint(); try{ Thread.sleep(SLEEP); }catch (InterruptedException e) { e.printStackTrace(); } } else { try{ wait(); }catch (InterruptedException e) { e.printStackTrace(); } } } /** * Add a PropertyChangeListener to the listener list. The listener is registered for all properties. * The same listener object may be added more than once, and will be called as many times as it is added. * If listener is null, no exception is thrown and no action is taken. * @param pcl The PropertyChangeListener to be added */ public void addListener(PropertyChangeListener pcl) { this.pcs.addPropertyChangeListener(pcl); } /** * Remove a PropertyChangeListener from the listener list. This removes a PropertyChangeListener * that was registered for all properties. If listener was added more than once to the same event * source, it will be notified one less time after being removed. If listener is null, or was never added, * no exception is thrown and no action is taken. * @param pcl The PropertyChangeListener to be removed */ public void removeListener(PropertyChangeListener pcl) { this.pcs.removePropertyChangeListener(pcl); } /* * Builds the layout of the game panel. (Adds all the GUI bits) */ private void buildLayout() { setLayout(new GridBagLayout()); GridBagConstraints gridBagConstraints = new GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_END; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 0.1; add(new PlayerPanel(model.getPlayer()), gridBagConstraints); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; Minimap minimap = new Minimap(model); minimap.setPreferredSize(new Dimension(200, 200)); minimap.setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0), 2)); add(minimap, gridBagConstraints); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; add(new BarPanel(model.getPlayer()), gridBagConstraints); gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END; gridBagConstraints.weightx = 0.1; gridBagConstraints.weighty = 0.1; add(new ScorePanel(model), gridBagConstraints); } /* * Creates the list which holds all the sprite views, and loads it with the * sprites already in the world. */ private void initObjectList() { objects = new ArrayList<ObjectRenderer<?>>(); for(Sprite s : this.model.getWorld().getSprites()) { if(s instanceof Player) { objects.add(new PlayerView((Player)s)); }else{ objects.add(new EnemyView((Enemy)s)); } } for(Projectile p : this.model.getWorld().getProjectiles()) { objects.add(new ProjectileView(p)); } for(Item i : this.model.getWorld().getItems()){ objects.add(new ItemView(i)); } Collections.sort(objects, new ObjectSort()); } /* * Creates the list which holds all the renderers of the tiles. */ private void initTileList() { tiles = new TileView[model.getWorld().getTiles().length][model.getWorld().getTiles()[0].length]; for(int i = 0; i < model.getWorld().getTiles().length; i++) { for(int j = 0; j < model.getWorld().getTiles()[i].length; j++) { tiles[i][j] = new TileView(model.getWorld().getTiles()[i][j]); } } } private Position translatePos(Position pos) { return new Position((pos.getX() - camera.getX())/camera.getScale(), (pos.getY() - camera.getY())/camera.getScale()); } /** * Draws the collision box. * @param g the graphics instance to use when drawing. * @param scale the scale to draw at. * @param box the collision box to draw. * @param color the colour to draw in. * @param renderPosition specify if the position of each line should be marked. * @param colourPosition the colour of the position mark. */ public static void renderCollisionBox(Graphics g, model.geometrical.Position pos, int scale, CollisionBox box, Color colour, boolean renderPosition, Color colourPosition) { g.setColor(colour); if(box != null) { for(java.awt.geom.Line2D r : box.getLines()) { g.drawLine((int)(r.getX1() * scale + pos.getX()), (int)(r.getY1() * scale + pos.getY()), (int)(r.getX2() * scale + pos.getX()), (int)(r.getY2() * scale + pos.getY())); } } } @Override public void propertyChange(PropertyChangeEvent e) { if(e.getPropertyName().equals(GameModel.ADDED_SPRITE)) { if(e.getNewValue() instanceof Player) { this.objects.add(new PlayerView((Player)e.getNewValue())); }else{ this.objects.add(new EnemyView((Enemy)e.getNewValue())); } }else if(e.getPropertyName().equals(GameModel.REMOVED_OBJECT)) { for(ObjectRenderer<?> or : this.objects) { if(or.getObject() == e.getOldValue()) { objects.remove(or); break; } } if(e.getOldValue() instanceof Sprite) { objects.add(new BloodPool(((Sprite)e.getOldValue()).getCenter())); } }else if(e.getPropertyName().equals(GameModel.ADDED_PROJECTILE)) { this.objects.add(new ProjectileView((Projectile)e.getNewValue())); }else if(e.getPropertyName().equals(GameModel.ADDED_SUPPLY)){ this.objects.add(new ItemView((Item)e.getNewValue())); } Collections.sort(objects, new ObjectSort()); } @Override public void mouseDragged(MouseEvent e) { this.mouseMoved(e); } @Override public void mouseMoved(MouseEvent e) { Position msPos = new Position((float)(e.getX()-camera.getX())/camera.getScale(), (float)(e.getY()-camera.getY())/camera.getScale()); this.pcs.firePropertyChange(MOUSE_INPUT, null, msPos); } @Override public synchronized void pauseThread(){ paused=true; } @Override public synchronized void resumeThread(){ paused=false; notify(); } @Override public synchronized void stopThread() { isRunning=false; notify(); } @Override public void render(Graphics g) { Graphics2D g2d = (Graphics2D)g; //Turn on anti alignment //Note: setting the hints to KEY_ANTIALIASING won't render the rotated images as such! g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Draws all the static world objects. Position drawMin = translatePos(new Position(0, 0)); Position drawMax = translatePos(new Position(getWidth(), getHeight())); camera.setToCenter(model.getPlayer().getCenter(), getSize()); for(int x = Math.max((int)drawMin.getX(), 0); x < Math.min(model.getWorld().getWidth(), drawMax.getX()); x++) { for(int y = Math.max((int)drawMin.getY(), 0); y < Math.min(model.getWorld().getHeight(), drawMax.getY()); y++) { tiles[x][y].render(g2d, camera.getOffset(), camera.getScale()); } } //Draws all the dynamic items. - for(@SuppressWarnings("rawtypes") ObjectRenderer ob : objects) { - if(ob instanceof PlayerView) { - ((PlayerView)ob).render(g2d, camera.getOffset(), camera.getScale(), + for(int i = 0; i < objects.size(); i++) { + if(objects.get(i) instanceof PlayerView) { + ((PlayerView)objects.get(i)).render(g2d, camera.getOffset(), camera.getScale(), new Position(this.getWidth()/2, this.getHeight()/2)); }else{ - ob.render(g2d, camera.getOffset(), camera.getScale()); + objects.get(i).render(g2d, camera.getOffset(), camera.getScale()); } } //Draw cursor cursor.render(g2d); } }
false
true
public void render(Graphics g) { Graphics2D g2d = (Graphics2D)g; //Turn on anti alignment //Note: setting the hints to KEY_ANTIALIASING won't render the rotated images as such! g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Draws all the static world objects. Position drawMin = translatePos(new Position(0, 0)); Position drawMax = translatePos(new Position(getWidth(), getHeight())); camera.setToCenter(model.getPlayer().getCenter(), getSize()); for(int x = Math.max((int)drawMin.getX(), 0); x < Math.min(model.getWorld().getWidth(), drawMax.getX()); x++) { for(int y = Math.max((int)drawMin.getY(), 0); y < Math.min(model.getWorld().getHeight(), drawMax.getY()); y++) { tiles[x][y].render(g2d, camera.getOffset(), camera.getScale()); } } //Draws all the dynamic items. for(@SuppressWarnings("rawtypes") ObjectRenderer ob : objects) { if(ob instanceof PlayerView) { ((PlayerView)ob).render(g2d, camera.getOffset(), camera.getScale(), new Position(this.getWidth()/2, this.getHeight()/2)); }else{ ob.render(g2d, camera.getOffset(), camera.getScale()); } } //Draw cursor cursor.render(g2d); }
public void render(Graphics g) { Graphics2D g2d = (Graphics2D)g; //Turn on anti alignment //Note: setting the hints to KEY_ANTIALIASING won't render the rotated images as such! g2d.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Draws all the static world objects. Position drawMin = translatePos(new Position(0, 0)); Position drawMax = translatePos(new Position(getWidth(), getHeight())); camera.setToCenter(model.getPlayer().getCenter(), getSize()); for(int x = Math.max((int)drawMin.getX(), 0); x < Math.min(model.getWorld().getWidth(), drawMax.getX()); x++) { for(int y = Math.max((int)drawMin.getY(), 0); y < Math.min(model.getWorld().getHeight(), drawMax.getY()); y++) { tiles[x][y].render(g2d, camera.getOffset(), camera.getScale()); } } //Draws all the dynamic items. for(int i = 0; i < objects.size(); i++) { if(objects.get(i) instanceof PlayerView) { ((PlayerView)objects.get(i)).render(g2d, camera.getOffset(), camera.getScale(), new Position(this.getWidth()/2, this.getHeight()/2)); }else{ objects.get(i).render(g2d, camera.getOffset(), camera.getScale()); } } //Draw cursor cursor.render(g2d); }
diff --git a/parser/src/main/java/org/apache/abdera/parser/stax/FOMFactory.java b/parser/src/main/java/org/apache/abdera/parser/stax/FOMFactory.java index f472d803..97247644 100644 --- a/parser/src/main/java/org/apache/abdera/parser/stax/FOMFactory.java +++ b/parser/src/main/java/org/apache/abdera/parser/stax/FOMFactory.java @@ -1,915 +1,917 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.parser.stax; import java.util.ArrayList; import java.util.List; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.factory.ExtensionFactory; import org.apache.abdera.factory.ExtensionFactoryMap; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Content; import org.apache.abdera.model.Control; import org.apache.abdera.model.DateTime; import org.apache.abdera.model.Div; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.model.ExtensibleElement; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Generator; import org.apache.abdera.model.IRIElement; import org.apache.abdera.model.Link; import org.apache.abdera.model.Person; import org.apache.abdera.model.Service; import org.apache.abdera.model.Source; import org.apache.abdera.model.Text; import org.apache.abdera.model.Workspace; import org.apache.abdera.model.Content.Type; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.util.Version; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMText; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.llom.factory.OMLinkedListImplFactory; @SuppressWarnings("unchecked") public class FOMFactory extends OMLinkedListImplFactory implements Factory, Constants, ExtensionFactory { private final ExtensionFactoryMap factoriesMap; private final Abdera abdera; public static void registerAsDefault() { System.setProperty( OMAbstractFactory.OM_FACTORY_NAME_PROPERTY, FOMFactory.class.getName()); } public FOMFactory() { this(new Abdera()); } public FOMFactory(Abdera abdera) { List<ExtensionFactory> f= abdera.getConfiguration().getExtensionFactories(); factoriesMap = new ExtensionFactoryMap( (f != null) ? new ArrayList<ExtensionFactory>(f) : new ArrayList<ExtensionFactory>()); this.abdera = abdera; } public Parser newParser() { return new FOMParser(abdera); } public <T extends Element>Document<T> newDocument() { return new FOMDocument(this); } public <T extends Element>Document<T> newDocument( OMXMLParserWrapper parserWrapper) { return new FOMDocument(parserWrapper, this); } public <T extends Element>Document<T> newDocument( T root, OMXMLParserWrapper parserWrapper) { FOMDocument<T> doc = (FOMDocument<T>) newDocument(parserWrapper); doc.setRoot(root); return doc; } public Service newService( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMService(qname, parent, this, parserWrapper); } public Service newService( Base parent) { return new FOMService((OMContainer) parent,this); } public Workspace newWorkspace( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMWorkspace(qname,parent, this, parserWrapper); } public Workspace newWorkspace() { return newWorkspace(null); } public Workspace newWorkspace( Element parent) { return new FOMWorkspace((OMContainer)parent, this); } public Collection newCollection( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMCollection(qname, parent, this, parserWrapper); } public Collection newCollection() { return newCollection(null); } public Collection newCollection( Element parent) { return new FOMCollection((OMContainer)parent,this); } public Feed newFeed() { Document<Feed> doc = newDocument(); return newFeed(doc); } public Entry newEntry() { Document<Entry> doc = newDocument(); return newEntry(doc); } public Service newService() { Document<Service> doc = newDocument(); return newService(doc); } public Feed newFeed( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMFeed(qname,parent,this,parserWrapper); } public Feed newFeed( Base parent) { return new FOMFeed((OMContainer)parent,this); } public Entry newEntry( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMEntry(qname,parent,this,parserWrapper); } public Entry newEntry( Base parent) { return new FOMEntry((OMContainer)parent,this); } public Category newCategory( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMCategory(qname,parent,this,parserWrapper); } public Category newCategory() { return newCategory(null); } public Category newCategory( Element parent) { return new FOMCategory((OMContainer)parent,this); } public Content newContent( QName qname, Type type, OMContainer parent, OMXMLParserWrapper parserWrapper) { if (type == null) type = Content.Type.TEXT; return new FOMContent(qname,type,parent,this,parserWrapper); } public Content newContent() { return newContent(Content.Type.TEXT); } public Content newContent(Type type) { if (type == null) type = Content.Type.TEXT; return newContent(type, null); } public Content newContent( Type type, Element parent) { if (type == null) type = Content.Type.TEXT; Content content = new FOMContent(type, (OMContainer)parent,this); if (type.equals(Content.Type.XML)) content.setMimeType(XML_MEDIA_TYPE); return content; } public Content newContent(MimeType mediaType) { return newContent(mediaType, null); } public Content newContent( MimeType mediaType, Element parent) { Content.Type type = (MimeTypeHelper.isXml(mediaType.toString())) ? Content.Type.XML : Content.Type.MEDIA; Content content = newContent(type, parent); content.setMimeType(mediaType.toString()); return content; } public DateTime newDateTimeElement( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMDateTime(qname,parent,this,parserWrapper); } public DateTime newDateTime( QName qname, Element parent) { return new FOMDateTime(qname, (OMContainer)parent,this); } public Generator newGenerator( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMGenerator(qname,parent,this,parserWrapper); } public Generator newDefaultGenerator() { return newDefaultGenerator(null); } public Generator newDefaultGenerator( Element parent) { Generator generator = newGenerator(parent); generator.setVersion(Version.VERSION); generator.setText(Version.APP_NAME); generator.setUri(Version.URI); return generator; } public Generator newGenerator() { return newGenerator(null); } public Generator newGenerator( Element parent) { return new FOMGenerator((OMContainer)parent,this); } public IRIElement newID( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMIRI(qname,parent,this,parserWrapper); } public IRIElement newID() { return newID(null); } public IRIElement newID( Element parent) { return new FOMIRI(Constants.ID, (OMContainer)parent, this); } public IRIElement newURIElement( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMIRI(qname,parent,this,parserWrapper); } public IRIElement newIRIElement( QName qname, Element parent) { return new FOMIRI(qname, (OMContainer)parent, this); } public Link newLink( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMLink(qname,parent,this,parserWrapper); } public Link newLink() { return newLink(null); } public Link newLink( Element parent) { return new FOMLink((OMContainer)parent,this); } public Person newPerson( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMPerson(qname, parent, this, parserWrapper); } public Person newPerson( QName qname, Element parent) { return new FOMPerson(qname, (OMContainer)parent,this); } public Source newSource( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMSource(qname,parent,this,parserWrapper); } public Source newSource() { return newSource(null); } public Source newSource( Element parent) { return new FOMSource((OMContainer)parent,this); } public Text newText( QName qname, Text.Type type, OMContainer parent, OMXMLParserWrapper parserWrapper) { if (type == null) type = Text.Type.TEXT; return new FOMText(type, qname, parent, this, parserWrapper); } public Text newText( QName qname, Text.Type type) { return newText(qname, type, null); } public Text newText( QName qname, Text.Type type, Element parent) { if (type == null) type = Text.Type.TEXT; return new FOMText(type, qname, (OMContainer)parent,this); } public <T extends Element>T newElement(QName qname) { return (T)newElement(qname, null); } public <T extends Element>T newElement( QName qname, Base parent) { return (T)newExtensionElement(qname, parent); } public <T extends Element>T newExtensionElement(QName qname) { return (T)newExtensionElement(qname, (OMContainer)null); } public <T extends Element>T newExtensionElement( QName qname, Base parent) { return (T)newExtensionElement(qname, (OMContainer)parent); } private <T extends Element>T newExtensionElement( QName qname, OMContainer parent) { String ns = qname.getNamespaceURI(); Element el = newExtensionElement(qname, parent, null); return (T)((ATOM_NS.equals(ns) || APP_NS.equals(ns)) ? el : factoriesMap.getElementWrapper(el)); } private <T extends Element>T newExtensionElement( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { // Element element = (parserWrapper == null) ? // new FOMExtensibleElement(qname, parent, this) : // new FOMExtensibleElement(qname, parent, this, parserWrapper); Element element = (parserWrapper == null) ? (Element)createElement(qname,parent,this,null) : (Element)createElement(qname,parent,(FOMBuilder)parserWrapper); return (T) element; } public Control newControl() { return newControl(null); } public Control newControl(Element parent) { return new FOMControl((OMContainer)parent,this); } public Control newControl( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMControl(qname, parent,this,parserWrapper); } public DateTime newPublished() { return newPublished(null); } public DateTime newPublished(Element parent) { return newDateTime(Constants.PUBLISHED, parent); } public DateTime newUpdated() { return newUpdated(null); } public DateTime newUpdated(Element parent) { return newDateTime(Constants.UPDATED, parent); } public DateTime newEdited() { return newEdited(null); } public DateTime newEdited(Element parent) { return newDateTime(Constants.EDITED, parent); } public IRIElement newIcon() { return newIcon(null); } public IRIElement newIcon(Element parent) { return newIRIElement(Constants.ICON, parent); } public IRIElement newLogo() { return newLogo(null); } public IRIElement newLogo(Element parent) { return newIRIElement(Constants.LOGO, parent); } public IRIElement newUri() { return newUri(null); } public IRIElement newUri(Element parent) { return newIRIElement(Constants.URI, parent); } public Person newAuthor() { return newAuthor(null); } public Person newAuthor(Element parent) { return newPerson(Constants.AUTHOR, parent); } public Person newContributor() { return newContributor(null); } public Person newContributor( Element parent) { return newPerson(Constants.CONTRIBUTOR, parent); } public Text newTitle() { return newTitle(Text.Type.TEXT); } public Text newTitle(Element parent) { return newTitle(Text.Type.TEXT, parent); } public Text newTitle(Text.Type type) { return newTitle(type, null); } public Text newTitle(Text.Type type, Element parent) { return newText(Constants.TITLE, type, parent); } public Text newSubtitle() { return newSubtitle(Text.Type.TEXT); } public Text newSubtitle(Element parent) { return newSubtitle(Text.Type.TEXT, parent); } public Text newSubtitle(Text.Type type) { return newSubtitle(type, null); } public Text newSubtitle(Text.Type type, Element parent) { return newText(Constants.SUBTITLE, type, parent); } public Text newSummary() { return newSummary(Text.Type.TEXT); } public Text newSummary(Element parent) { return newSummary(Text.Type.TEXT, parent); } public Text newSummary(Text.Type type) { return newSummary(type, null); } public Text newSummary(Text.Type type, Element parent) { return newText(Constants.SUMMARY, type, parent); } public Text newRights() { return newRights(Text.Type.TEXT); } public Text newRights(Element parent) { return newRights(Text.Type.TEXT, parent); } public Text newRights(Text.Type type) { return newRights(type, null); } public Text newRights(Text.Type type, Element parent) { return newText(Constants.RIGHTS, type, parent); } public Element newName() { return newName(null); } public Element newName(Element parent) { return newElement(Constants.NAME, parent); } public Element newEmail() { return newEmail(null); } public Element newEmail(Element parent) { return newElement(Constants.EMAIL, parent); } public Div newDiv() { return newDiv(null); } public Div newDiv(Base parent) { return new FOMDiv(DIV, (OMContainer)parent,this); } public Div newDiv( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMDiv(qname,parent,this,parserWrapper); } public Element newElement( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMExtensibleElement(qname,parent,this,parserWrapper); } protected OMElement createElement( QName qname, OMContainer parent, OMFactory factory, Object objecttype) { OMElement element = null; OMNamespace namespace = this.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()); if (FEED.equals(qname)) { element = new FOMFeed(qname.getLocalPart(), namespace, parent, factory); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = new FOMService(qname.getLocalPart(), namespace, parent, factory); } else if (ENTRY.equals(qname)) { element = new FOMEntry(qname.getLocalPart(), namespace, parent, factory); } else if (AUTHOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORY.equals(qname)) { element = new FOMCategory(qname.getLocalPart(), namespace, parent, factory); } else if (CONTENT.equals(qname)) { Content.Type type = (Content.Type) objecttype; element = new FOMContent(qname.getLocalPart(), namespace, type, parent, factory); } else if (CONTRIBUTOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (GENERATOR.equals(qname)) { element = new FOMGenerator(qname.getLocalPart(), namespace, parent, factory); } else if (ICON.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (ID.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LOGO.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LINK.equals(qname)) { element = new FOMLink(qname.getLocalPart(), namespace, parent, factory); } else if (PUBLISHED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (RIGHTS.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SOURCE.equals(qname)) { element = new FOMSource(qname.getLocalPart(), namespace, parent, factory); } else if (SUBTITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SUMMARY.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (TITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (UPDATED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = new FOMWorkspace(qname.getLocalPart(), namespace, parent, factory); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = new FOMCollection(qname.getLocalPart(), namespace, parent, factory); } else if (NAME.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (EMAIL.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (URI.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = new FOMControl(qname.getLocalPart(), namespace, parent, factory); } else if (DIV.equals(qname)) { element = new FOMDiv(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = new FOMCategories(qname.getLocalPart(), namespace, parent, factory); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = (OMElement) new FOMExtensibleElement( - qname.getLocalPart(), namespace, parent, this); + qname, parent, this); + } else { + element = (OMElement) new FOMExtensibleElement(qname,null,this); } return element; } protected OMElement createElement( QName qname, OMContainer parent, FOMBuilder builder) { OMElement element = null; if (FEED.equals(qname)) { element = (OMElement) newFeed(qname, parent, builder); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = (OMElement) newService(qname, parent, builder); } else if (ENTRY.equals(qname)) { element = (OMElement) newEntry(qname, parent, builder); } else if (AUTHOR.equals(qname)) { element = (OMElement) newPerson(qname, parent, builder); } else if (CATEGORY.equals(qname)) { element = (OMElement) newCategory(qname, parent, builder); } else if (CONTENT.equals(qname)) { Content.Type type = builder.getContentType(); element = (OMElement) newContent(qname, type, parent, builder); } else if (CONTRIBUTOR.equals(qname)) { element = (OMElement) newPerson(qname, parent, builder); } else if (GENERATOR.equals(qname)) { element = (OMElement) newGenerator(qname, parent, builder); } else if (ICON.equals(qname)) { element = (OMElement) newURIElement(qname, parent, builder); } else if (ID.equals(qname)) { element = (OMElement) newID(qname, parent, builder); } else if (LOGO.equals(qname)) { element = (OMElement) newURIElement(qname, parent, builder); } else if (LINK.equals(qname)) { element = (OMElement) newLink(qname, parent, builder); } else if (PUBLISHED.equals(qname)) { element = (OMElement) newDateTimeElement(qname, parent, builder); } else if (RIGHTS.equals(qname)) { Text.Type type = builder.getTextType(); element = (OMElement) newText(qname, type, parent, builder); } else if (SOURCE.equals(qname)) { element = (OMElement) newSource(qname, parent, builder); } else if (SUBTITLE.equals(qname)) { Text.Type type = builder.getTextType(); element = (OMElement) newText(qname, type, parent, builder); } else if (SUMMARY.equals(qname)) { Text.Type type = builder.getTextType(); element = (OMElement) newText(qname, type, parent, builder); } else if (TITLE.equals(qname)) { Text.Type type = builder.getTextType(); element = (OMElement) newText(qname, type, parent, builder); } else if (UPDATED.equals(qname)) { element = (OMElement) newDateTimeElement(qname, parent, builder); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = (OMElement) newWorkspace(qname, parent, builder); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = (OMElement) newCollection(qname, parent, builder); } else if (NAME.equals(qname)) { element = (OMElement) new FOMElement(qname,parent,this,builder); } else if (EMAIL.equals(qname)) { element = (OMElement) new FOMElement(qname,parent,this,builder); } else if (URI.equals(qname)) { element = (OMElement) newURIElement(qname, parent, builder); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = (OMElement) newControl(qname, parent, builder); } else if (DIV.equals(qname)) { element = (OMElement) newDiv(qname, parent, builder); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = (OMElement) newCategories(qname, parent, builder); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = (OMElement) newDateTimeElement(qname, parent, builder); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = (OMElement) new FOMExtensibleElement(qname, parent, this,builder); } return element; } public void registerExtension(ExtensionFactory factory) { factoriesMap.addFactory(factory); } public Categories newCategories() { Document<Categories> doc = newDocument(); return newCategories(doc); } public Categories newCategories(Base parent) { return new FOMCategories((OMContainer)parent, this); } public Categories newCategories( QName qname, OMContainer parent, OMXMLParserWrapper parserWrapper) { return new FOMCategories(qname,parent, this, parserWrapper); } public String newUuidUri() { return FOMHelper.generateUuid(); } // public void setElementWrapper(Element internal, Element wrapper) { // factoriesMap.setElementWrapper(internal, wrapper); // } // public <T extends Element> T getElementWrapper(Element internal) { if (internal == null) return null; String ns = internal.getQName().getNamespaceURI(); return (T) ((ATOM_NS.equals(ns) || APP_NS.equals(ns) || internal.getQName().equals(DIV)) ? internal : factoriesMap.getElementWrapper(internal)); } public String[] getNamespaces() { return factoriesMap.getNamespaces(); } public boolean handlesNamespace(String namespace) { return factoriesMap.handlesNamespace(namespace); } public Abdera getAbdera() { return abdera; } public <T extends Base> String getMimeType(T base) { String type = factoriesMap.getMimeType(base); return type; } public String[] listExtensionFactories() { return factoriesMap.listExtensionFactories(); } @Override public OMText createOMText(Object arg0, boolean arg1) { return new FOMTextValue(arg0,arg1,this); } @Override public OMText createOMText(OMContainer arg0, char[] arg1, int arg2) { return new FOMTextValue(arg0,arg1,arg2,this); } @Override public OMText createOMText(OMContainer arg0, QName arg1, int arg2) { return new FOMTextValue(arg0,arg1,arg2,this); } @Override public OMText createOMText(OMContainer arg0, QName arg1) { return new FOMTextValue(arg0,arg1,this); } @Override public OMText createOMText(OMContainer arg0, String arg1, int arg2) { return new FOMTextValue(arg0,arg1,arg2,this); } @Override public OMText createOMText(OMContainer arg0, String arg1, String arg2, boolean arg3) { return new FOMTextValue(arg0,arg1,arg2,arg3,this); } @Override public OMText createOMText(OMContainer arg0, String arg1) { return new FOMTextValue(arg0,arg1,this); } @Override public OMText createOMText(String arg0, int arg1) { return new FOMTextValue(arg0,arg1,this); } @Override public OMText createOMText(String arg0, OMContainer arg1, OMXMLParserWrapper arg2) { return new FOMTextValue(arg0,arg1,arg2,this); } @Override public OMText createOMText(String arg0, String arg1, boolean arg2) { return new FOMTextValue(arg0,arg1,arg2,this); } @Override public OMText createOMText(String arg0) { return new FOMTextValue(arg0,this); } @Override public OMComment createOMComment(OMContainer arg0, String arg1) { return new FOMComment(arg0,arg1,this); } @Override public OMProcessingInstruction createOMProcessingInstruction(OMContainer arg0, String arg1, String arg2) { return new FOMProcessingInstruction(arg0,arg1,arg2,this); } }
true
true
protected OMElement createElement( QName qname, OMContainer parent, OMFactory factory, Object objecttype) { OMElement element = null; OMNamespace namespace = this.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()); if (FEED.equals(qname)) { element = new FOMFeed(qname.getLocalPart(), namespace, parent, factory); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = new FOMService(qname.getLocalPart(), namespace, parent, factory); } else if (ENTRY.equals(qname)) { element = new FOMEntry(qname.getLocalPart(), namespace, parent, factory); } else if (AUTHOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORY.equals(qname)) { element = new FOMCategory(qname.getLocalPart(), namespace, parent, factory); } else if (CONTENT.equals(qname)) { Content.Type type = (Content.Type) objecttype; element = new FOMContent(qname.getLocalPart(), namespace, type, parent, factory); } else if (CONTRIBUTOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (GENERATOR.equals(qname)) { element = new FOMGenerator(qname.getLocalPart(), namespace, parent, factory); } else if (ICON.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (ID.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LOGO.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LINK.equals(qname)) { element = new FOMLink(qname.getLocalPart(), namespace, parent, factory); } else if (PUBLISHED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (RIGHTS.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SOURCE.equals(qname)) { element = new FOMSource(qname.getLocalPart(), namespace, parent, factory); } else if (SUBTITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SUMMARY.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (TITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (UPDATED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = new FOMWorkspace(qname.getLocalPart(), namespace, parent, factory); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = new FOMCollection(qname.getLocalPart(), namespace, parent, factory); } else if (NAME.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (EMAIL.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (URI.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = new FOMControl(qname.getLocalPart(), namespace, parent, factory); } else if (DIV.equals(qname)) { element = new FOMDiv(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = new FOMCategories(qname.getLocalPart(), namespace, parent, factory); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = (OMElement) new FOMExtensibleElement( qname.getLocalPart(), namespace, parent, this); } return element; }
protected OMElement createElement( QName qname, OMContainer parent, OMFactory factory, Object objecttype) { OMElement element = null; OMNamespace namespace = this.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()); if (FEED.equals(qname)) { element = new FOMFeed(qname.getLocalPart(), namespace, parent, factory); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = new FOMService(qname.getLocalPart(), namespace, parent, factory); } else if (ENTRY.equals(qname)) { element = new FOMEntry(qname.getLocalPart(), namespace, parent, factory); } else if (AUTHOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORY.equals(qname)) { element = new FOMCategory(qname.getLocalPart(), namespace, parent, factory); } else if (CONTENT.equals(qname)) { Content.Type type = (Content.Type) objecttype; element = new FOMContent(qname.getLocalPart(), namespace, type, parent, factory); } else if (CONTRIBUTOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (GENERATOR.equals(qname)) { element = new FOMGenerator(qname.getLocalPart(), namespace, parent, factory); } else if (ICON.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (ID.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LOGO.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LINK.equals(qname)) { element = new FOMLink(qname.getLocalPart(), namespace, parent, factory); } else if (PUBLISHED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (RIGHTS.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SOURCE.equals(qname)) { element = new FOMSource(qname.getLocalPart(), namespace, parent, factory); } else if (SUBTITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SUMMARY.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (TITLE.equals(qname)) { Text.Type type = (Text.Type) objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (UPDATED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = new FOMWorkspace(qname.getLocalPart(), namespace, parent, factory); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = new FOMCollection(qname.getLocalPart(), namespace, parent, factory); } else if (NAME.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (EMAIL.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (URI.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = new FOMControl(qname.getLocalPart(), namespace, parent, factory); } else if (DIV.equals(qname)) { element = new FOMDiv(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = new FOMCategories(qname.getLocalPart(), namespace, parent, factory); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = (OMElement) new FOMExtensibleElement( qname, parent, this); } else { element = (OMElement) new FOMExtensibleElement(qname,null,this); } return element; }
diff --git a/src/com/tortel/syslog/MainActivity.java b/src/com/tortel/syslog/MainActivity.java index c4762bb..54012fd 100644 --- a/src/com/tortel/syslog/MainActivity.java +++ b/src/com/tortel/syslog/MainActivity.java @@ -1,610 +1,616 @@ /* SysLog - A simple logging tool * Copyright (C) 2013 Scott Warner <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.tortel.syslog; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.tortel.syslog.exception.*; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.telephony.TelephonyManager; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import eu.chainfire.libsuperuser.Shell; public class MainActivity extends SherlockFragmentActivity { private static final String TAG = "SysLog"; private static final String LAST_KMSG = "/proc/last_kmsg"; private static final String KEY_KERNEL = "kernel"; private static final String KEY_MAIN = "main"; private static final String KEY_MODEM = "modem"; private static final String KEY_LASTKMSG = "lastKmsg"; //Flags for running threads private static boolean running; private boolean kernelLog; private boolean lastKmsg; private boolean mainLog; private boolean modemLog; private static boolean root; private ProgressDialog dialog; private EditText fileEditText; private EditText notesEditText; private EditText grepEditText; private Spinner grepSpinner; private Menu settingsMenu; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); //Load the logging options SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE); kernelLog = prefs.getBoolean(KEY_KERNEL, true); mainLog = prefs.getBoolean(KEY_MAIN, true); modemLog = prefs.getBoolean(KEY_MODEM, true); lastKmsg = prefs.getBoolean(KEY_LASTKMSG, true); fileEditText = (EditText) findViewById(R.id.file_name); notesEditText = (EditText) findViewById(R.id.notes); grepEditText = (EditText) findViewById(R.id.grep_string); grepSpinner = (Spinner) findViewById(R.id.grep_log); //Create a new shell object if(!root){ new CheckRootTask().execute(); } else { enableLogButton(true); } //Check for last_kmsg and modem new CheckOptionsTask().execute(); //Set the checkboxes setCheckBoxes(); //Hide the keyboard on open getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); if(running){ showRunningDialog(); } } public void onResume(){ super.onResume(); //Load the logging options SharedPreferences prefs = getPreferences(Activity.MODE_PRIVATE); kernelLog = prefs.getBoolean("kernel", true); mainLog = prefs.getBoolean("main", true); modemLog = prefs.getBoolean("modem", true); lastKmsg = prefs.getBoolean("lastKmsg", true); fileEditText = (EditText) findViewById(R.id.file_name); notesEditText = (EditText) findViewById(R.id.notes); setCheckBoxes(); } public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.main_menu, menu); settingsMenu = menu; return true; } public boolean onKeyUp(int keycode, KeyEvent e) { switch (keycode) { case KeyEvent.KEYCODE_MENU: settingsMenu.performIdentifierAction(R.id.full_menu_settings, 0); return true; } return super.onKeyUp(keycode, e); } public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.clean_uncompressed: new CleanUncompressedTask().execute(); return true; case R.id.clean_all: new CleanAllTask().execute(); return true; case R.id.about: showAboutDialog(); return true; case R.id.faq: showFaqDialog(); return true; default: return super.onOptionsItemSelected(item); } } /** * Shows the About dialog box */ private void showAboutDialog(){ AboutDialog dialog = new AboutDialog(); dialog.show(getSupportFragmentManager(), "about"); } /** * Shows the FAQ dialog box */ private void showFaqDialog(){ FaqDialog dialog = new FaqDialog(); dialog.show(getSupportFragmentManager(), "faq"); } /** * Sets the checkboxes according to what the user selected. */ private void setCheckBoxes(){ CheckBox box = (CheckBox) findViewById(R.id.main_log); box.setChecked(mainLog); box = (CheckBox) findViewById(R.id.modem_log); box.setChecked(modemLog); box = (CheckBox) findViewById(R.id.kernel_log); box.setChecked(kernelLog); box = (CheckBox) findViewById(R.id.last_kmsg); box.setChecked(lastKmsg); } /** * Logging options were changed * @param v */ public void logChange(View v){ CheckBox box = (CheckBox) v; Editor prefs = getPreferences(Activity.MODE_PRIVATE).edit(); switch(box.getId()){ case R.id.kernel_log: kernelLog = box.isChecked(); prefs.putBoolean(KEY_KERNEL, kernelLog); break; case R.id.last_kmsg: lastKmsg = box.isChecked(); prefs.putBoolean(KEY_LASTKMSG, lastKmsg); break; case R.id.main_log: mainLog = box.isChecked(); prefs.putBoolean(KEY_MAIN, mainLog); break; case R.id.modem_log: modemLog = box.isChecked(); prefs.putBoolean(KEY_MODEM, modemLog); break; } //Make sure that at least one type is selected enableLogButton(mainLog || lastKmsg || modemLog || kernelLog); //Save the settings prefs.apply(); } private void enableLogButton(boolean flag){ Button button = (Button) findViewById(R.id.take_log); button.setEnabled(flag); button.setText(R.string.take_log); } /** * Start the logging process * @param v */ public void startLog(View v){ //Check for external storage if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ //Build the command RunCommand command = new RunCommand(); //Log flags command.setKernelLog(kernelLog); command.setLastKernelLog(lastKmsg); command.setMainLog(mainLog); command.setModemLog(modemLog); //Grep options command.setGrepOption(GrepOption.fromString(grepSpinner.getSelectedItem().toString())); command.setGrep(grepEditText.getText().toString()); //Notes/text command.setAppendText(fileEditText.getText().toString()); command.setNotes(notesEditText.getText().toString()); new LogTask().execute(command); } else { Toast.makeText(this, R.string.storage_err, Toast.LENGTH_LONG).show(); } } /** * Show the running dialog box */ private void showRunningDialog(){ dialog = ProgressDialog.show(MainActivity.this, "", getResources().getString(R.string.working)); } /** * Checks if options are available, such as last_kmsg or a radio. * If they are not available, disable the check boxes. */ private class CheckOptionsTask extends AsyncTask<Void, Void, Void>{ private boolean hasLastKmsg = false; private boolean hasRadio = false; protected Void doInBackground(Void... params) { File lastKmsg = new File(LAST_KMSG); hasLastKmsg = lastKmsg.exists(); TelephonyManager manager = (TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE); hasRadio = manager.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE; return null; } protected void onPostExecute(Void param){ if(!hasLastKmsg){ CheckBox lastKmsgBox = (CheckBox) findViewById(R.id.last_kmsg); lastKmsgBox.setChecked(false); lastKmsgBox.setEnabled(false); logChange(lastKmsgBox); } if(!hasRadio){ CheckBox modemCheckBox = (CheckBox) findViewById(R.id.modem_log); modemCheckBox.setChecked(false); modemCheckBox.setEnabled(false); logChange(modemCheckBox); } } } /** * Clean all the saved log files */ private class CleanAllTask extends AsyncTask<Void, Void, Void>{ protected Void doInBackground(Void... params) { String path = Environment.getExternalStorageDirectory().getPath(); path += "/SysLog/*"; Shell.SH.run("rm -rf "+path); return null; } protected void onPostExecute(Void param){ Toast.makeText(getBaseContext(), R.string.done, Toast.LENGTH_SHORT).show(); } } /** * Clean only the uncompressed logs */ private class CleanUncompressedTask extends AsyncTask<Void, Void, Void>{ protected Void doInBackground(Void... params) { String path = Environment.getExternalStorageDirectory().getPath(); path += "/SysLog/*/"; //All the log files end in .log, and there are also notes.txt files String commands[] = new String[2]; commands[0] = "rm "+path+"*.log"; commands[1] = "rm "+path+"*.txt"; Shell.SH.run(commands); return null; } protected void onPostExecute(Void param){ Toast.makeText(getBaseContext(), R.string.done, Toast.LENGTH_SHORT).show(); } } private class CheckRootTask extends AsyncTask<Void, Void, Boolean>{ protected Boolean doInBackground(Void... params) { root = Shell.SU.available(); return root; } protected void onPostExecute(Boolean root){ //Check for root access if(!root){ //Warn the user TextView noRoot = (TextView) findViewById(R.id.warn_root); noRoot.setVisibility(View.VISIBLE); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN){ //JB and higher needs a different warning noRoot.setText(R.string.noroot_jb); } } enableLogButton(true); } } private class LogTask extends AsyncTask<RunCommand, Void, Result> { private String archivePath; private String shortPath; protected void onPreExecute(){ showRunningDialog(); running = true; } /** * Process the logs */ protected Result doInBackground(RunCommand... params) { RunCommand command = params[0]; Result result = new Result(false); result.setRoot(root); result.setCommand(command); try{ if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { //Commands to execute List<String> commands = new LinkedList<String>(); //Create the directories String path = Environment.getExternalStorageDirectory().getPath(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US); Date date = new Date(); File nomedia = new File(path+"/SysLog/.nomedia"); path += "/SysLog/"+sdf.format(date)+"/"; File outPath = new File(path); //Check if this path already exists (Happens if you run this multiple times a minute if(outPath.exists()){ //Append the seconds path = path.substring(0, path.length()-1) +"."+Calendar.getInstance().get(Calendar.SECOND)+"/"; outPath = new File(path); Log.v(TAG, "Path already exists, added seconds"); } Log.v(TAG, "Path: "+path); //Make the directory if(!outPath.mkdirs() && !outPath.isDirectory()){ throw new CreateFolderException(); } //Put a .nomedia file in the directory if(!nomedia.exists()){ try { nomedia.createNewFile(); } catch (IOException e) { Log.e(TAG, "Failed to create .nomedia file", e); } } /* * If the system is 4.3, some superuser setups (CM10.2) have issues accessing * the normal external storage path. Replace the first portion of the path * with /data/media/{UID} */ String rootPath = path; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ rootPath = path.replaceAll("/storage/emulated/", "/data/media/"); Log.v(TAG, "Using path "+path+" for root commands"); } //Commands to dump the logs if(command.isMainLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MAIN || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -d | grep \""+command.getGrep()+"\" > "+rootPath+"logcat.log"); } else { commands.add("logcat -v time -d -f "+rootPath+"logcat.log"); } } if(command.isKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.KERNEL || command.getGrepOption() == GrepOption.ALL){ commands.add("dmesg | grep \""+command.getGrep()+"\" > "+rootPath+"dmesg.log"); } else { commands.add("dmesg > "+rootPath+"dmesg.log"); } } if(command.isModemLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MODEM || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -b radio -d | grep \""+command.getGrep()+"\" > "+rootPath+"modem.log"); } else { commands.add("logcat -v time -b radio -d -f "+rootPath+"modem.log"); } } if(command.isLastKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.LAST_KERNEL || command.getGrepOption() == GrepOption.ALL){ //Log should be run through grep commands.add("cat "+LAST_KMSG+" | grep \""+command.getGrep()+"\" > "+rootPath+"last_kmsg.log"); } else { //Try copying the last_kmsg over commands.add("cp "+LAST_KMSG+" "+rootPath+"last_kmsg.log"); } } /* * More 4.3+ SU issues - need to chown to media_rw */ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ // Some kernels/systems may not work properly with /* // List the files explicitly commands.add("chown media_rw:media_rw "+rootPath+"/logcat.log"); commands.add("chown media_rw:media_rw "+rootPath+"/dmesg.log"); commands.add("chown media_rw:media_rw "+rootPath+"/modem.log"); commands.add("chown media_rw:media_rw "+rootPath+"/last_kmsg.log"); + // Some Omni-based ROMs/kernels have issues even with the above + // When in doubt, overkill it + commands.add("chmod 666 "+rootPath+"/logcat.log"); + commands.add("chmod 666 "+rootPath+"/dmesg.log"); + commands.add("chmod 666 "+rootPath+"/modem.log"); + commands.add("chmod 666 "+rootPath+"/last_kmsg.log"); } //Run the commands if(root){ if(Shell.SU.run(commands) == null){ throw new RunCommandException(); } } else { if(Shell.SH.run(commands) == null){ throw new RunCommandException(); } } //If there are notes, write them to a notes file if(command.getNotes().length() > 0){ File noteFile = new File(path+"/notes.txt"); FileWriter writer = new FileWriter(noteFile); writer.write(command.getNotes()); try{ writer.close(); } catch(Exception e){ //Ignore } } //Append the users input into the zip if(command.getAppendText().length() > 0){ archivePath = sdf.format(date)+"-"+command.getAppendText()+".zip"; } else { archivePath = sdf.format(date)+".zip"; } ZipWriter writer = new ZipWriter(path, archivePath); archivePath = path+archivePath; //Trim the path for the message shortPath = path.substring( Environment.getExternalStorageDirectory().getPath().length()+1); writer.createZip(); result.setSuccess(true); } else { //Default storage not accessible result.setSuccess(false); result.setMessage(R.string.storage_err); } } catch(CreateFolderException e){ //Error creating the folder e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_folder); } catch (FileNotFoundException e) { //Exception creating zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch (RunCommandException e) { //Exception running commands e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_commands); } catch (NoFilesException e) { //No files to zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip_nofiles); } catch (IOException e) { //Exception writing zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch(Exception e){ //Unknown exception e.printStackTrace(); } return result; } protected void onPostExecute(Result result){ running = false; try{ dialog.dismiss(); } catch (Exception e){ // Should cover null pointer/leaked view exceptions from rotation/ect } if(result.success()){ String msg = getResources().getString(R.string.save_path)+shortPath; Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show(); //Display a share intent Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("application/zip"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+archivePath)); if(isAvailable(getApplicationContext(), share)){ startActivity(share); } else { result.setMessage(R.string.exception_send); result.setException(null); //Show the error dialog. It will have stacktrace/bugreport disabled ExceptionDialog dialog = new ExceptionDialog(); dialog.setResult(result); dialog.show(getSupportFragmentManager(), "exceptionDialog"); } } else { //Show the error dialog ExceptionDialog dialog = new ExceptionDialog(); dialog.setResult(result); dialog.show(getSupportFragmentManager(), "exceptionDialog"); } fileEditText.setText(""); notesEditText.setText(""); grepEditText.setText(""); } } public static boolean isAvailable(Context ctx, Intent intent) { final PackageManager mgr = ctx.getPackageManager(); List<ResolveInfo> list = mgr.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); return list.size() > 0; } }
true
true
protected Result doInBackground(RunCommand... params) { RunCommand command = params[0]; Result result = new Result(false); result.setRoot(root); result.setCommand(command); try{ if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { //Commands to execute List<String> commands = new LinkedList<String>(); //Create the directories String path = Environment.getExternalStorageDirectory().getPath(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US); Date date = new Date(); File nomedia = new File(path+"/SysLog/.nomedia"); path += "/SysLog/"+sdf.format(date)+"/"; File outPath = new File(path); //Check if this path already exists (Happens if you run this multiple times a minute if(outPath.exists()){ //Append the seconds path = path.substring(0, path.length()-1) +"."+Calendar.getInstance().get(Calendar.SECOND)+"/"; outPath = new File(path); Log.v(TAG, "Path already exists, added seconds"); } Log.v(TAG, "Path: "+path); //Make the directory if(!outPath.mkdirs() && !outPath.isDirectory()){ throw new CreateFolderException(); } //Put a .nomedia file in the directory if(!nomedia.exists()){ try { nomedia.createNewFile(); } catch (IOException e) { Log.e(TAG, "Failed to create .nomedia file", e); } } /* * If the system is 4.3, some superuser setups (CM10.2) have issues accessing * the normal external storage path. Replace the first portion of the path * with /data/media/{UID} */ String rootPath = path; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ rootPath = path.replaceAll("/storage/emulated/", "/data/media/"); Log.v(TAG, "Using path "+path+" for root commands"); } //Commands to dump the logs if(command.isMainLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MAIN || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -d | grep \""+command.getGrep()+"\" > "+rootPath+"logcat.log"); } else { commands.add("logcat -v time -d -f "+rootPath+"logcat.log"); } } if(command.isKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.KERNEL || command.getGrepOption() == GrepOption.ALL){ commands.add("dmesg | grep \""+command.getGrep()+"\" > "+rootPath+"dmesg.log"); } else { commands.add("dmesg > "+rootPath+"dmesg.log"); } } if(command.isModemLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MODEM || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -b radio -d | grep \""+command.getGrep()+"\" > "+rootPath+"modem.log"); } else { commands.add("logcat -v time -b radio -d -f "+rootPath+"modem.log"); } } if(command.isLastKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.LAST_KERNEL || command.getGrepOption() == GrepOption.ALL){ //Log should be run through grep commands.add("cat "+LAST_KMSG+" | grep \""+command.getGrep()+"\" > "+rootPath+"last_kmsg.log"); } else { //Try copying the last_kmsg over commands.add("cp "+LAST_KMSG+" "+rootPath+"last_kmsg.log"); } } /* * More 4.3+ SU issues - need to chown to media_rw */ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ // Some kernels/systems may not work properly with /* // List the files explicitly commands.add("chown media_rw:media_rw "+rootPath+"/logcat.log"); commands.add("chown media_rw:media_rw "+rootPath+"/dmesg.log"); commands.add("chown media_rw:media_rw "+rootPath+"/modem.log"); commands.add("chown media_rw:media_rw "+rootPath+"/last_kmsg.log"); } //Run the commands if(root){ if(Shell.SU.run(commands) == null){ throw new RunCommandException(); } } else { if(Shell.SH.run(commands) == null){ throw new RunCommandException(); } } //If there are notes, write them to a notes file if(command.getNotes().length() > 0){ File noteFile = new File(path+"/notes.txt"); FileWriter writer = new FileWriter(noteFile); writer.write(command.getNotes()); try{ writer.close(); } catch(Exception e){ //Ignore } } //Append the users input into the zip if(command.getAppendText().length() > 0){ archivePath = sdf.format(date)+"-"+command.getAppendText()+".zip"; } else { archivePath = sdf.format(date)+".zip"; } ZipWriter writer = new ZipWriter(path, archivePath); archivePath = path+archivePath; //Trim the path for the message shortPath = path.substring( Environment.getExternalStorageDirectory().getPath().length()+1); writer.createZip(); result.setSuccess(true); } else { //Default storage not accessible result.setSuccess(false); result.setMessage(R.string.storage_err); } } catch(CreateFolderException e){ //Error creating the folder e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_folder); } catch (FileNotFoundException e) { //Exception creating zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch (RunCommandException e) { //Exception running commands e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_commands); } catch (NoFilesException e) { //No files to zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip_nofiles); } catch (IOException e) { //Exception writing zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch(Exception e){ //Unknown exception e.printStackTrace(); } return result; }
protected Result doInBackground(RunCommand... params) { RunCommand command = params[0]; Result result = new Result(false); result.setRoot(root); result.setCommand(command); try{ if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { //Commands to execute List<String> commands = new LinkedList<String>(); //Create the directories String path = Environment.getExternalStorageDirectory().getPath(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH.mm", Locale.US); Date date = new Date(); File nomedia = new File(path+"/SysLog/.nomedia"); path += "/SysLog/"+sdf.format(date)+"/"; File outPath = new File(path); //Check if this path already exists (Happens if you run this multiple times a minute if(outPath.exists()){ //Append the seconds path = path.substring(0, path.length()-1) +"."+Calendar.getInstance().get(Calendar.SECOND)+"/"; outPath = new File(path); Log.v(TAG, "Path already exists, added seconds"); } Log.v(TAG, "Path: "+path); //Make the directory if(!outPath.mkdirs() && !outPath.isDirectory()){ throw new CreateFolderException(); } //Put a .nomedia file in the directory if(!nomedia.exists()){ try { nomedia.createNewFile(); } catch (IOException e) { Log.e(TAG, "Failed to create .nomedia file", e); } } /* * If the system is 4.3, some superuser setups (CM10.2) have issues accessing * the normal external storage path. Replace the first portion of the path * with /data/media/{UID} */ String rootPath = path; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ rootPath = path.replaceAll("/storage/emulated/", "/data/media/"); Log.v(TAG, "Using path "+path+" for root commands"); } //Commands to dump the logs if(command.isMainLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MAIN || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -d | grep \""+command.getGrep()+"\" > "+rootPath+"logcat.log"); } else { commands.add("logcat -v time -d -f "+rootPath+"logcat.log"); } } if(command.isKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.KERNEL || command.getGrepOption() == GrepOption.ALL){ commands.add("dmesg | grep \""+command.getGrep()+"\" > "+rootPath+"dmesg.log"); } else { commands.add("dmesg > "+rootPath+"dmesg.log"); } } if(command.isModemLog()){ if(command.grep() && command.getGrepOption() == GrepOption.MODEM || command.getGrepOption() == GrepOption.ALL){ commands.add("logcat -v time -b radio -d | grep \""+command.getGrep()+"\" > "+rootPath+"modem.log"); } else { commands.add("logcat -v time -b radio -d -f "+rootPath+"modem.log"); } } if(command.isLastKernelLog()){ if(command.grep() && command.getGrepOption() == GrepOption.LAST_KERNEL || command.getGrepOption() == GrepOption.ALL){ //Log should be run through grep commands.add("cat "+LAST_KMSG+" | grep \""+command.getGrep()+"\" > "+rootPath+"last_kmsg.log"); } else { //Try copying the last_kmsg over commands.add("cp "+LAST_KMSG+" "+rootPath+"last_kmsg.log"); } } /* * More 4.3+ SU issues - need to chown to media_rw */ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){ // Some kernels/systems may not work properly with /* // List the files explicitly commands.add("chown media_rw:media_rw "+rootPath+"/logcat.log"); commands.add("chown media_rw:media_rw "+rootPath+"/dmesg.log"); commands.add("chown media_rw:media_rw "+rootPath+"/modem.log"); commands.add("chown media_rw:media_rw "+rootPath+"/last_kmsg.log"); // Some Omni-based ROMs/kernels have issues even with the above // When in doubt, overkill it commands.add("chmod 666 "+rootPath+"/logcat.log"); commands.add("chmod 666 "+rootPath+"/dmesg.log"); commands.add("chmod 666 "+rootPath+"/modem.log"); commands.add("chmod 666 "+rootPath+"/last_kmsg.log"); } //Run the commands if(root){ if(Shell.SU.run(commands) == null){ throw new RunCommandException(); } } else { if(Shell.SH.run(commands) == null){ throw new RunCommandException(); } } //If there are notes, write them to a notes file if(command.getNotes().length() > 0){ File noteFile = new File(path+"/notes.txt"); FileWriter writer = new FileWriter(noteFile); writer.write(command.getNotes()); try{ writer.close(); } catch(Exception e){ //Ignore } } //Append the users input into the zip if(command.getAppendText().length() > 0){ archivePath = sdf.format(date)+"-"+command.getAppendText()+".zip"; } else { archivePath = sdf.format(date)+".zip"; } ZipWriter writer = new ZipWriter(path, archivePath); archivePath = path+archivePath; //Trim the path for the message shortPath = path.substring( Environment.getExternalStorageDirectory().getPath().length()+1); writer.createZip(); result.setSuccess(true); } else { //Default storage not accessible result.setSuccess(false); result.setMessage(R.string.storage_err); } } catch(CreateFolderException e){ //Error creating the folder e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_folder); } catch (FileNotFoundException e) { //Exception creating zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch (RunCommandException e) { //Exception running commands e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_commands); } catch (NoFilesException e) { //No files to zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip_nofiles); } catch (IOException e) { //Exception writing zip e.printStackTrace(); result.setException(e); result.setMessage(R.string.exception_zip); } catch(Exception e){ //Unknown exception e.printStackTrace(); } return result; }
diff --git a/src/com/ds/avare/WeatherCache.java b/src/com/ds/avare/WeatherCache.java index 570357a5..b344f1c8 100644 --- a/src/com/ds/avare/WeatherCache.java +++ b/src/com/ds/avare/WeatherCache.java @@ -1,108 +1,114 @@ /* Copyright (c) 2012, Zubair Khan ([email protected]) 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.ds.avare; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import android.content.Context; import android.os.SystemClock; /** * @author zkhan * */ public class WeatherCache { private HashMap<String, String> mMap; private Context mContext; /* * Drop METAR after 30 minutes. */ private static long UPDATE_TIME = 30 * 60 * 1000; /** * */ public WeatherCache(Context context) { mMap = new HashMap<String, String>(); mContext = context; } /** * * @param id * @return */ public String get(String id) { /* * Remove all entries older than update time. */ String weather = null; /* * Save concurrent mod as many tasks update mMap. */ synchronized(mMap) { Iterator<Entry<String, String>> it = mMap.entrySet().iterator(); long now = SystemClock.elapsedRealtime(); while (it.hasNext()) { HashMap.Entry<String, String> pairs = (HashMap.Entry <String, String>)it.next(); String[] tokens = pairs.getValue().split("@"); - long then = Long.parseLong(tokens[1]); - if(Math.abs(now - then) > UPDATE_TIME) { - it.remove(); + long then; + try { + then = Long.parseLong(tokens[1]); + if(Math.abs(now - then) > UPDATE_TIME) { + it.remove(); + } + } + catch (Exception e) { + it.remove(); } } weather = mMap.get(id); } if(null == weather) { /* * Not found in cache */ weather = NetworkHelper.getMETAR(mContext, id); /* * This is some sort of network error, return. */ if(null == weather) { return ""; } weather += NetworkHelper.getTAF(mContext, id); weather = WeatherHelper.formatWeather(weather); /* * Put in hash * @ time it was obtained */ synchronized(mMap) { mMap.put(id, weather + "@" + SystemClock.elapsedRealtime()); } } /* * Now get, remove @ sign */ if(null != weather) { String tokens[] = weather.split("@"); weather = tokens[0]; } return weather; } }
true
true
public String get(String id) { /* * Remove all entries older than update time. */ String weather = null; /* * Save concurrent mod as many tasks update mMap. */ synchronized(mMap) { Iterator<Entry<String, String>> it = mMap.entrySet().iterator(); long now = SystemClock.elapsedRealtime(); while (it.hasNext()) { HashMap.Entry<String, String> pairs = (HashMap.Entry <String, String>)it.next(); String[] tokens = pairs.getValue().split("@"); long then = Long.parseLong(tokens[1]); if(Math.abs(now - then) > UPDATE_TIME) { it.remove(); } } weather = mMap.get(id); } if(null == weather) { /* * Not found in cache */ weather = NetworkHelper.getMETAR(mContext, id); /* * This is some sort of network error, return. */ if(null == weather) { return ""; } weather += NetworkHelper.getTAF(mContext, id); weather = WeatherHelper.formatWeather(weather); /* * Put in hash * @ time it was obtained */ synchronized(mMap) { mMap.put(id, weather + "@" + SystemClock.elapsedRealtime()); } } /* * Now get, remove @ sign */ if(null != weather) { String tokens[] = weather.split("@"); weather = tokens[0]; } return weather; }
public String get(String id) { /* * Remove all entries older than update time. */ String weather = null; /* * Save concurrent mod as many tasks update mMap. */ synchronized(mMap) { Iterator<Entry<String, String>> it = mMap.entrySet().iterator(); long now = SystemClock.elapsedRealtime(); while (it.hasNext()) { HashMap.Entry<String, String> pairs = (HashMap.Entry <String, String>)it.next(); String[] tokens = pairs.getValue().split("@"); long then; try { then = Long.parseLong(tokens[1]); if(Math.abs(now - then) > UPDATE_TIME) { it.remove(); } } catch (Exception e) { it.remove(); } } weather = mMap.get(id); } if(null == weather) { /* * Not found in cache */ weather = NetworkHelper.getMETAR(mContext, id); /* * This is some sort of network error, return. */ if(null == weather) { return ""; } weather += NetworkHelper.getTAF(mContext, id); weather = WeatherHelper.formatWeather(weather); /* * Put in hash * @ time it was obtained */ synchronized(mMap) { mMap.put(id, weather + "@" + SystemClock.elapsedRealtime()); } } /* * Now get, remove @ sign */ if(null != weather) { String tokens[] = weather.split("@"); weather = tokens[0]; } return weather; }
diff --git a/src/com/android/settings/ChooseLockSettingsHelper.java b/src/com/android/settings/ChooseLockSettingsHelper.java index 5fe3118fb..6382891fe 100644 --- a/src/com/android/settings/ChooseLockSettingsHelper.java +++ b/src/com/android/settings/ChooseLockSettingsHelper.java @@ -1,86 +1,87 @@ /* * 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.settings; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.Intent; import com.android.internal.widget.LockPatternUtils; public class ChooseLockSettingsHelper { private LockPatternUtils mLockPatternUtils; private Activity mActivity; public ChooseLockSettingsHelper(Activity activity) { mActivity = activity; mLockPatternUtils = new LockPatternUtils(activity); } public LockPatternUtils utils() { return mLockPatternUtils; } /** * If a pattern, password or PIN exists, prompt the user before allowing them to change it. * @return true if one exists and we launched an activity to confirm it * @see #onActivityResult(int, int, android.content.Intent) */ protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: + case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: launched = confirmPassword(request); break; } return launched; } /** * Launch screen to confirm the existing lock pattern. * @see #onActivityResult(int, int, android.content.Intent) * @return true if we launched an activity to confirm pattern */ private boolean confirmPattern(int request) { if (!mLockPatternUtils.isLockPatternEnabled() || !mLockPatternUtils.savedPatternExists()) { return false; } final Intent intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.ConfirmLockPattern"); mActivity.startActivityForResult(intent, request); return true; } /** * Launch screen to confirm the existing lock password. * @see #onActivityResult(int, int, android.content.Intent) * @return true if we launched an activity to confirm password */ private boolean confirmPassword(int request) { if (!mLockPatternUtils.isLockPasswordEnabled()) return false; final Intent intent = new Intent(); intent.setClassName("com.android.settings", "com.android.settings.ConfirmLockPassword"); mActivity.startActivityForResult(intent, request); return true; } }
true
true
protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: launched = confirmPassword(request); break; } return launched; }
protected boolean launchConfirmationActivity(int request) { boolean launched = false; switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) { case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: launched = confirmPattern(request); break; case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: launched = confirmPassword(request); break; } return launched; }
diff --git a/src/java/davmail/ui/tray/SwtGatewayTray.java b/src/java/davmail/ui/tray/SwtGatewayTray.java index 787ee6c..1e4a890 100644 --- a/src/java/davmail/ui/tray/SwtGatewayTray.java +++ b/src/java/davmail/ui/tray/SwtGatewayTray.java @@ -1,355 +1,361 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail.ui.tray; import davmail.Settings; import davmail.BundleMessage; import davmail.DavGateway; import davmail.ui.AboutFrame; import davmail.ui.SettingsFrame; import org.apache.log4j.Logger; import org.apache.log4j.Level; import org.apache.log4j.lf5.LF5Appender; import org.apache.log4j.lf5.LogLevel; import org.apache.log4j.lf5.viewer.LogBrokerMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.*; import javax.swing.*; import java.io.IOException; import java.net.URL; /** * Tray icon handler based on SWT */ public class SwtGatewayTray implements DavGatewayTrayInterface { protected SwtGatewayTray() { } private static TrayItem trayItem; private static java.awt.Image awtImage; private static Image image; private static Image image2; private static Image inactiveImage; private static Display display; private static Shell shell; private LogBrokerMonitor logBrokerMonitor; private boolean isActive = true; private boolean isReady; private final Thread mainThread = Thread.currentThread(); /** * Return AWT Image icon for frame title. * * @return frame icon */ public java.awt.Image getFrameIcon() { return awtImage; } /** * Switch tray icon between active and standby icon. */ public void switchIcon() { isActive = true; display.syncExec(new Runnable() { public void run() { if (trayItem.getImage().equals(image)) { trayItem.setImage(image2); } else { trayItem.setImage(image); } } }); } /** * Set tray icon to inactive (network down) */ public void resetIcon() { display.syncExec(new Runnable() { public void run() { trayItem.setImage(image); } }); } /** * Set tray icon to inactive (network down) */ public void inactiveIcon() { isActive = false; display.syncExec(new Runnable() { public void run() { trayItem.setImage(inactiveImage); } }); } /** * Check if current tray status is inactive (network down). * * @return true if inactive */ public boolean isActive() { return isActive; } /** * Log and display balloon message according to log level. * * @param message text message * @param level log level */ public void displayMessage(final String message, final Level level) { if (trayItem != null) { display.asyncExec(new Runnable() { public void run() { int messageType = 0; if (level.equals(Level.INFO)) { messageType = SWT.ICON_INFORMATION; } else if (level.equals(Level.WARN)) { messageType = SWT.ICON_WARNING; } else if (level.equals(Level.ERROR)) { messageType = SWT.ICON_ERROR; } if (messageType != 0) { final ToolTip toolTip = new ToolTip(shell, SWT.BALLOON | messageType); toolTip.setText(BundleMessage.format("UI_DAVMAIL_GATEWAY")); toolTip.setMessage(message); trayItem.setToolTip(toolTip); toolTip.setVisible(true); } trayItem.setToolTipText(BundleMessage.format("UI_DAVMAIL_GATEWAY") + '\n' + message); } }); } } /** * Load image with current class loader. * * @param fileName image resource file name * @return image */ public static Image loadSwtImage(String fileName) { Image result = null; try { ClassLoader classloader = DavGatewayTray.class.getClassLoader(); URL imageUrl = classloader.getResource(fileName); result = new Image(display, imageUrl.openStream()); } catch (IOException e) { DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_LOAD_IMAGE"), e); } return result; } /** * Create tray icon and register frame listeners. */ public void init() { // set native look and feel try { String lafClassName = UIManager.getSystemLookAndFeelClassName(); // workaround for bug when SWT and AWT both try to access Gtk if (lafClassName.indexOf("gtk") > 0) { lafClassName = UIManager.getCrossPlatformLookAndFeelClassName(); } UIManager.setLookAndFeel(lafClassName); } catch (Exception e) { DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_SET_LOOK_AND_FEEL")); } new Thread("SWT") { @Override public void run() { try { display = new Display(); shell = new Shell(display); final Tray tray = display.getSystemTray(); if (tray != null) { trayItem = new TrayItem(tray, SWT.NONE); trayItem.setToolTipText(BundleMessage.format("UI_DAVMAIL_GATEWAY")); awtImage = DavGatewayTray.loadImage(AwtGatewayTray.TRAY_PNG); image = loadSwtImage(AwtGatewayTray.TRAY_PNG); image2 = loadSwtImage(AwtGatewayTray.TRAY_ACTIVE_PNG); inactiveImage = loadSwtImage(AwtGatewayTray.TRAY_INACTIVE_PNG); trayItem.setImage(image); // create a popup menu final Menu popup = new Menu(shell, SWT.POP_UP); trayItem.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { display.asyncExec( new Runnable() { public void run() { popup.setVisible(true); } }); } }); MenuItem aboutItem = new MenuItem(popup, SWT.PUSH); aboutItem.setText(BundleMessage.format("UI_ABOUT")); final AboutFrame aboutFrame = new AboutFrame(); aboutItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { aboutFrame.update(); aboutFrame.setVisible(true); } }); } }); final SettingsFrame settingsFrame = new SettingsFrame(); trayItem.addListener(SWT.DefaultSelection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); // create menu item for the default action MenuItem defaultItem = new MenuItem(popup, SWT.PUSH); defaultItem.setText(BundleMessage.format("UI_SETTINGS")); defaultItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); MenuItem logItem = new MenuItem(popup, SWT.PUSH); logItem.setText(BundleMessage.format("UI_SHOW_LOGS")); logItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { Logger rootLogger = Logger.getRootLogger(); LF5Appender lf5Appender = (LF5Appender) rootLogger.getAppender("LF5Appender"); if (lf5Appender == null) { logBrokerMonitor = new LogBrokerMonitor(LogLevel.getLog4JLevels()) { @Override protected void closeAfterConfirm() { hide(); } }; lf5Appender = new LF5Appender(logBrokerMonitor); lf5Appender.setName("LF5Appender"); rootLogger.addAppender(lf5Appender); } lf5Appender.getLogBrokerMonitor().show(); } }); } }); MenuItem exitItem = new MenuItem(popup, SWT.PUSH); exitItem.setText(BundleMessage.format("UI_EXIT")); exitItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { DavGateway.stop(); shell.dispose(); } }); // display settings frame on first start if (Settings.isFirstStart()) { settingsFrame.setVisible(true); } synchronized (mainThread) { // ready isReady = true; mainThread.notifyAll(); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } if (trayItem != null) { trayItem.dispose(); trayItem = null; } if (image != null) { image.dispose(); } if (image2 != null) { image2.dispose(); } - display.dispose(); + try { + if (!display.isDisposed()) { + display.dispose(); + } + } catch (Exception e) { + // already disposed + } // dispose AWT frames settingsFrame.dispose(); aboutFrame.dispose(); if (logBrokerMonitor != null) { logBrokerMonitor.dispose(); } } } catch (Exception exc) { DavGatewayTray.error(exc); } // make sure we do exit System.exit(0); } }.start(); while (true) { // wait for SWT init try { synchronized (mainThread) { if (isReady) { break; } mainThread.wait(1000); } } catch (InterruptedException e) { DavGatewayTray.error(new BundleMessage("LOG_ERROR_WAITING_FOR_SWT_INIT"), e); } } } }
true
true
public void init() { // set native look and feel try { String lafClassName = UIManager.getSystemLookAndFeelClassName(); // workaround for bug when SWT and AWT both try to access Gtk if (lafClassName.indexOf("gtk") > 0) { lafClassName = UIManager.getCrossPlatformLookAndFeelClassName(); } UIManager.setLookAndFeel(lafClassName); } catch (Exception e) { DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_SET_LOOK_AND_FEEL")); } new Thread("SWT") { @Override public void run() { try { display = new Display(); shell = new Shell(display); final Tray tray = display.getSystemTray(); if (tray != null) { trayItem = new TrayItem(tray, SWT.NONE); trayItem.setToolTipText(BundleMessage.format("UI_DAVMAIL_GATEWAY")); awtImage = DavGatewayTray.loadImage(AwtGatewayTray.TRAY_PNG); image = loadSwtImage(AwtGatewayTray.TRAY_PNG); image2 = loadSwtImage(AwtGatewayTray.TRAY_ACTIVE_PNG); inactiveImage = loadSwtImage(AwtGatewayTray.TRAY_INACTIVE_PNG); trayItem.setImage(image); // create a popup menu final Menu popup = new Menu(shell, SWT.POP_UP); trayItem.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { display.asyncExec( new Runnable() { public void run() { popup.setVisible(true); } }); } }); MenuItem aboutItem = new MenuItem(popup, SWT.PUSH); aboutItem.setText(BundleMessage.format("UI_ABOUT")); final AboutFrame aboutFrame = new AboutFrame(); aboutItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { aboutFrame.update(); aboutFrame.setVisible(true); } }); } }); final SettingsFrame settingsFrame = new SettingsFrame(); trayItem.addListener(SWT.DefaultSelection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); // create menu item for the default action MenuItem defaultItem = new MenuItem(popup, SWT.PUSH); defaultItem.setText(BundleMessage.format("UI_SETTINGS")); defaultItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); MenuItem logItem = new MenuItem(popup, SWT.PUSH); logItem.setText(BundleMessage.format("UI_SHOW_LOGS")); logItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { Logger rootLogger = Logger.getRootLogger(); LF5Appender lf5Appender = (LF5Appender) rootLogger.getAppender("LF5Appender"); if (lf5Appender == null) { logBrokerMonitor = new LogBrokerMonitor(LogLevel.getLog4JLevels()) { @Override protected void closeAfterConfirm() { hide(); } }; lf5Appender = new LF5Appender(logBrokerMonitor); lf5Appender.setName("LF5Appender"); rootLogger.addAppender(lf5Appender); } lf5Appender.getLogBrokerMonitor().show(); } }); } }); MenuItem exitItem = new MenuItem(popup, SWT.PUSH); exitItem.setText(BundleMessage.format("UI_EXIT")); exitItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { DavGateway.stop(); shell.dispose(); } }); // display settings frame on first start if (Settings.isFirstStart()) { settingsFrame.setVisible(true); } synchronized (mainThread) { // ready isReady = true; mainThread.notifyAll(); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } if (trayItem != null) { trayItem.dispose(); trayItem = null; } if (image != null) { image.dispose(); } if (image2 != null) { image2.dispose(); } display.dispose(); // dispose AWT frames settingsFrame.dispose(); aboutFrame.dispose(); if (logBrokerMonitor != null) { logBrokerMonitor.dispose(); } } } catch (Exception exc) { DavGatewayTray.error(exc); } // make sure we do exit System.exit(0); } }.start(); while (true) { // wait for SWT init try { synchronized (mainThread) { if (isReady) { break; } mainThread.wait(1000); } } catch (InterruptedException e) { DavGatewayTray.error(new BundleMessage("LOG_ERROR_WAITING_FOR_SWT_INIT"), e); } } }
public void init() { // set native look and feel try { String lafClassName = UIManager.getSystemLookAndFeelClassName(); // workaround for bug when SWT and AWT both try to access Gtk if (lafClassName.indexOf("gtk") > 0) { lafClassName = UIManager.getCrossPlatformLookAndFeelClassName(); } UIManager.setLookAndFeel(lafClassName); } catch (Exception e) { DavGatewayTray.warn(new BundleMessage("LOG_UNABLE_TO_SET_LOOK_AND_FEEL")); } new Thread("SWT") { @Override public void run() { try { display = new Display(); shell = new Shell(display); final Tray tray = display.getSystemTray(); if (tray != null) { trayItem = new TrayItem(tray, SWT.NONE); trayItem.setToolTipText(BundleMessage.format("UI_DAVMAIL_GATEWAY")); awtImage = DavGatewayTray.loadImage(AwtGatewayTray.TRAY_PNG); image = loadSwtImage(AwtGatewayTray.TRAY_PNG); image2 = loadSwtImage(AwtGatewayTray.TRAY_ACTIVE_PNG); inactiveImage = loadSwtImage(AwtGatewayTray.TRAY_INACTIVE_PNG); trayItem.setImage(image); // create a popup menu final Menu popup = new Menu(shell, SWT.POP_UP); trayItem.addListener(SWT.MenuDetect, new Listener() { public void handleEvent(Event event) { display.asyncExec( new Runnable() { public void run() { popup.setVisible(true); } }); } }); MenuItem aboutItem = new MenuItem(popup, SWT.PUSH); aboutItem.setText(BundleMessage.format("UI_ABOUT")); final AboutFrame aboutFrame = new AboutFrame(); aboutItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { aboutFrame.update(); aboutFrame.setVisible(true); } }); } }); final SettingsFrame settingsFrame = new SettingsFrame(); trayItem.addListener(SWT.DefaultSelection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); // create menu item for the default action MenuItem defaultItem = new MenuItem(popup, SWT.PUSH); defaultItem.setText(BundleMessage.format("UI_SETTINGS")); defaultItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { settingsFrame.reload(); settingsFrame.setVisible(true); // workaround for focus on first open settingsFrame.setVisible(true); } }); } }); MenuItem logItem = new MenuItem(popup, SWT.PUSH); logItem.setText(BundleMessage.format("UI_SHOW_LOGS")); logItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { SwingUtilities.invokeLater( new Runnable() { public void run() { Logger rootLogger = Logger.getRootLogger(); LF5Appender lf5Appender = (LF5Appender) rootLogger.getAppender("LF5Appender"); if (lf5Appender == null) { logBrokerMonitor = new LogBrokerMonitor(LogLevel.getLog4JLevels()) { @Override protected void closeAfterConfirm() { hide(); } }; lf5Appender = new LF5Appender(logBrokerMonitor); lf5Appender.setName("LF5Appender"); rootLogger.addAppender(lf5Appender); } lf5Appender.getLogBrokerMonitor().show(); } }); } }); MenuItem exitItem = new MenuItem(popup, SWT.PUSH); exitItem.setText(BundleMessage.format("UI_EXIT")); exitItem.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { DavGateway.stop(); shell.dispose(); } }); // display settings frame on first start if (Settings.isFirstStart()) { settingsFrame.setVisible(true); } synchronized (mainThread) { // ready isReady = true; mainThread.notifyAll(); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } if (trayItem != null) { trayItem.dispose(); trayItem = null; } if (image != null) { image.dispose(); } if (image2 != null) { image2.dispose(); } try { if (!display.isDisposed()) { display.dispose(); } } catch (Exception e) { // already disposed } // dispose AWT frames settingsFrame.dispose(); aboutFrame.dispose(); if (logBrokerMonitor != null) { logBrokerMonitor.dispose(); } } } catch (Exception exc) { DavGatewayTray.error(exc); } // make sure we do exit System.exit(0); } }.start(); while (true) { // wait for SWT init try { synchronized (mainThread) { if (isReady) { break; } mainThread.wait(1000); } } catch (InterruptedException e) { DavGatewayTray.error(new BundleMessage("LOG_ERROR_WAITING_FOR_SWT_INIT"), e); } } }
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/ViewInHierarchyUtils.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/ViewInHierarchyUtils.java index a5fffa6c..f8f73a0d 100644 --- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/ViewInHierarchyUtils.java +++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/ViewInHierarchyUtils.java @@ -1,241 +1,243 @@ package gov.nih.nci.evs.browser.utils; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag; import org.LexGrid.LexBIG.Utility.Constructors; import org.json.JSONArray; import org.json.JSONObject; import org.lexevs.tree.json.JsonConverter; import org.lexevs.tree.json.JsonConverterFactory; import org.lexevs.tree.model.LexEvsTree; import org.lexevs.tree.model.LexEvsTreeNode; import org.lexevs.tree.model.LexEvsTreeNode.ExpandableStatus; import org.lexevs.tree.service.TreeService; import org.lexevs.tree.service.TreeServiceFactory; /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. 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. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES 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. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Modification history Initial implementation [email protected] * */ // Note: Version with the has more (...) nodes feature. public class ViewInHierarchyUtils { int has_more_node_knt = 0; public ViewInHierarchyUtils() { has_more_node_knt = 0; } private static void println(PrintWriter out, String text) { gov.nih.nci.evs.browser.servlet.AjaxServlet.println(out, text); } private String replaceNodeID(String code) { code = code.replaceAll(":", "_"); return code; } public ViewInHierarchyUtils(String codingScheme, String version, String code) { has_more_node_knt = 0; try { PrintWriter pw = new PrintWriter(System.out, true); printTree(pw, codingScheme, version, code); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } } public void printTree(PrintWriter out, String codingScheme, String version, String code) { TreeService service = TreeServiceFactory.getInstance().getTreeService( RemoteServerUtil.createLexBIGService()); long start = System.currentTimeMillis(); CodingSchemeVersionOrTag csvt = null; if (version != null && version.length() > 0) csvt = Constructors.createCodingSchemeVersionOrTagFromVersion(version); String namespace = DataUtils.getNamespaceByCode(codingScheme, version, code); System.out.println("(*************) namespace: " + namespace); LexEvsTree tree = service.getTree(codingScheme, csvt, code, namespace); List<LexEvsTreeNode> listEvsTreeNode = service.getEvsTreeConverter() .buildEvsTreePathFromRootTree(tree.getCurrentFocus()); LexEvsTreeNode root = null; printTree(out, "", code, root, listEvsTreeNode); } private void printTree(PrintWriter out, String indent, String focus_code, LexEvsTreeNode parent, List<LexEvsTreeNode> nodes) { for (LexEvsTreeNode node : nodes) { char c = ' '; if (node.getExpandableStatus() == LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { c = node.getPathToRootChildren() != null ? '-' : '+'; } printTreeNode(out, indent, focus_code, node, parent); List<LexEvsTreeNode> list_children = node.getPathToRootChildren(); if (list_children != null) { printTree(out, indent + " ", focus_code, node, list_children); } } } private void printTreeNode(PrintWriter out, String indent, String focus_code, LexEvsTreeNode node, LexEvsTreeNode parent) { if (node == null) return; try { LexEvsTreeNode.ExpandableStatus node_status = node.getExpandableStatus(); String image = "[+]"; boolean expandable = true; if (node_status != LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { image = "."; expandable = false; } boolean expanded = false; if (node_status == LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { List<LexEvsTreeNode> list_children = node.getPathToRootChildren(); if (list_children != null && list_children.size() > 0) { expanded = true; } } String parent_code = null; if (parent != null) { parent_code = parent.getCode(); } String parent_id = null; if (parent == null) { parent_id = "root"; } else { parent_id = replaceNodeID("N_" + parent.getCode()); } String code = node.getCode(); boolean isHasMoreNode = false; if (code.compareTo("...") == 0) { + isHasMoreNode = true; has_more_node_knt++; if (parent == null) { code = "root" + "_dot_" + new Integer(has_more_node_knt).toString(); } else { - isHasMoreNode = true; code = parent.getCode() + "_dot_" + new Integer(has_more_node_knt).toString(); } } String node_id = replaceNodeID("N_" + code); String node_label = node.getEntityDescription(); String indentStr = indent + " "; String symbol = getNodeSymbol(node); println(out, ""); println(out, indentStr + "// " + symbol + " " + node_label + "(" + code + ")"); println(out, indentStr + "newNodeDetails = \"javascript:onClickTreeNode('" + code + "');\";"); println(out, indentStr + "newNodeData = { label:\"" + node_label + "\", id:\"" + code + "\", href:newNodeDetails };"); if (expanded) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", true);"); } else if (isHasMoreNode) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } else { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } if (expandable || isHasMoreNode) { println(out, indentStr + node_id + ".isLeaf = false;"); println(out, indentStr + node_id + ".ontology_node_child_count = 1;"); - if (node.getPathToRootChildren() == null && !isHasMoreNode) + //if (node.getPathToRootChildren() == null && !isHasMoreNode) + if (node.getPathToRootChildren() == null) { println(out, indentStr + node_id + ".setDynamicLoad(loadNodeData);"); + } } else { println(out, indentStr + node_id + ".ontology_node_child_count = 0;"); println(out, indentStr + node_id + ".isLeaf = true;"); } if (focus_code.compareTo(code) == 0) { println(out, indentStr + node_id + ".labelStyle = \"ygtvlabel_highlight\";"); } } catch (Exception ex) { } } private static String getNodeSymbol(LexEvsTreeNode node) { String symbol = "@"; if (node.getExpandableStatus() == LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { symbol = node.getPathToRootChildren() != null ? "-" : "+"; } return symbol; } public static void main(String[] args) throws Exception { new ViewInHierarchyUtils("NCI_Thesaurus", "11.09d", "C37927"); // Color } }
false
true
private void printTreeNode(PrintWriter out, String indent, String focus_code, LexEvsTreeNode node, LexEvsTreeNode parent) { if (node == null) return; try { LexEvsTreeNode.ExpandableStatus node_status = node.getExpandableStatus(); String image = "[+]"; boolean expandable = true; if (node_status != LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { image = "."; expandable = false; } boolean expanded = false; if (node_status == LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { List<LexEvsTreeNode> list_children = node.getPathToRootChildren(); if (list_children != null && list_children.size() > 0) { expanded = true; } } String parent_code = null; if (parent != null) { parent_code = parent.getCode(); } String parent_id = null; if (parent == null) { parent_id = "root"; } else { parent_id = replaceNodeID("N_" + parent.getCode()); } String code = node.getCode(); boolean isHasMoreNode = false; if (code.compareTo("...") == 0) { has_more_node_knt++; if (parent == null) { code = "root" + "_dot_" + new Integer(has_more_node_knt).toString(); } else { isHasMoreNode = true; code = parent.getCode() + "_dot_" + new Integer(has_more_node_knt).toString(); } } String node_id = replaceNodeID("N_" + code); String node_label = node.getEntityDescription(); String indentStr = indent + " "; String symbol = getNodeSymbol(node); println(out, ""); println(out, indentStr + "// " + symbol + " " + node_label + "(" + code + ")"); println(out, indentStr + "newNodeDetails = \"javascript:onClickTreeNode('" + code + "');\";"); println(out, indentStr + "newNodeData = { label:\"" + node_label + "\", id:\"" + code + "\", href:newNodeDetails };"); if (expanded) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", true);"); } else if (isHasMoreNode) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } else { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } if (expandable || isHasMoreNode) { println(out, indentStr + node_id + ".isLeaf = false;"); println(out, indentStr + node_id + ".ontology_node_child_count = 1;"); if (node.getPathToRootChildren() == null && !isHasMoreNode) println(out, indentStr + node_id + ".setDynamicLoad(loadNodeData);"); } else { println(out, indentStr + node_id + ".ontology_node_child_count = 0;"); println(out, indentStr + node_id + ".isLeaf = true;"); } if (focus_code.compareTo(code) == 0) { println(out, indentStr + node_id + ".labelStyle = \"ygtvlabel_highlight\";"); } } catch (Exception ex) { } }
private void printTreeNode(PrintWriter out, String indent, String focus_code, LexEvsTreeNode node, LexEvsTreeNode parent) { if (node == null) return; try { LexEvsTreeNode.ExpandableStatus node_status = node.getExpandableStatus(); String image = "[+]"; boolean expandable = true; if (node_status != LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { image = "."; expandable = false; } boolean expanded = false; if (node_status == LexEvsTreeNode.ExpandableStatus.IS_EXPANDABLE) { List<LexEvsTreeNode> list_children = node.getPathToRootChildren(); if (list_children != null && list_children.size() > 0) { expanded = true; } } String parent_code = null; if (parent != null) { parent_code = parent.getCode(); } String parent_id = null; if (parent == null) { parent_id = "root"; } else { parent_id = replaceNodeID("N_" + parent.getCode()); } String code = node.getCode(); boolean isHasMoreNode = false; if (code.compareTo("...") == 0) { isHasMoreNode = true; has_more_node_knt++; if (parent == null) { code = "root" + "_dot_" + new Integer(has_more_node_knt).toString(); } else { code = parent.getCode() + "_dot_" + new Integer(has_more_node_knt).toString(); } } String node_id = replaceNodeID("N_" + code); String node_label = node.getEntityDescription(); String indentStr = indent + " "; String symbol = getNodeSymbol(node); println(out, ""); println(out, indentStr + "// " + symbol + " " + node_label + "(" + code + ")"); println(out, indentStr + "newNodeDetails = \"javascript:onClickTreeNode('" + code + "');\";"); println(out, indentStr + "newNodeData = { label:\"" + node_label + "\", id:\"" + code + "\", href:newNodeDetails };"); if (expanded) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", true);"); } else if (isHasMoreNode) { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } else { println(out, indentStr + "var " + node_id + " = new YAHOO.widget.TextNode(newNodeData, " + parent_id + ", false);"); } if (expandable || isHasMoreNode) { println(out, indentStr + node_id + ".isLeaf = false;"); println(out, indentStr + node_id + ".ontology_node_child_count = 1;"); //if (node.getPathToRootChildren() == null && !isHasMoreNode) if (node.getPathToRootChildren() == null) { println(out, indentStr + node_id + ".setDynamicLoad(loadNodeData);"); } } else { println(out, indentStr + node_id + ".ontology_node_child_count = 0;"); println(out, indentStr + node_id + ".isLeaf = true;"); } if (focus_code.compareTo(code) == 0) { println(out, indentStr + node_id + ".labelStyle = \"ygtvlabel_highlight\";"); } } catch (Exception ex) { } }
diff --git a/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveyedLocaleManager.java b/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveyedLocaleManager.java index 0a164db4c..4b8c56df9 100644 --- a/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveyedLocaleManager.java +++ b/GAE/src/org/waterforpeople/mapping/portal/client/widgets/component/SurveyedLocaleManager.java @@ -1,289 +1,290 @@ package org.waterforpeople.mapping.portal.client.widgets.component; import java.util.ArrayList; import java.util.Map; import org.waterforpeople.mapping.app.gwt.client.accesspoint.AccessPointSearchCriteriaDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyedLocaleDto; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyedLocaleService; import org.waterforpeople.mapping.app.gwt.client.survey.SurveyedLocaleServiceAsync; import org.waterforpeople.mapping.app.gwt.client.util.TextConstants; import org.waterforpeople.mapping.portal.client.widgets.component.AccessPointSearchControl.Mode; import com.gallatinsystems.framework.gwt.component.DataTableBinder; import com.gallatinsystems.framework.gwt.component.DataTableHeader; import com.gallatinsystems.framework.gwt.component.DataTableListener; import com.gallatinsystems.framework.gwt.component.PaginatedDataTable; import com.gallatinsystems.framework.gwt.dto.client.ResponseDto; import com.gallatinsystems.framework.gwt.util.client.CompletionListener; import com.gallatinsystems.framework.gwt.util.client.MessageDialog; import com.gallatinsystems.user.app.gwt.client.PermissionConstants; import com.gallatinsystems.user.app.gwt.client.UserDto; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CaptionPanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.VerticalPanel; /** * UI component for searching/editing/creating SurveyedLocale objects * * @author Christopher Fagiani * */ public class SurveyedLocaleManager extends Composite implements DataTableBinder<SurveyedLocaleDto>, DataTableListener<SurveyedLocaleDto>, ClickHandler { private static TextConstants TEXT_CONSTANTS = GWT .create(TextConstants.class); private static final String DEFAULT_SORT_FIELD = "key"; private static final Integer PAGE_SIZE = 20; private static final DataTableHeader HEADERS[] = { new DataTableHeader(TEXT_CONSTANTS.id(), "key", true), new DataTableHeader(TEXT_CONSTANTS.communityCode(), "identifier", true), new DataTableHeader(TEXT_CONSTANTS.latitude(), "latitude", true), new DataTableHeader(TEXT_CONSTANTS.longitude(), "longitude", true), new DataTableHeader(TEXT_CONSTANTS.pointType(), "localeType", true), new DataTableHeader(TEXT_CONSTANTS.lastUpdated(), "lastSurveyedDate", true), new DataTableHeader(TEXT_CONSTANTS.editDelete()) }; private Panel contentPanel; private PaginatedDataTable<SurveyedLocaleDto> dataTable; private AccessPointSearchControl searchControl; private Button searchButton; private Button createButton; private DateTimeFormat dateFormat; private UserDto currentUser; private SurveyedLocaleServiceAsync surveyedLocaleService; public SurveyedLocaleManager(UserDto user) { surveyedLocaleService = GWT.create(SurveyedLocaleService.class); currentUser = user; contentPanel = new VerticalPanel(); contentPanel.add(constructSearchPanel()); dataTable = new PaginatedDataTable<SurveyedLocaleDto>( DEFAULT_SORT_FIELD, this, this, false,false); contentPanel.add(dataTable); dateFormat = DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT); initWidget(contentPanel); } /** * constructs the search control and binds the button listeners to the * search button. * * @return */ private Composite constructSearchPanel() { CaptionPanel cap = new CaptionPanel(TEXT_CONSTANTS.searchCriteria()); Panel content = new VerticalPanel(); searchControl = new AccessPointSearchControl(Mode.LOCALE); searchButton = new Button(TEXT_CONSTANTS.search()); createButton = new Button(TEXT_CONSTANTS.createNew()); Panel buttonPanel = new HorizontalPanel(); buttonPanel.add(searchButton); if(currentUser.hasPermission(PermissionConstants.EDIT_AP)){ buttonPanel.add(createButton); } content.add(searchControl); content.add(buttonPanel); cap.add(content); searchButton.addClickHandler(this); createButton.addClickHandler(this); return cap; } @Override public void onItemSelected(SurveyedLocaleDto item) { // TODO Auto-generated method stub } /** * constructs a search criteria object using values from the form * * @return */ private AccessPointSearchCriteriaDto formSearchCriteria() { AccessPointSearchCriteriaDto dto = searchControl.getSearchCriteria(); dto.setOrderBy(dataTable.getCurrentSortField()); dto.setOrderByDir(dataTable.getCurrentSortDirection()); return dto; } @Override public void requestData(String cursor, final boolean isResort) { final boolean isNew = (cursor == null); final AccessPointSearchCriteriaDto searchDto = formSearchCriteria(); AsyncCallback<ResponseDto<ArrayList<SurveyedLocaleDto>>> dataCallback = new AsyncCallback<ResponseDto<ArrayList<SurveyedLocaleDto>>>() { @Override public void onFailure(Throwable caught) { MessageDialog errDia = new MessageDialog( TEXT_CONSTANTS.error(), TEXT_CONSTANTS.errorTracePrefix() + " " + caught.getLocalizedMessage()); errDia.showCentered(); } @Override public void onSuccess( ResponseDto<ArrayList<SurveyedLocaleDto>> result) { dataTable.bindData(result.getPayload(), result.getCursorString(), isNew, isResort); if (result.getPayload() != null && result.getPayload().size() > 0) { dataTable.setVisible(true); } } }; surveyedLocaleService.listLocales(searchDto, cursor, dataCallback); } @Override public DataTableHeader[] getHeaders() { return HEADERS; } @Override public void bindRow(final Grid grid, final SurveyedLocaleDto item,final int row) { Label keyIdLabel = new Label(item.getKeyId().toString()); grid.setWidget(row, 0, keyIdLabel); if (item.getIdentifier() != null) { String communityCode = item.getIdentifier(); if (communityCode.length() > 10) communityCode = communityCode.substring(0, 10); grid.setWidget(row, 1, new Label(communityCode)); } if (item.getLatitude() != null && item.getLongitude() != null) { grid.setWidget(row, 2, new Label(item.getLatitude().toString())); grid.setWidget(row, 3, new Label(item.getLongitude().toString())); } if (item.getLocaleType() != null) { grid.setWidget(row, 4, new Label(item.getLocaleType())); } if (item.getLastSurveyedDate() != null) { grid.setWidget(row, 5, new Label(dateFormat.format(item.getLastSurveyedDate()))); } Button editLocale = new Button(TEXT_CONSTANTS.edit()); - Button deleteLocale = new Button(TEXT_CONSTANTS.delete()); + Button deleteLocale = new Button(TEXT_CONSTANTS.delete()); + deleteLocale.setTitle(row+"|"+item.getKeyId()); HorizontalPanel buttonHPanel = new HorizontalPanel(); buttonHPanel.add(editLocale); buttonHPanel.add(deleteLocale); if (!currentUser.hasPermission(PermissionConstants.EDIT_AP)) { buttonHPanel.setVisible(false); } editLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { SurveyedLocaleEditorDialog dia = new SurveyedLocaleEditorDialog(new CompletionListener() { @Override public void operationComplete(boolean wasSuccessful, Map<String, Object> payload) { if(payload != null && payload.containsKey(SurveyedLocaleEditorWidget.LOCALE_KEY)){ SurveyedLocaleDto dto = (SurveyedLocaleDto)payload.get(SurveyedLocaleEditorWidget.LOCALE_KEY); bindRow(grid,dto,row); } } },item, currentUser.hasPermission(PermissionConstants.EDIT_AP)); dia.show(); } }); deleteLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { final Button pressedButton = (Button) event.getSource(); String[] titleParts = pressedButton.getTitle().split("\\|"); final Integer row = Integer.parseInt(titleParts[0]); final Long itemId = Long.parseLong(titleParts[1]); surveyedLocaleService.deleteLocale(itemId, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert(TEXT_CONSTANTS.errorTracePrefix() + " " + caught.getLocalizedMessage()); } @Override public void onSuccess(Void result) { int rowSelected = row; dataTable.removeRow(rowSelected); Grid grid = dataTable.getGrid(); for (int i = rowSelected; i < grid .getRowCount() - 1; i++) { HorizontalPanel hPanel = (HorizontalPanel) grid .getWidget(i, 6); Button deleteButton = (Button) hPanel .getWidget(1); String[] buttonTitleParts = deleteButton .getTitle().split("\\|"); Integer newRowNum = Integer .parseInt(buttonTitleParts[0]); newRowNum = newRowNum - 1; deleteButton.setTitle(newRowNum + "|" + buttonTitleParts[1]); } Window.alert(TEXT_CONSTANTS.deleteComplete()); } }); } }); grid.setWidget(row, 6, buttonHPanel); } @Override public Integer getPageSize() { return PAGE_SIZE; } @Override public void onClick(ClickEvent event) { if (event.getSource() == searchButton) { requestData(null, false); }else if (event.getSource() == createButton){ SurveyedLocaleEditorDialog dia = new SurveyedLocaleEditorDialog(new CompletionListener() { @Override public void operationComplete(boolean wasSuccessful, Map<String, Object> payload) { if(payload != null && payload.containsKey(SurveyedLocaleEditorWidget.LOCALE_KEY)){ SurveyedLocaleDto dto = (SurveyedLocaleDto)payload.get(SurveyedLocaleEditorWidget.LOCALE_KEY); dataTable.addNewRow(dto); } } },null, currentUser.hasPermission(PermissionConstants.EDIT_AP)); dia.show(); } } }
true
true
public void bindRow(final Grid grid, final SurveyedLocaleDto item,final int row) { Label keyIdLabel = new Label(item.getKeyId().toString()); grid.setWidget(row, 0, keyIdLabel); if (item.getIdentifier() != null) { String communityCode = item.getIdentifier(); if (communityCode.length() > 10) communityCode = communityCode.substring(0, 10); grid.setWidget(row, 1, new Label(communityCode)); } if (item.getLatitude() != null && item.getLongitude() != null) { grid.setWidget(row, 2, new Label(item.getLatitude().toString())); grid.setWidget(row, 3, new Label(item.getLongitude().toString())); } if (item.getLocaleType() != null) { grid.setWidget(row, 4, new Label(item.getLocaleType())); } if (item.getLastSurveyedDate() != null) { grid.setWidget(row, 5, new Label(dateFormat.format(item.getLastSurveyedDate()))); } Button editLocale = new Button(TEXT_CONSTANTS.edit()); Button deleteLocale = new Button(TEXT_CONSTANTS.delete()); HorizontalPanel buttonHPanel = new HorizontalPanel(); buttonHPanel.add(editLocale); buttonHPanel.add(deleteLocale); if (!currentUser.hasPermission(PermissionConstants.EDIT_AP)) { buttonHPanel.setVisible(false); } editLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { SurveyedLocaleEditorDialog dia = new SurveyedLocaleEditorDialog(new CompletionListener() { @Override public void operationComplete(boolean wasSuccessful, Map<String, Object> payload) { if(payload != null && payload.containsKey(SurveyedLocaleEditorWidget.LOCALE_KEY)){ SurveyedLocaleDto dto = (SurveyedLocaleDto)payload.get(SurveyedLocaleEditorWidget.LOCALE_KEY); bindRow(grid,dto,row); } } },item, currentUser.hasPermission(PermissionConstants.EDIT_AP)); dia.show(); } }); deleteLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { final Button pressedButton = (Button) event.getSource(); String[] titleParts = pressedButton.getTitle().split("\\|"); final Integer row = Integer.parseInt(titleParts[0]); final Long itemId = Long.parseLong(titleParts[1]); surveyedLocaleService.deleteLocale(itemId, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert(TEXT_CONSTANTS.errorTracePrefix() + " " + caught.getLocalizedMessage()); } @Override public void onSuccess(Void result) { int rowSelected = row; dataTable.removeRow(rowSelected); Grid grid = dataTable.getGrid(); for (int i = rowSelected; i < grid .getRowCount() - 1; i++) { HorizontalPanel hPanel = (HorizontalPanel) grid .getWidget(i, 6); Button deleteButton = (Button) hPanel .getWidget(1); String[] buttonTitleParts = deleteButton .getTitle().split("\\|"); Integer newRowNum = Integer .parseInt(buttonTitleParts[0]); newRowNum = newRowNum - 1; deleteButton.setTitle(newRowNum + "|" + buttonTitleParts[1]); } Window.alert(TEXT_CONSTANTS.deleteComplete()); } }); } }); grid.setWidget(row, 6, buttonHPanel); }
public void bindRow(final Grid grid, final SurveyedLocaleDto item,final int row) { Label keyIdLabel = new Label(item.getKeyId().toString()); grid.setWidget(row, 0, keyIdLabel); if (item.getIdentifier() != null) { String communityCode = item.getIdentifier(); if (communityCode.length() > 10) communityCode = communityCode.substring(0, 10); grid.setWidget(row, 1, new Label(communityCode)); } if (item.getLatitude() != null && item.getLongitude() != null) { grid.setWidget(row, 2, new Label(item.getLatitude().toString())); grid.setWidget(row, 3, new Label(item.getLongitude().toString())); } if (item.getLocaleType() != null) { grid.setWidget(row, 4, new Label(item.getLocaleType())); } if (item.getLastSurveyedDate() != null) { grid.setWidget(row, 5, new Label(dateFormat.format(item.getLastSurveyedDate()))); } Button editLocale = new Button(TEXT_CONSTANTS.edit()); Button deleteLocale = new Button(TEXT_CONSTANTS.delete()); deleteLocale.setTitle(row+"|"+item.getKeyId()); HorizontalPanel buttonHPanel = new HorizontalPanel(); buttonHPanel.add(editLocale); buttonHPanel.add(deleteLocale); if (!currentUser.hasPermission(PermissionConstants.EDIT_AP)) { buttonHPanel.setVisible(false); } editLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { SurveyedLocaleEditorDialog dia = new SurveyedLocaleEditorDialog(new CompletionListener() { @Override public void operationComplete(boolean wasSuccessful, Map<String, Object> payload) { if(payload != null && payload.containsKey(SurveyedLocaleEditorWidget.LOCALE_KEY)){ SurveyedLocaleDto dto = (SurveyedLocaleDto)payload.get(SurveyedLocaleEditorWidget.LOCALE_KEY); bindRow(grid,dto,row); } } },item, currentUser.hasPermission(PermissionConstants.EDIT_AP)); dia.show(); } }); deleteLocale.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { final Button pressedButton = (Button) event.getSource(); String[] titleParts = pressedButton.getTitle().split("\\|"); final Integer row = Integer.parseInt(titleParts[0]); final Long itemId = Long.parseLong(titleParts[1]); surveyedLocaleService.deleteLocale(itemId, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert(TEXT_CONSTANTS.errorTracePrefix() + " " + caught.getLocalizedMessage()); } @Override public void onSuccess(Void result) { int rowSelected = row; dataTable.removeRow(rowSelected); Grid grid = dataTable.getGrid(); for (int i = rowSelected; i < grid .getRowCount() - 1; i++) { HorizontalPanel hPanel = (HorizontalPanel) grid .getWidget(i, 6); Button deleteButton = (Button) hPanel .getWidget(1); String[] buttonTitleParts = deleteButton .getTitle().split("\\|"); Integer newRowNum = Integer .parseInt(buttonTitleParts[0]); newRowNum = newRowNum - 1; deleteButton.setTitle(newRowNum + "|" + buttonTitleParts[1]); } Window.alert(TEXT_CONSTANTS.deleteComplete()); } }); } }); grid.setWidget(row, 6, buttonHPanel); }
diff --git a/src/edu/sc/seis/sod/tools/find_events.java b/src/edu/sc/seis/sod/tools/find_events.java index 3804c654a..16c167222 100644 --- a/src/edu/sc/seis/sod/tools/find_events.java +++ b/src/edu/sc/seis/sod/tools/find_events.java @@ -1,62 +1,62 @@ package edu.sc.seis.sod.tools; import java.text.DateFormat; import java.text.SimpleDateFormat; import com.martiansoftware.jsap.JSAPException; import edu.iris.Fissures.model.MicroSecondDate; import edu.iris.Fissures.model.TimeInterval; import edu.iris.Fissures.model.UnitImpl; import edu.sc.seis.fissuresUtil.chooser.ClockUtil; public class find_events extends CommandLineTool { public find_events(String[] args) throws JSAPException { super(args); } protected void addParams() throws JSAPException { super.addParams(); add(ServerParser.createParam("edu/iris/dmc/IRIS_EventDC", "The event server to use.")); add(BoxAreaParser.createParam("A box the events must be in. It's specified as west/east/north/south")); add(DonutParser.createParam("A donut the events must be in. It's specified as centerLat/centerLon/minRadiusDegrees/maxRadiusDegrees")); MicroSecondDate now = ClockUtil.now(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); add(TimeParser.createParam("begin", df.format(now.subtract(new TimeInterval(1, UnitImpl.DAY))), "The earliest time for an accepted event. Must be in 'YYYY-MM-DD' format.")); add(TimeParser.createParam("end", "now", "The latest time for an accepted event. Must be in 'YYYY-MM-DD' format or 'now' for the current time.")); add(RangeParser.createParam("magnitude", "0-10", "The range of acceptable magnitudes.")); add(createListOption("types", 't', "types", "The types of magnitudes to retrieve. If unspecified, all magnitude types will be retrieved")); add(RangeParser.createParam("depth", "0-10000", "The range of acceptable depths in kilometers.", 'D')); - add(OutputFormatParser.createParam("$event.getLongitude(' ##0.0000;-##0.0000') $event.getLatitude(' ##0.0000;-##0.0000') $event.getDepth('###0.##') ${event.getTime('yyyy_DDD_HH_mm_sss')}-$event.magnitudeValue$event.magnitudeType", + add(OutputFormatParser.createParam("$event.getLongitude(' ##0.0000;-##0.0000') $event.getLatitude(' ##0.0000;-##0.0000') $event.getDepth('###0.##') ${event.getTime('yyyy_DDD_HH_mm_sss')} $event.magnitudeValue$event.magnitudeType", "http://www.seis.sc.edu/sod/ingredients/event/origin/printline.html")); add(createListOption("catalogs", 'c', "catalogs", "A comma separated list of catalogs to search. If unspecified, all catalogs will be searched")); add(createListOption("seismicRegions", 's', "seismic-regions", "A comma separated list of seismic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); add(createListOption("geographicRegions", 'g', "geographic-regions", "A comma separated list of geographic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); } public static void main(String[] args) throws Exception { CommandLineTool.run(new find_events(args)); } }
true
true
protected void addParams() throws JSAPException { super.addParams(); add(ServerParser.createParam("edu/iris/dmc/IRIS_EventDC", "The event server to use.")); add(BoxAreaParser.createParam("A box the events must be in. It's specified as west/east/north/south")); add(DonutParser.createParam("A donut the events must be in. It's specified as centerLat/centerLon/minRadiusDegrees/maxRadiusDegrees")); MicroSecondDate now = ClockUtil.now(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); add(TimeParser.createParam("begin", df.format(now.subtract(new TimeInterval(1, UnitImpl.DAY))), "The earliest time for an accepted event. Must be in 'YYYY-MM-DD' format.")); add(TimeParser.createParam("end", "now", "The latest time for an accepted event. Must be in 'YYYY-MM-DD' format or 'now' for the current time.")); add(RangeParser.createParam("magnitude", "0-10", "The range of acceptable magnitudes.")); add(createListOption("types", 't', "types", "The types of magnitudes to retrieve. If unspecified, all magnitude types will be retrieved")); add(RangeParser.createParam("depth", "0-10000", "The range of acceptable depths in kilometers.", 'D')); add(OutputFormatParser.createParam("$event.getLongitude(' ##0.0000;-##0.0000') $event.getLatitude(' ##0.0000;-##0.0000') $event.getDepth('###0.##') ${event.getTime('yyyy_DDD_HH_mm_sss')}-$event.magnitudeValue$event.magnitudeType", "http://www.seis.sc.edu/sod/ingredients/event/origin/printline.html")); add(createListOption("catalogs", 'c', "catalogs", "A comma separated list of catalogs to search. If unspecified, all catalogs will be searched")); add(createListOption("seismicRegions", 's', "seismic-regions", "A comma separated list of seismic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); add(createListOption("geographicRegions", 'g', "geographic-regions", "A comma separated list of geographic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); }
protected void addParams() throws JSAPException { super.addParams(); add(ServerParser.createParam("edu/iris/dmc/IRIS_EventDC", "The event server to use.")); add(BoxAreaParser.createParam("A box the events must be in. It's specified as west/east/north/south")); add(DonutParser.createParam("A donut the events must be in. It's specified as centerLat/centerLon/minRadiusDegrees/maxRadiusDegrees")); MicroSecondDate now = ClockUtil.now(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); add(TimeParser.createParam("begin", df.format(now.subtract(new TimeInterval(1, UnitImpl.DAY))), "The earliest time for an accepted event. Must be in 'YYYY-MM-DD' format.")); add(TimeParser.createParam("end", "now", "The latest time for an accepted event. Must be in 'YYYY-MM-DD' format or 'now' for the current time.")); add(RangeParser.createParam("magnitude", "0-10", "The range of acceptable magnitudes.")); add(createListOption("types", 't', "types", "The types of magnitudes to retrieve. If unspecified, all magnitude types will be retrieved")); add(RangeParser.createParam("depth", "0-10000", "The range of acceptable depths in kilometers.", 'D')); add(OutputFormatParser.createParam("$event.getLongitude(' ##0.0000;-##0.0000') $event.getLatitude(' ##0.0000;-##0.0000') $event.getDepth('###0.##') ${event.getTime('yyyy_DDD_HH_mm_sss')} $event.magnitudeValue$event.magnitudeType", "http://www.seis.sc.edu/sod/ingredients/event/origin/printline.html")); add(createListOption("catalogs", 'c', "catalogs", "A comma separated list of catalogs to search. If unspecified, all catalogs will be searched")); add(createListOption("seismicRegions", 's', "seismic-regions", "A comma separated list of seismic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); add(createListOption("geographicRegions", 'g', "geographic-regions", "A comma separated list of geographic Flinn-Engdahl regions. An event must be in one of these regions to pass. If unspecified, all regions will be acceptable")); }
diff --git a/JavaSource/org/unitime/timetable/action/SolutionChangesAction.java b/JavaSource/org/unitime/timetable/action/SolutionChangesAction.java index 2ea0a962..04db3fd8 100644 --- a/JavaSource/org/unitime/timetable/action/SolutionChangesAction.java +++ b/JavaSource/org/unitime/timetable/action/SolutionChangesAction.java @@ -1,365 +1,368 @@ /* * UniTime 3.2 (University Timetabling Application) * Copyright (C) 2008 - 2010, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * 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.unitime.timetable.action; import java.io.File; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.unitime.commons.Debug; import org.unitime.commons.web.Web; import org.unitime.commons.web.WebTable; import org.unitime.timetable.ApplicationProperties; import org.unitime.timetable.form.SolutionChangesForm; import org.unitime.timetable.model.UserData; import org.unitime.timetable.solver.SolverProxy; import org.unitime.timetable.solver.WebSolver; import org.unitime.timetable.solver.TimetableSolver.RecordedAssignment; import org.unitime.timetable.solver.interactive.ClassAssignmentDetails; import org.unitime.timetable.solver.interactive.SuggestionsModel; import org.unitime.timetable.solver.ui.AssignmentPreferenceInfo; import org.unitime.timetable.util.Constants; import org.unitime.timetable.webutil.PdfWebTable; /** * @author Tomas Muller */ public class SolutionChangesAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SolutionChangesForm myForm = (SolutionChangesForm) form; // Check Access if (!Web.isLoggedIn( request.getSession() )) { throw new Exception ("Access Denied."); } SuggestionsModel model = (SuggestionsModel)request.getSession().getAttribute("Suggestions.model"); if (model==null) { model = new SuggestionsModel(); model.load(request.getSession()); request.getSession().setAttribute("Suggestions.model", model); } // Read operation to be performed String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op")); if ("Apply".equals(op) || "Export PDF".equals(op)) { UserData.setPropertyInt(request.getSession(),"SolutionChanges.reference",myForm.getReferenceInt()); myForm.save(model); model.save(request.getSession()); } if ("Refresh".equals(op)) { myForm.reset(mapping, request); } myForm.load(model); SolverProxy solver = WebSolver.getSolver(request.getSession()); if (solver==null) { request.setAttribute("SolutionChanges.message","No timetable is loaded. However, you can load one <a href='listSolutions.do'>here</a>."); return mapping.findForward("showSolutionChanges"); } Vector changes = null; if (myForm.getReferenceInt()==SolutionChangesForm.sReferenceBest) { if (solver.bestSolutionInfo()==null) { request.setAttribute("SolutionChanges.message","No best solution saved so far."); return mapping.findForward("showSolutionChanges"); } changes = solver.getChangesToBest(); } else if (myForm.getReferenceInt()==SolutionChangesForm.sReferenceInitial) { changes = solver.getChangesToInitial(); } else if (myForm.getReferenceInt()==SolutionChangesForm.sReferenceSelected) { String solutionIdsStr = (String)request.getSession().getAttribute("Solver.selectedSolutionId"); if (solutionIdsStr==null || solutionIdsStr.length()==0) { request.setAttribute("SolutionChanges.message","No solution selected. However, you can select one <a href='listSolutions.do'>here"); return mapping.findForward("showSolutionChanges"); } changes = new Vector(); for (StringTokenizer s=new StringTokenizer(solutionIdsStr,",");s.hasMoreTokens();) { Long solutionId = Long.valueOf(s.nextToken()); Vector ch = solver.getChangesToSolution(solutionId); if (ch!=null) changes.addAll(ch); } } String changeTable = getChangesTable(model.getSimpleMode(),model.getReversedMode(),request,"Changes",changes); if (changeTable!=null) { request.setAttribute("SolutionChanges.table",changeTable); request.setAttribute("SolutionChanges.table.colspan",new Integer(model.getSimpleMode()?5:14)); } else request.setAttribute("SolutionChanges.message","No changes."); if ("Export PDF".equals(op)) { File f = exportPdf(model.getSimpleMode(),model.getReversedMode(),request,"Changes",changes); if (f!=null) request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+f.getName()); //response.sendRedirect("temp/"+f.getName()); } return mapping.findForward("showSolutionChanges"); } public String getChangesTable(boolean simple, boolean reversed, HttpServletRequest request, String name, Vector changes) { if (changes==null || changes.isEmpty()) return null; WebTable.setOrder(request.getSession(),"solutionChanges.ord",request.getParameter("ord"),1); WebTable webTable = (simple? new WebTable( 5, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Students"}, new String[] {"left", "left", "left", "left", "right"}, null ) : new WebTable( 14, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Std","Tm","Rm","Gr","Ins","Usl","Big","Dept","Subp","Pert"}, new String[] {"left", "left", "left", "left", "right","right","right","right","right","right","right","right","right","right","right"}, null )); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Enumeration e=changes.elements();e.hasMoreElements();idx++) { RecordedAssignment assignment = (RecordedAssignment)e.nextElement(); ClassAssignmentDetails before = (assignment.getBefore()==null?null:assignment.getBefore().getDetails(request.getSession(),false)); ClassAssignmentDetails after = (assignment.getAfter()==null?null:assignment.getAfter().getDetails(request.getSession(),false)); if (reversed) { ClassAssignmentDetails x = after; after = before; before = x; } String className = (after==null?before.getClazz().toHtml(true,true):after.getClazz().toHtml(true,true)); ClassAssignmentDetails classSort = (after==null?before:after); String time = ClassAssignmentDetails.dispTime2((before==null?null:before.getTime()),(after==null?null:after.getTime())); String rooms = ""; String link = (before==null?null:"id="+before.getClazz().getClassId()+"&days="+before.getTime().getDays()+"&slot="+before.getTime().getStartSlot()+"&pattern="+before.getTime().getPatternId()); - for (int i=0;i<(before==null?(after.getRoom()==null?0:after.getRoom().length):(before.getRoom()==null?0:before.getRoom().length));i++) { + int nrRooms = Math.max(before == null || before.getRoom() == null ? 0 : before.getRoom().length, after == null || after.getRoom() == null ? 0 : after.getRoom().length); + for (int i=0;i<nrRooms;i++) { if (i>0) rooms += ", "; - rooms += (ClassAssignmentDetails.dispRoom2((before==null || before.getRoom().length<=i?null:before.getRoom()[i]),(after==null || after.getRoom().length<=i?null:after.getRoom()[i]))); - if (before!=null) + rooms += (ClassAssignmentDetails.dispRoom2( + (before==null || before.getRoom()==null || before.getRoom().length<=i ? null : before.getRoom()[i]), + (after==null || after.getRoom()==null || after.getRoom().length<=i ? null : after.getRoom()[i]))); + if (before!=null && before.getRoom()!=null && before.getRoom().length>i) link += "&room"+i+"="+before.getRoom()[i].getId(); } String dates = (before==null?after.getDaysHtml():before.getDaysHtml()); String timesSort = (before==null?after.getTimeName():before.getTimeName()); String roomsSort = (before==null?after.getRoomName():before.getRoomName()); String datesSort = (before==null?after.getDaysName():before.getDaysName()); AssignmentPreferenceInfo bInf = (before==null?null:before.getInfo()); AssignmentPreferenceInfo aInf = (after==null?null:after.getInfo()); if (aInf==null) aInf = new AssignmentPreferenceInfo(); if (bInf==null) bInf = new AssignmentPreferenceInfo(); StringBuffer sb = new StringBuffer(); if (aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("c",aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts())); } if (aInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("d",bInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts())); } if (aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("h",aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts())); } if (sb.length()>0) sb.append(")"); if (simple) webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()) }); else webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb, ClassAssignmentDetails.dispNumber(aInf.getTimePreference()-bInf.getTimePreference()), ClassAssignmentDetails.dispNumber(aInf.sumRoomPreference()-bInf.sumRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), ClassAssignmentDetails.dispNumber(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), ClassAssignmentDetails.dispNumber(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), ClassAssignmentDetails.dispNumber(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), ClassAssignmentDetails.dispNumber(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), ClassAssignmentDetails.dispNumber(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()), new Double(aInf.getTimePreference()-bInf.getTimePreference()), new Long(aInf.sumRoomPreference()-bInf.sumRoomPreference()), new Long(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), new Long(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), new Long(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), new Long(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), new Double(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), new Double(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), new Double(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable.printTable(WebTable.getOrder(request.getSession(),"solutionChanges.ord")); } public File exportPdf(boolean simple, boolean reversed, HttpServletRequest request, String name, Vector changes) { if (changes==null || changes.isEmpty()) return null; PdfWebTable webTable = (simple? new PdfWebTable( 5, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Students"}, new String[] {"left", "left", "left", "left", "right"}, null ) : new PdfWebTable( 14, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Std","Tm","Rm","Gr","Ins","Usl","Big","Dept","Subp","Pert"}, new String[] {"left", "left", "left", "left", "right","right","right","right","right","right","right","right","right","right","right"}, null )); try { int idx = 0; for (Enumeration e=changes.elements();e.hasMoreElements();idx++) { RecordedAssignment assignment = (RecordedAssignment)e.nextElement(); ClassAssignmentDetails before = (assignment.getBefore()==null?null:assignment.getBefore().getDetails(request.getSession(),false)); ClassAssignmentDetails after = (assignment.getAfter()==null?null:assignment.getAfter().getDetails(request.getSession(),false)); if (reversed) { ClassAssignmentDetails x = after; after = before; before = x; } String className = (after==null?before.getClazz().getName():after.getClazz().getName()); ClassAssignmentDetails classSort = (after==null?before:after); String time = ClassAssignmentDetails.dispTimeNoHtml((before==null?null:before.getTime()),(after==null?null:after.getTime())); String rooms = ""; for (int i=0;i<(before==null?(after.getRoom()==null?0:after.getRoom().length):(before.getRoom()==null?0:before.getRoom().length));i++) { if (i>0) rooms += ", "; rooms += (ClassAssignmentDetails.dispRoomNoHtml((before==null?null:before.getRoom()[i]),(after==null?null:after.getRoom()[i]))); } String dates = (before==null?after.getDaysName():before.getDaysName()); String timesSort = (before==null?after.getTimeName():before.getTimeName()); String roomsSort = (before==null?after.getRoomName():before.getRoomName()); String datesSort = (before==null?after.getDaysName():before.getDaysName()); AssignmentPreferenceInfo bInf = (before==null?null:before.getInfo()); AssignmentPreferenceInfo aInf = (after==null?null:after.getInfo()); if (aInf==null) aInf = new AssignmentPreferenceInfo(); if (bInf==null) bInf = new AssignmentPreferenceInfo(); StringBuffer sb = new StringBuffer(); if (aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumberNoHtml("c",aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts())); } if (aInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumberNoHtml("d",bInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts())); } if (aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumberNoHtml("h",aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts())); } if (sb.length()>0) sb.append(")"); if (simple) webTable.addLine(null, new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumberNoHtml(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()) }); else webTable.addLine(null, new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumberNoHtml(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb, ClassAssignmentDetails.dispNumberNoHtml(aInf.getTimePreference()-bInf.getTimePreference()), ClassAssignmentDetails.dispNumberNoHtml(aInf.sumRoomPreference()-bInf.sumRoomPreference()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), ClassAssignmentDetails.dispNumberNoHtml(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()), new Double(aInf.getTimePreference()-bInf.getTimePreference()), new Long(aInf.sumRoomPreference()-bInf.sumRoomPreference()), new Long(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), new Long(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), new Long(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), new Long(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), new Double(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), new Double(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), new Double(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }); } File file = ApplicationProperties.getTempFile("changes", "pdf"); webTable.exportPdf(file, WebTable.getOrder(request.getSession(),"solutionChanges.ord")); return file; } catch (Exception e) { Debug.error(e); } return null; } }
false
true
public String getChangesTable(boolean simple, boolean reversed, HttpServletRequest request, String name, Vector changes) { if (changes==null || changes.isEmpty()) return null; WebTable.setOrder(request.getSession(),"solutionChanges.ord",request.getParameter("ord"),1); WebTable webTable = (simple? new WebTable( 5, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Students"}, new String[] {"left", "left", "left", "left", "right"}, null ) : new WebTable( 14, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Std","Tm","Rm","Gr","Ins","Usl","Big","Dept","Subp","Pert"}, new String[] {"left", "left", "left", "left", "right","right","right","right","right","right","right","right","right","right","right"}, null )); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Enumeration e=changes.elements();e.hasMoreElements();idx++) { RecordedAssignment assignment = (RecordedAssignment)e.nextElement(); ClassAssignmentDetails before = (assignment.getBefore()==null?null:assignment.getBefore().getDetails(request.getSession(),false)); ClassAssignmentDetails after = (assignment.getAfter()==null?null:assignment.getAfter().getDetails(request.getSession(),false)); if (reversed) { ClassAssignmentDetails x = after; after = before; before = x; } String className = (after==null?before.getClazz().toHtml(true,true):after.getClazz().toHtml(true,true)); ClassAssignmentDetails classSort = (after==null?before:after); String time = ClassAssignmentDetails.dispTime2((before==null?null:before.getTime()),(after==null?null:after.getTime())); String rooms = ""; String link = (before==null?null:"id="+before.getClazz().getClassId()+"&days="+before.getTime().getDays()+"&slot="+before.getTime().getStartSlot()+"&pattern="+before.getTime().getPatternId()); for (int i=0;i<(before==null?(after.getRoom()==null?0:after.getRoom().length):(before.getRoom()==null?0:before.getRoom().length));i++) { if (i>0) rooms += ", "; rooms += (ClassAssignmentDetails.dispRoom2((before==null || before.getRoom().length<=i?null:before.getRoom()[i]),(after==null || after.getRoom().length<=i?null:after.getRoom()[i]))); if (before!=null) link += "&room"+i+"="+before.getRoom()[i].getId(); } String dates = (before==null?after.getDaysHtml():before.getDaysHtml()); String timesSort = (before==null?after.getTimeName():before.getTimeName()); String roomsSort = (before==null?after.getRoomName():before.getRoomName()); String datesSort = (before==null?after.getDaysName():before.getDaysName()); AssignmentPreferenceInfo bInf = (before==null?null:before.getInfo()); AssignmentPreferenceInfo aInf = (after==null?null:after.getInfo()); if (aInf==null) aInf = new AssignmentPreferenceInfo(); if (bInf==null) bInf = new AssignmentPreferenceInfo(); StringBuffer sb = new StringBuffer(); if (aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("c",aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts())); } if (aInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("d",bInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts())); } if (aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("h",aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts())); } if (sb.length()>0) sb.append(")"); if (simple) webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()) }); else webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb, ClassAssignmentDetails.dispNumber(aInf.getTimePreference()-bInf.getTimePreference()), ClassAssignmentDetails.dispNumber(aInf.sumRoomPreference()-bInf.sumRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), ClassAssignmentDetails.dispNumber(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), ClassAssignmentDetails.dispNumber(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), ClassAssignmentDetails.dispNumber(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), ClassAssignmentDetails.dispNumber(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), ClassAssignmentDetails.dispNumber(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()), new Double(aInf.getTimePreference()-bInf.getTimePreference()), new Long(aInf.sumRoomPreference()-bInf.sumRoomPreference()), new Long(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), new Long(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), new Long(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), new Long(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), new Double(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), new Double(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), new Double(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable.printTable(WebTable.getOrder(request.getSession(),"solutionChanges.ord")); }
public String getChangesTable(boolean simple, boolean reversed, HttpServletRequest request, String name, Vector changes) { if (changes==null || changes.isEmpty()) return null; WebTable.setOrder(request.getSession(),"solutionChanges.ord",request.getParameter("ord"),1); WebTable webTable = (simple? new WebTable( 5, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Students"}, new String[] {"left", "left", "left", "left", "right"}, null ) : new WebTable( 14, name, "solutionChanges.do?ord=%%", new String[] {"Class", "Date", "Time", "Room", "Std","Tm","Rm","Gr","Ins","Usl","Big","Dept","Subp","Pert"}, new String[] {"left", "left", "left", "left", "right","right","right","right","right","right","right","right","right","right","right"}, null )); webTable.setRowStyle("white-space:nowrap"); try { int idx = 0; for (Enumeration e=changes.elements();e.hasMoreElements();idx++) { RecordedAssignment assignment = (RecordedAssignment)e.nextElement(); ClassAssignmentDetails before = (assignment.getBefore()==null?null:assignment.getBefore().getDetails(request.getSession(),false)); ClassAssignmentDetails after = (assignment.getAfter()==null?null:assignment.getAfter().getDetails(request.getSession(),false)); if (reversed) { ClassAssignmentDetails x = after; after = before; before = x; } String className = (after==null?before.getClazz().toHtml(true,true):after.getClazz().toHtml(true,true)); ClassAssignmentDetails classSort = (after==null?before:after); String time = ClassAssignmentDetails.dispTime2((before==null?null:before.getTime()),(after==null?null:after.getTime())); String rooms = ""; String link = (before==null?null:"id="+before.getClazz().getClassId()+"&days="+before.getTime().getDays()+"&slot="+before.getTime().getStartSlot()+"&pattern="+before.getTime().getPatternId()); int nrRooms = Math.max(before == null || before.getRoom() == null ? 0 : before.getRoom().length, after == null || after.getRoom() == null ? 0 : after.getRoom().length); for (int i=0;i<nrRooms;i++) { if (i>0) rooms += ", "; rooms += (ClassAssignmentDetails.dispRoom2( (before==null || before.getRoom()==null || before.getRoom().length<=i ? null : before.getRoom()[i]), (after==null || after.getRoom()==null || after.getRoom().length<=i ? null : after.getRoom()[i]))); if (before!=null && before.getRoom()!=null && before.getRoom().length>i) link += "&room"+i+"="+before.getRoom()[i].getId(); } String dates = (before==null?after.getDaysHtml():before.getDaysHtml()); String timesSort = (before==null?after.getTimeName():before.getTimeName()); String roomsSort = (before==null?after.getRoomName():before.getRoomName()); String datesSort = (before==null?after.getDaysName():before.getDaysName()); AssignmentPreferenceInfo bInf = (before==null?null:before.getInfo()); AssignmentPreferenceInfo aInf = (after==null?null:after.getInfo()); if (aInf==null) aInf = new AssignmentPreferenceInfo(); if (bInf==null) bInf = new AssignmentPreferenceInfo(); StringBuffer sb = new StringBuffer(); if (aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("c",aInf.getNrCommitedStudentConflicts()-bInf.getNrCommitedStudentConflicts())); } if (aInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("d",bInf.getNrDistanceStudentConflicts()-bInf.getNrDistanceStudentConflicts())); } if (aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts()!=0) { if (sb.length()==0) sb.append(" ("); else sb.append(","); sb.append(ClassAssignmentDetails.dispNumber("h",aInf.getNrHardStudentConflicts()-bInf.getNrHardStudentConflicts())); } if (sb.length()>0) sb.append(")"); if (simple) webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()) }); else webTable.addLine((link!=null?"onClick=\"showGwtDialog('Suggestions', 'suggestions.do?"+link+"&op=Try','900','90%');\"":null), new String[] { className, dates, time, rooms, ClassAssignmentDetails.dispNumber(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts())+sb, ClassAssignmentDetails.dispNumber(aInf.getTimePreference()-bInf.getTimePreference()), ClassAssignmentDetails.dispNumber(aInf.sumRoomPreference()-bInf.sumRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), ClassAssignmentDetails.dispNumber(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), ClassAssignmentDetails.dispNumber(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), ClassAssignmentDetails.dispNumber(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), ClassAssignmentDetails.dispNumber(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), ClassAssignmentDetails.dispNumber(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), ClassAssignmentDetails.dispNumber(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }, new Comparable[] { classSort, datesSort, timesSort, roomsSort, new Long(aInf.getNrStudentConflicts()-bInf.getNrStudentConflicts()), new Double(aInf.getTimePreference()-bInf.getTimePreference()), new Long(aInf.sumRoomPreference()-bInf.sumRoomPreference()), new Long(aInf.getGroupConstraintPref()-bInf.getGroupConstraintPref()), new Long(aInf.getBtbInstructorPreference()-bInf.getBtbInstructorPreference()), new Long(aInf.getUselessHalfHours()-bInf.getUselessHalfHours()), new Long(aInf.getTooBigRoomPreference()-bInf.getTooBigRoomPreference()), new Double(aInf.getDeptBalancPenalty()-bInf.getDeptBalancPenalty()), new Double(aInf.getSpreadPenalty()-bInf.getSpreadPenalty()), new Double(aInf.getPerturbationPenalty()-bInf.getPerturbationPenalty()) }); } } catch (Exception e) { Debug.error(e); webTable.addLine(new String[] {"<font color='red'>ERROR:"+e.getMessage()+"</font>"},null); } return webTable.printTable(WebTable.getOrder(request.getSession(),"solutionChanges.ord")); }
diff --git a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java index 3035908c2..a550889b5 100644 --- a/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java +++ b/openjpa-kernel/src/main/java/org/apache/openjpa/kernel/AbstractBrokerFactory.java @@ -1,886 +1,892 @@ /* * 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.openjpa.kernel; import java.io.ObjectStreamException; import java.security.AccessController; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.apache.commons.collections.set.MapBackedSet; import org.apache.commons.lang.StringUtils; import org.apache.openjpa.kernel.AuditManager; import org.apache.openjpa.audit.Auditor; import org.apache.openjpa.conf.BrokerValue; import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.conf.OpenJPAConfigurationImpl; import org.apache.openjpa.conf.OpenJPAVersion; import org.apache.openjpa.datacache.DataCacheStoreManager; import org.apache.openjpa.ee.ManagedRuntime; import org.apache.openjpa.enhance.ManagedClassSubclasser; import org.apache.openjpa.enhance.PCRegistry; import org.apache.openjpa.enhance.PersistenceCapable; import org.apache.openjpa.event.BrokerFactoryEvent; import org.apache.openjpa.event.RemoteCommitEventManager; import org.apache.openjpa.instrumentation.InstrumentationManager; import org.apache.openjpa.lib.conf.Configuration; import org.apache.openjpa.lib.conf.Configurations; import org.apache.openjpa.lib.instrumentation.InstrumentationLevel; import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.lib.util.J2DoPrivHelper; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.Options; import org.apache.openjpa.lib.util.concurrent.ConcurrentReferenceHashSet; import org.apache.openjpa.meta.MetaDataModes; import org.apache.openjpa.meta.MetaDataRepository; import org.apache.openjpa.util.GeneralException; import org.apache.openjpa.util.InvalidStateException; import org.apache.openjpa.util.OpenJPAException; import org.apache.openjpa.util.UserException; /** * Abstract implementation of the {@link BrokerFactory} * that must be subclassed for a specific runtime. * * @author Abe White */ @SuppressWarnings("serial") public abstract class AbstractBrokerFactory implements BrokerFactory { private static final Localizer _loc = Localizer.forPackage(AbstractBrokerFactory.class); // static mapping of configurations to pooled broker factories private static final Map<Object,AbstractBrokerFactory> _pool = Collections.synchronizedMap(new HashMap<Object,AbstractBrokerFactory>()); // configuration private final OpenJPAConfiguration _conf; private transient boolean _readOnly = false; private transient boolean _closed = false; private transient RuntimeException _closedException = null; private Map<Object,Object> _userObjects = null; // internal lock: spec forbids synchronization on this object private final ReentrantLock _lock = new ReentrantLock(); // maps global transactions to associated brokers private transient ConcurrentHashMap<Object,Collection<Broker>> _transactional = new ConcurrentHashMap<Object,Collection<Broker>>(); // weak-ref tracking of open brokers private transient Set<Broker> _brokers; // cache the class names loaded from the persistent classes property so // that we can re-load them for each new broker private transient Collection<String> _pcClassNames = null; private transient Collection<ClassLoader> _pcClassLoaders = null; private transient boolean _persistentTypesLoaded = false; // lifecycle listeners to pass to each broker private transient Map<Object, Class<?>[]> _lifecycleListeners = null; // transaction listeners to pass to each broker private transient List<Object> _transactionListeners = null; // key under which this instance can be stored in the broker pool // and later identified private Object _poolKey; /** * Return an internal factory pool key for the given configuration. * * @since 1.1.0 */ protected static Object toPoolKey(Map<String,Object> map) { Object key = Configurations.getProperty("Id", map); return ( key != null) ? key : map; } /** * Register <code>factory</code> in the pool under <code>key</code>. * * @since 1.1.0 */ protected static void pool(Object key, AbstractBrokerFactory factory) { synchronized(_pool) { _pool.put(key, factory); factory.setPoolKey(key); factory.makeReadOnly(); } } /** * Return the pooled factory matching the given key, or null * if none. The key must be of the form created by {@link #getPoolKey}. */ public static AbstractBrokerFactory getPooledFactoryForKey(Object key) { return (AbstractBrokerFactory) _pool.get(key); } /** * Constructor. Configuration must be provided on construction. */ protected AbstractBrokerFactory(OpenJPAConfiguration config) { _conf = config; _brokers = newBrokerSet(); getPcClassLoaders(); } /** * Return the configuration for this factory. */ public OpenJPAConfiguration getConfiguration() { return _conf; } public Broker newBroker() { return newBroker(_conf.getConnectionUserName(), _conf.getConnectionPassword()); } public Broker newBroker(String user, String pass) { return newBroker(user, pass, _conf.isTransactionModeManaged(), _conf.getConnectionRetainModeConstant()); } public Broker newBroker(boolean managed, int connRetainMode) { return newBroker(_conf.getConnectionUserName(), _conf.getConnectionPassword(), managed, connRetainMode); } public Broker newBroker(String user, String pass, boolean managed, int connRetainMode) { return newBroker(user, pass, managed, connRetainMode, true); } public Broker newBroker(String user, String pass, boolean managed, int connRetainMode, boolean findExisting) { return newBroker(user, pass, managed, connRetainMode, findExisting, "", ""); } public Broker newBroker(String user, String pass, boolean managed, int connRetainMode, boolean findExisting, String cf1Name, String cf2Name) { try { assertOpen(); if(StringUtils.isNotEmpty(cf1Name)) { // If the cfName has been set on the broker try looking up now. try { _conf.getConnectionFactory(); } catch(UserException ue) { // try setting the broker's CF into the configuration. _conf.setConnectionFactoryName(cf1Name); } } makeReadOnly(); Broker broker = null; if (findExisting) broker = findBroker(user, pass, managed); if (broker == null) { broker = newBrokerImpl(user, pass); broker.setConnectionFactoryName(cf1Name); broker.setConnectionFactory2Name(cf2Name); initializeBroker(managed, connRetainMode, broker, false); } return broker; } catch (OpenJPAException ke) { throw ke; } catch (RuntimeException re) { throw new GeneralException(re); } } void initializeBroker(boolean managed, int connRetainMode, Broker broker, boolean fromDeserialization) { assertOpen(); makeReadOnly(); DelegatingStoreManager dsm = createDelegatingStoreManager(); ((BrokerImpl) broker).initialize(this, dsm, managed, connRetainMode, fromDeserialization); if (!fromDeserialization) addListeners(broker); // if we're using remote events, register the event manager so // that it can broadcast commit notifications from the broker RemoteCommitEventManager remote = _conf.getRemoteCommitEventManager(); if (remote.areRemoteEventsEnabled()) broker.addTransactionListener(remote); loadPersistentTypes(broker.getClassLoader()); _brokers.add(broker); _conf.setReadOnly(Configuration.INIT_STATE_FROZEN); } /** * Add factory-registered lifecycle listeners to the broker. */ protected void addListeners(Broker broker) { if (_lifecycleListeners != null && !_lifecycleListeners.isEmpty()) { for (Map.Entry<Object,Class<?>[]> entry : _lifecycleListeners.entrySet()) { broker.addLifecycleListener(entry.getKey(), entry.getValue()); } } if (_transactionListeners != null && !_transactionListeners.isEmpty()) { for (Iterator<Object> itr = _transactionListeners.iterator(); itr.hasNext(); ) { broker.addTransactionListener(itr.next()); } } } /** * Load the configured persistent classes list. Performed automatically * whenever a broker is created. */ public void loadPersistentTypes(ClassLoader envLoader) { // if we've loaded the persistent types and the class name list // is empty, then we can simply return. Note that there is a // potential threading scenario in which _persistentTypesLoaded is // false when read, but the work to populate _pcClassNames has // already been done. This is ok; _pcClassNames can tolerate // concurrent access, so the worst case is that the list is // persistent type data is processed multiple times, which this // algorithm takes into account. if (_persistentTypesLoaded && _pcClassNames.isEmpty()) return; // cache persistent type names if not already ClassLoader loader = _conf.getClassResolverInstance(). getClassLoader(getClass(), envLoader); Collection<Class<?>> toRedefine = new ArrayList<Class<?>>(); if (!_persistentTypesLoaded) { Collection<Class<?>> clss = _conf.getMetaDataRepositoryInstance(). loadPersistentTypes(false, loader, _conf.isInitializeEagerly()); if (clss.isEmpty()) _pcClassNames = Collections.emptyList(); else { Collection<String> c = new ArrayList<String>(clss.size()); for (Iterator<Class<?>> itr = clss.iterator(); itr.hasNext();) { Class<?> cls = itr.next(); c.add(cls.getName()); if (needsSub(cls)) toRedefine.add(cls); } getPcClassLoaders().add(loader); _pcClassNames = c; } _persistentTypesLoaded = true; } else { // reload with this loader if (getPcClassLoaders().add(loader)) { for (String clsName : _pcClassNames) { try { Class<?> cls = Class.forName(clsName, true, loader); if (needsSub(cls)) toRedefine.add(cls); } catch (Throwable t) { _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME).warn(null, t); } } } } // get the ManagedClassSubclasser into the loop ManagedClassSubclasser.prepareUnenhancedClasses(_conf, toRedefine, envLoader); } private boolean needsSub(Class<?> cls) { return !cls.isInterface() && !PersistenceCapable.class.isAssignableFrom(cls); } public void addLifecycleListener(Object listener, Class<?>[] classes) { lock(); try { assertOpen(); if (_lifecycleListeners == null) _lifecycleListeners = new HashMap<Object, Class<?>[]>(7); _lifecycleListeners.put(listener, classes); } finally { unlock(); } } public void removeLifecycleListener(Object listener) { lock(); try { assertOpen(); if (_lifecycleListeners != null) _lifecycleListeners.remove(listener); } finally { unlock(); } } public void addTransactionListener(Object listener) { lock(); try { assertOpen(); if (_transactionListeners == null) _transactionListeners = new LinkedList<Object>(); _transactionListeners.add(listener); } finally { unlock(); } } public void removeTransactionListener(Object listener) { lock(); try { assertOpen(); if (_transactionListeners != null) _transactionListeners.remove(listener); } finally { unlock(); } } /** * Returns true if this broker factory is closed. */ public boolean isClosed() { return _closed; } public void close() { lock(); try { assertOpen(); assertNoActiveTransaction(); // remove from factory pool synchronized (_pool) { if (_pool.get(_poolKey) == this) _pool.remove(_poolKey); } // close all brokers for (Broker broker : _brokers) { // Check for null because _brokers may contain weak references if ((broker != null) && (!broker.isClosed())) broker.close(); } if(_conf.metaDataRepositoryAvailable()) { // remove metadata repository from listener list PCRegistry.removeRegisterClassListener (_conf.getMetaDataRepositoryInstance()); } _conf.close(); _closed = true; Log log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isTraceEnabled()) _closedException = new IllegalStateException(); } finally { unlock(); } } /** * Subclasses should override this method to add a <code>Platform</code> * property listing the runtime platform, such as: * <code>OpenJPA JDBC Edition: Oracle Database</code> */ public Map<String,Object> getProperties() { // required props are VendorName and VersionNumber Map<String,Object> props = _conf.toProperties(true); props.put("VendorName", OpenJPAVersion.VENDOR_NAME); props.put("VersionNumber", OpenJPAVersion.VERSION_NUMBER); props.put("VersionId", OpenJPAVersion.VERSION_ID); return props; } public Set<String> getSupportedProperties() { return _conf.getPropertyKeys(); } public Object getUserObject(Object key) { lock(); try { assertOpen(); return (_userObjects == null) ? null : _userObjects.get(key); } finally { unlock(); } } public Object putUserObject(Object key, Object val) { lock(); try { assertOpen(); if (val == null) return (_userObjects == null) ? null : _userObjects.remove(key); if (_userObjects == null) _userObjects = new HashMap<Object,Object>(); return _userObjects.put(key, val); } finally { unlock(); } } public void lock() { _lock.lock(); } public void unlock() { _lock.unlock(); } /** * Replaces the factory with this JVMs pooled version if it exists. Also * freezes the factory. */ protected Object readResolve() throws ObjectStreamException { AbstractBrokerFactory factory = getPooledFactoryForKey(_poolKey); if (factory != null) return factory; // reset these transient fields to empty values _transactional = new ConcurrentHashMap<Object,Collection<Broker>>(); _brokers = newBrokerSet(); makeReadOnly(); return this; } private Set<Broker> newBrokerSet() { BrokerValue bv; if (_conf instanceof OpenJPAConfigurationImpl) bv = ((OpenJPAConfigurationImpl) _conf).brokerPlugin; else bv = (BrokerValue) _conf.getValue(BrokerValue.KEY); if (FinalizingBrokerImpl.class.isAssignableFrom(bv.getTemplateBrokerType(_conf))) { return MapBackedSet.decorate(new ConcurrentHashMap(), new Object() { }); } else { return new ConcurrentReferenceHashSet<Broker>(ConcurrentReferenceHashSet.WEAK); } } //////////////////////// // Methods for Override //////////////////////// /** * Return a new StoreManager for this runtime. Note that the instance * returned here may be wrapped before being passed to the * {@link #newBroker} method. */ protected abstract StoreManager newStoreManager(); /** * Find a pooled broker, or return null if none. If using * managed transactions, looks for a transactional broker; * otherwise returns null by default. This method will be called before * {@link #newStoreManager} so that factory subclasses implementing * pooling can return a matching manager before a new {@link StoreManager} * is created. */ protected Broker findBroker(String user, String pass, boolean managed) { if (managed) return findTransactionalBroker(user, pass); return null; } /** * Return a broker configured with the proper settings. * By default, this method constructs a new * BrokerImpl of the class set for this factory. */ protected BrokerImpl newBrokerImpl(String user, String pass) { BrokerImpl broker = _conf.newBrokerInstance(user, pass); if (broker == null) throw new UserException(_loc.get("no-broker-class", _conf.getBrokerImpl())); return broker; } /** * Setup transient state used by this factory based on the * current configuration, which will subsequently be locked down. This * method will be called before the first broker is requested, * and will be re-called each time the factory is deserialized into a JVM * that has no configuration for this data store. */ protected void setup() { } ///////////// // Utilities ///////////// /** * Find a managed runtime broker associated with the * current transaction, or returns null if none. */ protected Broker findTransactionalBroker(String user, String pass) { Transaction trans; ManagedRuntime mr = _conf.getManagedRuntimeInstance(); Object txKey; try { trans = mr.getTransactionManager(). getTransaction(); txKey = mr.getTransactionKey(); if (trans == null || trans.getStatus() == Status.STATUS_NO_TRANSACTION || trans.getStatus() == Status.STATUS_UNKNOWN) return null; } catch (OpenJPAException ke) { throw ke; } catch (Exception e) { throw new GeneralException(e); } Collection<Broker> brokers = _transactional.get(txKey); if (brokers != null) { // we don't need to synchronize on brokers since one JTA transaction // can never be active on multiple concurrent threads. for (Broker broker : brokers) { if (StringUtils.equals(broker.getConnectionUserName(), user) && StringUtils.equals(broker.getConnectionPassword(), pass)) return broker; } } return null; } /** * Configures the given broker with the current factory option settings. */ protected void configureBroker(BrokerImpl broker) { broker.setOptimistic(_conf.getOptimistic()); broker.setNontransactionalRead(_conf.getNontransactionalRead()); broker.setNontransactionalWrite(_conf.getNontransactionalWrite()); broker.setRetainState(_conf.getRetainState()); broker.setRestoreState(_conf.getRestoreStateConstant()); broker.setAutoClear(_conf.getAutoClearConstant()); broker.setIgnoreChanges(_conf.getIgnoreChanges()); broker.setMultithreaded(_conf.getMultithreaded()); broker.setAutoDetach(_conf.getAutoDetachConstant()); broker.setDetachState(_conf.getDetachStateInstance().getDetachState()); broker.setPostLoadOnMerge(_conf.getPostLoadOnMerge()); } /** * Freezes the configuration of this factory. */ public void makeReadOnly() { if (_readOnly) return; lock(); try { // check again if (_readOnly) return; _readOnly = true; Log log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); - if (log.isInfoEnabled()) + if (log.isInfoEnabled()) { log.info(getFactoryInitializationBanner()); + } if (log.isTraceEnabled()) { Map<String,Object> props = _conf.toProperties(true); String lineSep = J2DoPrivHelper.getLineSeparator(); StringBuilder buf = new StringBuilder(); Map.Entry<?,?> entry; for (Iterator<Map.Entry<String,Object>> itr = props.entrySet().iterator(); itr.hasNext();) { entry = itr.next(); Object value = entry.getValue(); buf.append(entry.getKey()).append(": ") .append(value != null && value.getClass().isArray() ? Arrays.toString((Object[])value) : value); if (itr.hasNext()) buf.append(lineSep); } log.trace(_loc.get("factory-properties", buf.toString())); } // setup transient state setup(); // register the metdata repository to auto-load persistent types // and make sure types are enhanced MetaDataRepository repos = _conf.getMetaDataRepositoryInstance(); repos.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true); repos.setResolve(MetaDataModes.MODE_MAPPING_INIT, true); PCRegistry.addRegisterClassListener(repos); // freeze underlying configuration and eagerly initialize to // avoid synchronization _conf.setReadOnly(Configuration.INIT_STATE_FREEZING); _conf.instantiateAll(); - if (_conf.isInitializeEagerly()) - _conf.setReadOnly(Configuration.INIT_STATE_FROZEN); + if (_conf.isInitializeEagerly()) { + _conf.setReadOnly(Configuration.INIT_STATE_FROZEN); + } // fire an event for all the broker factory listeners // registered on the configuration. _conf.getBrokerFactoryEventManager().fireEvent( new BrokerFactoryEvent(this, BrokerFactoryEvent.BROKER_FACTORY_CREATED)); + } catch (RuntimeException e) { + // if the db connection is not available we need to reset the state + _readOnly = false; + throw e; } finally { unlock(); } } /** * Return an object to be written to the log when this broker factory * initializes. This happens after the configuration is fully loaded. */ protected Object getFactoryInitializationBanner() { return _loc.get("factory-init", OpenJPAVersion.VERSION_NUMBER); } /** * Throw an exception if the factory is closed. The exact message and * content of the exception varies whether TRACE is enabled or not. */ public void assertOpen() { if (_closed) { if (_closedException == null) // TRACE not enabled throw new InvalidStateException(_loc .get("closed-factory-notrace")); else throw new InvalidStateException(_loc.get("closed-factory")) .setCause(_closedException); } } //////////////////// // Broker utilities //////////////////// /** * Throws a {@link UserException} if a transaction is active. The thrown * exception will contain all the Brokers with active transactions as * failed objects in the nested exceptions. */ private void assertNoActiveTransaction() { Collection<Throwable> excs; if (_transactional.isEmpty()) return; excs = new ArrayList<Throwable>(_transactional.size()); for (Collection<Broker> brokers : _transactional.values()) { for (Broker broker : brokers) { excs.add(new InvalidStateException(_loc.get("active")).setFailedObject(broker)); } } if (!excs.isEmpty()) throw new InvalidStateException(_loc.get("nested-exceps")). setNestedThrowables((Throwable[]) excs.toArray(new Throwable[excs.size()])); } /** * Synchronize the given broker with a managed transaction, * optionally starting one if none is in progress. * * @return true if synched with transaction, false otherwise */ boolean syncWithManagedTransaction(BrokerImpl broker, boolean begin) { Transaction trans; try { ManagedRuntime mr = broker.getManagedRuntime(); TransactionManager tm = mr.getTransactionManager(); trans = tm.getTransaction(); if (trans != null && (trans.getStatus() == Status.STATUS_NO_TRANSACTION || trans.getStatus() == Status.STATUS_UNKNOWN)) trans = null; if (trans == null && begin) { tm.begin(); trans = tm.getTransaction(); } else if (trans == null) return false; // synch broker and trans trans.registerSynchronization(broker); // we don't need to synchronize on brokers or guard against multiple // threads using the same trans since one JTA transaction can never // be active on multiple concurrent threads. Object txKey = mr.getTransactionKey(); Collection<Broker> brokers = _transactional.get(txKey); if (brokers == null) { brokers = new ArrayList<Broker>(2); _transactional.put(txKey, brokers); trans.registerSynchronization(new RemoveTransactionSync(txKey)); } brokers.add(broker); return true; } catch (OpenJPAException ke) { throw ke; } catch (Exception e) { throw new GeneralException(e); } } /** * Returns a set of all the open brokers associated with this factory. The * returned set is unmodifiable, and may contain null references. */ public Collection<Broker> getOpenBrokers() { return Collections.unmodifiableCollection(_brokers); } /** * Release <code>broker</code> from any internal data structures. This * is invoked by <code>broker</code> after the broker is fully closed. * * @since 1.1.0 */ protected void releaseBroker(BrokerImpl broker) { _brokers.remove(broker); } /** * @return a key that can be used to obtain this broker factory from the * pool at a later time. * * @since 1.1.0 */ public Object getPoolKey() { return _poolKey; } /** * Set a key that can be used to obtain this broker factory from the * pool at a later time. * * @since 1.1.0 */ void setPoolKey(Object key) { _poolKey = key; } /** * Simple synchronization listener to remove completed transactions * from our cache. */ private class RemoveTransactionSync implements Synchronization { private final Object _trans; public RemoveTransactionSync(Object trans) { _trans = trans; } public void beforeCompletion() { } public void afterCompletion(int status) { _transactional.remove (_trans); } } /** * Method insures that deserialized EMF has this reference re-instantiated */ private Collection<ClassLoader> getPcClassLoaders() { if (_pcClassLoaders == null) _pcClassLoaders = new ConcurrentReferenceHashSet<ClassLoader>(ConcurrentReferenceHashSet.WEAK); return _pcClassLoaders; } /** * <P> * Create a DelegatingStoreManager for use with a Broker created by this factory. * If a DataCache has been enabled a DataCacheStoreManager will be returned. * </P> * <P> * If no DataCache is in use an ROPStoreManager will be returned. * </P> * * @return A delegating store manager suitable for the current * configuration. */ protected DelegatingStoreManager createDelegatingStoreManager() { // decorate the store manager for data caching and custom // result object providers; always make sure it's a delegating // store manager, because it's easier for users to deal with // that way StoreManager sm = newStoreManager(); DelegatingStoreManager dsm = null; if (_conf.getDataCacheManagerInstance().getSystemDataCache() != null) { dsm = new DataCacheStoreManager(sm); } dsm = new ROPStoreManager((dsm == null) ? sm : dsm); return dsm; } /** * This method is invoked AFTER a BrokerFactory has been instantiated. */ public void postCreationCallback() { Auditor auditor = _conf.getAuditorInstance(); if (auditor != null) { addTransactionListener(new AuditManager(auditor)); } if (_conf.isInitializeEagerly()) { newBroker(_conf.getConnectionUserName(), _conf.getConnectionPassword(), _conf.isConnectionFactoryModeManaged(), _conf.getConnectionRetainModeConstant(), false).close(); } // Don't catch any exceptions here because we want to fail-fast if something bad happens when we're preloading. Options o = Configurations.parseProperties(Configurations.getProperties(_conf.getMetaDataRepository())); if (MetaDataRepository.needsPreload(o) == true) { MetaDataRepository mdr = _conf.getMetaDataRepositoryInstance(); mdr.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true); mdr.setResolve(MetaDataRepository.MODE_MAPPING_INIT, true); // Load persistent classes and hook in subclasser loadPersistentTypes((ClassLoader) AccessController.doPrivileged(J2DoPrivHelper .getContextClassLoaderAction())); mdr.preload(); } // Get a DataCacheManager instance up front to avoid threading concerns on first call. // _conf.getDataCacheManagerInstance(); InstrumentationManager imgr = _conf.getInstrumentationManagerInstance(); if (imgr != null) { // Start all factory level instrumentation imgr.start(InstrumentationLevel.FACTORY, this); } } }
false
true
public void makeReadOnly() { if (_readOnly) return; lock(); try { // check again if (_readOnly) return; _readOnly = true; Log log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isInfoEnabled()) log.info(getFactoryInitializationBanner()); if (log.isTraceEnabled()) { Map<String,Object> props = _conf.toProperties(true); String lineSep = J2DoPrivHelper.getLineSeparator(); StringBuilder buf = new StringBuilder(); Map.Entry<?,?> entry; for (Iterator<Map.Entry<String,Object>> itr = props.entrySet().iterator(); itr.hasNext();) { entry = itr.next(); Object value = entry.getValue(); buf.append(entry.getKey()).append(": ") .append(value != null && value.getClass().isArray() ? Arrays.toString((Object[])value) : value); if (itr.hasNext()) buf.append(lineSep); } log.trace(_loc.get("factory-properties", buf.toString())); } // setup transient state setup(); // register the metdata repository to auto-load persistent types // and make sure types are enhanced MetaDataRepository repos = _conf.getMetaDataRepositoryInstance(); repos.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true); repos.setResolve(MetaDataModes.MODE_MAPPING_INIT, true); PCRegistry.addRegisterClassListener(repos); // freeze underlying configuration and eagerly initialize to // avoid synchronization _conf.setReadOnly(Configuration.INIT_STATE_FREEZING); _conf.instantiateAll(); if (_conf.isInitializeEagerly()) _conf.setReadOnly(Configuration.INIT_STATE_FROZEN); // fire an event for all the broker factory listeners // registered on the configuration. _conf.getBrokerFactoryEventManager().fireEvent( new BrokerFactoryEvent(this, BrokerFactoryEvent.BROKER_FACTORY_CREATED)); } finally { unlock(); } }
public void makeReadOnly() { if (_readOnly) return; lock(); try { // check again if (_readOnly) return; _readOnly = true; Log log = _conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isInfoEnabled()) { log.info(getFactoryInitializationBanner()); } if (log.isTraceEnabled()) { Map<String,Object> props = _conf.toProperties(true); String lineSep = J2DoPrivHelper.getLineSeparator(); StringBuilder buf = new StringBuilder(); Map.Entry<?,?> entry; for (Iterator<Map.Entry<String,Object>> itr = props.entrySet().iterator(); itr.hasNext();) { entry = itr.next(); Object value = entry.getValue(); buf.append(entry.getKey()).append(": ") .append(value != null && value.getClass().isArray() ? Arrays.toString((Object[])value) : value); if (itr.hasNext()) buf.append(lineSep); } log.trace(_loc.get("factory-properties", buf.toString())); } // setup transient state setup(); // register the metdata repository to auto-load persistent types // and make sure types are enhanced MetaDataRepository repos = _conf.getMetaDataRepositoryInstance(); repos.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true); repos.setResolve(MetaDataModes.MODE_MAPPING_INIT, true); PCRegistry.addRegisterClassListener(repos); // freeze underlying configuration and eagerly initialize to // avoid synchronization _conf.setReadOnly(Configuration.INIT_STATE_FREEZING); _conf.instantiateAll(); if (_conf.isInitializeEagerly()) { _conf.setReadOnly(Configuration.INIT_STATE_FROZEN); } // fire an event for all the broker factory listeners // registered on the configuration. _conf.getBrokerFactoryEventManager().fireEvent( new BrokerFactoryEvent(this, BrokerFactoryEvent.BROKER_FACTORY_CREATED)); } catch (RuntimeException e) { // if the db connection is not available we need to reset the state _readOnly = false; throw e; } finally { unlock(); } }
diff --git a/Project3/src/Parser.java b/Project3/src/Parser.java index 0bbf25b..0589673 100644 --- a/Project3/src/Parser.java +++ b/Project3/src/Parser.java @@ -1,291 +1,291 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class Parser { /** * list of all publications by title */ private HashMap<String, Publication> publications; /** * list of what publications which authors published */ private HashMap<String, Author> authors; /** * location of file to parse */ private String file_loc; /** * default constructor * * @param file_loc location of file to parse * @throws IOException */ public Parser(String file_loc) throws IOException { publications= new HashMap<String, Publication>(); authors = new HashMap<String, Author>(); if(isValidSearchName(file_loc)) setFileLoc(file_loc); parsePublications(); } /** * decides whether or not the entered search name is valid * * @param file_loc location of file to parse * @return true if valid, false if not */ public boolean isValidSearchName(String file_loc) { //ensure an program argument exists if(file_loc.length() > 0) return true; else { return false; } } /** * parses input file * * @return true on success, false on error * @throws IOException */ public boolean parsePublications() throws IOException { if(isValidSearchName(getFileLoc())) { FileReader DBReader = new FileReader(getFileLoc()); BufferedReader DBReaderBuffered = new BufferedReader(DBReader); String next_line=""; int partNum = 1; String type = ""; ArrayList<String> authors = new ArrayList<String>(); String titlePaper = ""; String titleSerial = ""; String pageStart = "0"; String pageEnd = "0"; String Month = ""; String year =""; String volume = ""; String issue = ""; String link = ""; while(DBReaderBuffered.ready()) { next_line=DBReaderBuffered.readLine(); if(next_line != null && next_line.length() > 0) { //TODO use modulus instead of partNum if(partNum == 1) { type = next_line; } if(partNum == 2) { authors = parseAuthorList(next_line); for(String author : authors) { if(this.authors.get(author) == null) { this.authors.put(author, new Author(author)); } } } if(partNum == 3) { titlePaper = next_line; } if(partNum == 4) { titleSerial = next_line; } if(partNum == 5) { if(type.toLowerCase().equals("conference paper")) { pageStart = next_line.split("\\-")[0]; if(next_line.contains("-")) { pageEnd = next_line.split("\\-")[1]; } } else if(type.toLowerCase().equals("journal article")) { volume = next_line.split("\\(")[0]; if(next_line.contains("(")) { issue = next_line.split("\\(")[1].split("\\)")[0]; } if(next_line.contains(":")) { pageStart = next_line.split("\\:")[1].split("\\-")[0]; } if(next_line.contains(":") && next_line.contains("-")) { pageEnd = next_line.split("\\:")[1].split("\\-")[1]; } } } if(partNum == 6) { if(next_line.contains(" ") == true) { Month = next_line.split("\\ ")[0]; year = next_line.split("\\ ")[1]; } - else if(next_line.length() >= 6 && Publication.isNumeric(next_line.substring(next_line.length()-2))) + else if(next_line.length() >= 5 && Publication.isNumeric(next_line.substring(next_line.length()-2))) { - Month = next_line.substring(0, next_line.length()-6); + Month = next_line.substring(0, next_line.length()-5); year = next_line.substring(next_line.length()-5, next_line.length()-1); } else Month = next_line; } if(partNum == 7) { partNum=0; if(!isType(next_line)) { link = next_line; } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); } partNum++; } } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); DBReaderBuffered.close(); parseAuthors(); return true; } return false; } /** * parses publications to assign the papers to the author that wrote them */ public void parseAuthors() { //Iterator from http://stackoverflow.com/questions/1066589/java-iterate-through-hashmap for(Publication pub : publications.values()) { for(String author : pub.getAuthors()) { if(this.authors.get(author) != null) { if(this.authors.get(author).getPublishedPapers().contains(pub.getTitlePaper()) == false) { this.authors.get(author).addPublishedPaper(pub); } } } } } /** * checks if the inputed String is the type of a paper * @param in String to check * @return true is yes, false if no */ public boolean isType(String in) { return in.toLowerCase().equals("conference paper") || in.toLowerCase().equals("journal article"); } /** * parses the authors line into an ArrayList * @param authorsStr line with all authors * @return ArrayList of authors */ public ArrayList<String> parseAuthorList(String authorsStr) throws ArrayIndexOutOfBoundsException { String[] parts = authorsStr.split("\\; "); ArrayList<String> out = new ArrayList<String>(); for(String author : parts) { if(author != null) { if(author.contains(",") == true) { out.add(author.split("\\, ")[1] + " " + author.split("\\, ")[0]); } else if(author != null) { out.add(author); } } } return out; } public String getFileLoc() { if(isValidSearchName(file_loc)) { return file_loc; } return "Invalid File Location"; } public boolean setFileLoc(String file_loc) { if(isValidSearchName(file_loc)) { this.file_loc = file_loc; return true; } return false; } public HashMap<String, Publication> getPublications() { return publications; } public void setPublications(HashMap<String, Publication> publications) { this.publications = publications; } public HashMap<String, Author> getAuthors() { return this.authors; } public void setAuthors(HashMap<String, Author> authors) { this.authors = authors; } }
false
true
public boolean parsePublications() throws IOException { if(isValidSearchName(getFileLoc())) { FileReader DBReader = new FileReader(getFileLoc()); BufferedReader DBReaderBuffered = new BufferedReader(DBReader); String next_line=""; int partNum = 1; String type = ""; ArrayList<String> authors = new ArrayList<String>(); String titlePaper = ""; String titleSerial = ""; String pageStart = "0"; String pageEnd = "0"; String Month = ""; String year =""; String volume = ""; String issue = ""; String link = ""; while(DBReaderBuffered.ready()) { next_line=DBReaderBuffered.readLine(); if(next_line != null && next_line.length() > 0) { //TODO use modulus instead of partNum if(partNum == 1) { type = next_line; } if(partNum == 2) { authors = parseAuthorList(next_line); for(String author : authors) { if(this.authors.get(author) == null) { this.authors.put(author, new Author(author)); } } } if(partNum == 3) { titlePaper = next_line; } if(partNum == 4) { titleSerial = next_line; } if(partNum == 5) { if(type.toLowerCase().equals("conference paper")) { pageStart = next_line.split("\\-")[0]; if(next_line.contains("-")) { pageEnd = next_line.split("\\-")[1]; } } else if(type.toLowerCase().equals("journal article")) { volume = next_line.split("\\(")[0]; if(next_line.contains("(")) { issue = next_line.split("\\(")[1].split("\\)")[0]; } if(next_line.contains(":")) { pageStart = next_line.split("\\:")[1].split("\\-")[0]; } if(next_line.contains(":") && next_line.contains("-")) { pageEnd = next_line.split("\\:")[1].split("\\-")[1]; } } } if(partNum == 6) { if(next_line.contains(" ") == true) { Month = next_line.split("\\ ")[0]; year = next_line.split("\\ ")[1]; } else if(next_line.length() >= 6 && Publication.isNumeric(next_line.substring(next_line.length()-2))) { Month = next_line.substring(0, next_line.length()-6); year = next_line.substring(next_line.length()-5, next_line.length()-1); } else Month = next_line; } if(partNum == 7) { partNum=0; if(!isType(next_line)) { link = next_line; } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); } partNum++; } } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); DBReaderBuffered.close(); parseAuthors(); return true; } return false; }
public boolean parsePublications() throws IOException { if(isValidSearchName(getFileLoc())) { FileReader DBReader = new FileReader(getFileLoc()); BufferedReader DBReaderBuffered = new BufferedReader(DBReader); String next_line=""; int partNum = 1; String type = ""; ArrayList<String> authors = new ArrayList<String>(); String titlePaper = ""; String titleSerial = ""; String pageStart = "0"; String pageEnd = "0"; String Month = ""; String year =""; String volume = ""; String issue = ""; String link = ""; while(DBReaderBuffered.ready()) { next_line=DBReaderBuffered.readLine(); if(next_line != null && next_line.length() > 0) { //TODO use modulus instead of partNum if(partNum == 1) { type = next_line; } if(partNum == 2) { authors = parseAuthorList(next_line); for(String author : authors) { if(this.authors.get(author) == null) { this.authors.put(author, new Author(author)); } } } if(partNum == 3) { titlePaper = next_line; } if(partNum == 4) { titleSerial = next_line; } if(partNum == 5) { if(type.toLowerCase().equals("conference paper")) { pageStart = next_line.split("\\-")[0]; if(next_line.contains("-")) { pageEnd = next_line.split("\\-")[1]; } } else if(type.toLowerCase().equals("journal article")) { volume = next_line.split("\\(")[0]; if(next_line.contains("(")) { issue = next_line.split("\\(")[1].split("\\)")[0]; } if(next_line.contains(":")) { pageStart = next_line.split("\\:")[1].split("\\-")[0]; } if(next_line.contains(":") && next_line.contains("-")) { pageEnd = next_line.split("\\:")[1].split("\\-")[1]; } } } if(partNum == 6) { if(next_line.contains(" ") == true) { Month = next_line.split("\\ ")[0]; year = next_line.split("\\ ")[1]; } else if(next_line.length() >= 5 && Publication.isNumeric(next_line.substring(next_line.length()-2))) { Month = next_line.substring(0, next_line.length()-5); year = next_line.substring(next_line.length()-5, next_line.length()-1); } else Month = next_line; } if(partNum == 7) { partNum=0; if(!isType(next_line)) { link = next_line; } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); } partNum++; } } if(type.toLowerCase().equals("conference paper")) publications.put(titlePaper, new Publication(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link)); if(type.toLowerCase().equals("journal article")) publications.put(titlePaper, new JournalArticle(authors,titlePaper, titleSerial, pageStart, pageEnd, Month, year, link, volume, issue)); DBReaderBuffered.close(); parseAuthors(); return true; } return false; }
diff --git a/dalvik-explorer/src/org/jessies/dalvikexplorer/DeviceActivity.java b/dalvik-explorer/src/org/jessies/dalvikexplorer/DeviceActivity.java index 643cb70..f70ec50 100644 --- a/dalvik-explorer/src/org/jessies/dalvikexplorer/DeviceActivity.java +++ b/dalvik-explorer/src/org/jessies/dalvikexplorer/DeviceActivity.java @@ -1,225 +1,225 @@ package org.jessies.dalvikexplorer; import android.app.*; import android.content.pm.*; import android.os.*; import android.util.*; import android.view.*; import android.widget.*; import java.io.*; import java.lang.reflect.*; import java.util.*; public class DeviceActivity extends TextViewActivity { protected CharSequence title(String unused) { return "Device Details"; } protected CharSequence content(String unused) { return getDeviceDetailsAsString(this, getWindowManager()); } // sysconf _SC_NPROCESSORS_CONF and _SC_NPROCESSORS_ONLN have been broken // in bionic for various different reasons. /proc parsing was broken until // Gingerbread, and even then _SC_NPROCESSORS_CONF was broken because ARM // kernels remove offline processors from both /proc/stat and /proc/cpuinfo // unlike x86 ones; you need to look in /sys/devices/system/cpu to see all // the processors. This should be fixed some time post-JB. private static int countHardwareCores() { int result = 0; for (String file : new File("/sys/devices/system/cpu").list()) { if (file.matches("cpu[0-9]+")) { ++result; } } return result; } private static int countEnabledCores() { int count = 0; BufferedReader in = null; try { in = new BufferedReader(new FileReader("/proc/stat")); String line; while ((line = in.readLine()) != null) { if (line.startsWith("cpu") && !line.startsWith("cpu ")) { ++count; } } return count; } catch (IOException ex) { return -1; } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } } private static String valueForKey(String[] lines, String key) { String key1 = key + "\t: "; String key2 = key + ": "; for (String line : lines) { if (line.startsWith(key1)) { return line.substring(key1.length()); } else if (line.startsWith(key2)) { return line.substring(key2.length()); } } return null; } private static int numericValueForKey(String[] lines, String key) { String value = valueForKey(lines, key); if (value == null) { return -1; } int base = 10; if (value.startsWith("0x")) { base = 16; value = value.substring(2); } try { return Integer.valueOf(value, base); } catch (NumberFormatException ex) { return -1; } } private static String decodeImplementer(int implementer) { // From http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0014q/Bcfihfdj.html if (implementer == 0x41) { return "ARM"; } else if (implementer == 0x44) { return "Digital Equipment Corporation"; } else if (implementer == 0x4d) { return "Motorola"; } else if (implementer == 0x51) { return "Qualcomm"; } else if (implementer == 0x56) { return "Marvell"; } else if (implementer == 0x69) { return "Intel"; } else { return "unknown (0x" + Integer.toHexString(implementer) + ")"; } } private static String decodePartNumber(int part) { if (part == 0x920) { return "ARM920"; } else if (part == 0x926) { return "ARM926"; } else if (part == 0xa26) { return "ARM1026"; } else if (part == 0xb02) { return "ARM11mpcore"; } else if (part == 0xb36) { return "ARM1136"; } else if (part == 0xb56) { return "ARM1156"; } else if (part == 0xb76) { return "ARM1176"; } else if (part == 0xc05) { return "Cortex-A5"; } else if (part == 0xc07) { return "Cortex-A7"; } else if (part == 0xc08) { return "Cortex-A8"; } else if (part == 0xc09) { return "Cortex-A9"; } else if (part == 0xc0f) { return "Cortex-A15"; } else if (part == 0xc14) { return "Cortex-R4"; } else if (part == 0xc15) { return "Cortex-R5"; } else if (part == 0xc20) { return "Cortex-M0"; } else if (part == 0xc21) { return "Cortex-M1"; } else if (part == 0xc23) { return "Cortex-M3"; } else if (part == 0xc24) { return "Cortex-M4"; } else { return "unknown (0x" + Integer.toHexString(part) + ")"; } } static String getDeviceDetailsAsString(Activity context, WindowManager wm) { final StringBuilder result = new StringBuilder(); String[] procCpuLines = Utils.readFile("/proc/cpuinfo").split("\n"); String processor = valueForKey(procCpuLines, "Processor"); if (processor == null) { processor = valueForKey(procCpuLines, "model name"); } result.append("Processor: " + processor + "\n"); int hardwareCoreCount = countHardwareCores(); int enabledCoreCount = countEnabledCores(); String cores = Integer.toString(hardwareCoreCount); if (enabledCoreCount != hardwareCoreCount) { cores += " (enabled: " + enabledCoreCount + ")"; } result.append("Cores: " + cores + "\n"); result.append('\n'); String features = valueForKey(procCpuLines, "Features"); if (features == null) { features = valueForKey(procCpuLines, "flags\t"); } result.append("Features: " + features + "\n"); result.append('\n'); // ARM-specific. int implementer = numericValueForKey(procCpuLines, "CPU implementer"); if (implementer != -1) { result.append("CPU Implementer: " + decodeImplementer(implementer) + "\n"); result.append("CPU Part: " + decodePartNumber(numericValueForKey(procCpuLines, "CPU part")) + "\n"); // These two are included in the kernel's formatting of "Processor". //result.append("CPU Architecture: " + numericValueForKey(procCpuLines, "CPU architecture") + "\n"); //result.append("CPU Revision: " + numericValueForKey(procCpuLines, "CPU revision") + "\n"); result.append("CPU Variant: " + numericValueForKey(procCpuLines, "CPU variant") + "\n"); result.append('\n'); result.append("Hardware: " + valueForKey(procCpuLines, "Hardware") + "\n"); result.append("Revision: " + valueForKey(procCpuLines, "Revision") + "\n"); result.append("Serial: " + valueForKey(procCpuLines, "Serial\t") + "\n"); result.append('\n'); } // Intel-specific. String cacheSize = valueForKey(procCpuLines, "cache size"); String addressSizes = valueForKey(procCpuLines, "address sizes"); - if (cache_size != null) { + if (cacheSize != null) { result.append("Cache: " + cacheSize + "\n"); result.append("Address Sizes: " + addressSizes + "\n"); result.append('\n'); } DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); result.append("Screen Density: " + metrics.densityDpi + "dpi (" + metrics.density + "x DIP)\n"); result.append("Screen Size: " + metrics.widthPixels + " x " + metrics.heightPixels + " pixels\n"); result.append("Exact DPI: " + metrics.xdpi + " x " + metrics.ydpi + "\n"); double widthInches = metrics.widthPixels/metrics.xdpi; double heightInches = metrics.heightPixels/metrics.ydpi; double diagonalInches = Math.sqrt(widthInches*widthInches + heightInches*heightInches); result.append(String.format("Approximate Dimensions: %.1f\" x %.1f\" (%.1f\" diagonal)\n", widthInches, heightInches, diagonalInches)); result.append('\n'); return result.toString(); } private static String getFieldReflectively(Build build, String fieldName) { try { final Field field = Build.class.getField(fieldName); return field.get(build).toString(); } catch (Exception ex) { return "unknown"; } } }
true
true
static String getDeviceDetailsAsString(Activity context, WindowManager wm) { final StringBuilder result = new StringBuilder(); String[] procCpuLines = Utils.readFile("/proc/cpuinfo").split("\n"); String processor = valueForKey(procCpuLines, "Processor"); if (processor == null) { processor = valueForKey(procCpuLines, "model name"); } result.append("Processor: " + processor + "\n"); int hardwareCoreCount = countHardwareCores(); int enabledCoreCount = countEnabledCores(); String cores = Integer.toString(hardwareCoreCount); if (enabledCoreCount != hardwareCoreCount) { cores += " (enabled: " + enabledCoreCount + ")"; } result.append("Cores: " + cores + "\n"); result.append('\n'); String features = valueForKey(procCpuLines, "Features"); if (features == null) { features = valueForKey(procCpuLines, "flags\t"); } result.append("Features: " + features + "\n"); result.append('\n'); // ARM-specific. int implementer = numericValueForKey(procCpuLines, "CPU implementer"); if (implementer != -1) { result.append("CPU Implementer: " + decodeImplementer(implementer) + "\n"); result.append("CPU Part: " + decodePartNumber(numericValueForKey(procCpuLines, "CPU part")) + "\n"); // These two are included in the kernel's formatting of "Processor". //result.append("CPU Architecture: " + numericValueForKey(procCpuLines, "CPU architecture") + "\n"); //result.append("CPU Revision: " + numericValueForKey(procCpuLines, "CPU revision") + "\n"); result.append("CPU Variant: " + numericValueForKey(procCpuLines, "CPU variant") + "\n"); result.append('\n'); result.append("Hardware: " + valueForKey(procCpuLines, "Hardware") + "\n"); result.append("Revision: " + valueForKey(procCpuLines, "Revision") + "\n"); result.append("Serial: " + valueForKey(procCpuLines, "Serial\t") + "\n"); result.append('\n'); } // Intel-specific. String cacheSize = valueForKey(procCpuLines, "cache size"); String addressSizes = valueForKey(procCpuLines, "address sizes"); if (cache_size != null) { result.append("Cache: " + cacheSize + "\n"); result.append("Address Sizes: " + addressSizes + "\n"); result.append('\n'); } DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); result.append("Screen Density: " + metrics.densityDpi + "dpi (" + metrics.density + "x DIP)\n"); result.append("Screen Size: " + metrics.widthPixels + " x " + metrics.heightPixels + " pixels\n"); result.append("Exact DPI: " + metrics.xdpi + " x " + metrics.ydpi + "\n"); double widthInches = metrics.widthPixels/metrics.xdpi; double heightInches = metrics.heightPixels/metrics.ydpi; double diagonalInches = Math.sqrt(widthInches*widthInches + heightInches*heightInches); result.append(String.format("Approximate Dimensions: %.1f\" x %.1f\" (%.1f\" diagonal)\n", widthInches, heightInches, diagonalInches)); result.append('\n'); return result.toString(); }
static String getDeviceDetailsAsString(Activity context, WindowManager wm) { final StringBuilder result = new StringBuilder(); String[] procCpuLines = Utils.readFile("/proc/cpuinfo").split("\n"); String processor = valueForKey(procCpuLines, "Processor"); if (processor == null) { processor = valueForKey(procCpuLines, "model name"); } result.append("Processor: " + processor + "\n"); int hardwareCoreCount = countHardwareCores(); int enabledCoreCount = countEnabledCores(); String cores = Integer.toString(hardwareCoreCount); if (enabledCoreCount != hardwareCoreCount) { cores += " (enabled: " + enabledCoreCount + ")"; } result.append("Cores: " + cores + "\n"); result.append('\n'); String features = valueForKey(procCpuLines, "Features"); if (features == null) { features = valueForKey(procCpuLines, "flags\t"); } result.append("Features: " + features + "\n"); result.append('\n'); // ARM-specific. int implementer = numericValueForKey(procCpuLines, "CPU implementer"); if (implementer != -1) { result.append("CPU Implementer: " + decodeImplementer(implementer) + "\n"); result.append("CPU Part: " + decodePartNumber(numericValueForKey(procCpuLines, "CPU part")) + "\n"); // These two are included in the kernel's formatting of "Processor". //result.append("CPU Architecture: " + numericValueForKey(procCpuLines, "CPU architecture") + "\n"); //result.append("CPU Revision: " + numericValueForKey(procCpuLines, "CPU revision") + "\n"); result.append("CPU Variant: " + numericValueForKey(procCpuLines, "CPU variant") + "\n"); result.append('\n'); result.append("Hardware: " + valueForKey(procCpuLines, "Hardware") + "\n"); result.append("Revision: " + valueForKey(procCpuLines, "Revision") + "\n"); result.append("Serial: " + valueForKey(procCpuLines, "Serial\t") + "\n"); result.append('\n'); } // Intel-specific. String cacheSize = valueForKey(procCpuLines, "cache size"); String addressSizes = valueForKey(procCpuLines, "address sizes"); if (cacheSize != null) { result.append("Cache: " + cacheSize + "\n"); result.append("Address Sizes: " + addressSizes + "\n"); result.append('\n'); } DisplayMetrics metrics = new DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); result.append("Screen Density: " + metrics.densityDpi + "dpi (" + metrics.density + "x DIP)\n"); result.append("Screen Size: " + metrics.widthPixels + " x " + metrics.heightPixels + " pixels\n"); result.append("Exact DPI: " + metrics.xdpi + " x " + metrics.ydpi + "\n"); double widthInches = metrics.widthPixels/metrics.xdpi; double heightInches = metrics.heightPixels/metrics.ydpi; double diagonalInches = Math.sqrt(widthInches*widthInches + heightInches*heightInches); result.append(String.format("Approximate Dimensions: %.1f\" x %.1f\" (%.1f\" diagonal)\n", widthInches, heightInches, diagonalInches)); result.append('\n'); return result.toString(); }
diff --git a/src/impl/java/org/wyona/security/impl/util/PolicyAggregator.java b/src/impl/java/org/wyona/security/impl/util/PolicyAggregator.java index 8d17889..b4224f5 100644 --- a/src/impl/java/org/wyona/security/impl/util/PolicyAggregator.java +++ b/src/impl/java/org/wyona/security/impl/util/PolicyAggregator.java @@ -1,79 +1,77 @@ package org.wyona.security.impl.util; import org.wyona.security.core.AuthorizationException; import org.wyona.security.core.UsecasePolicy; import org.wyona.security.core.api.Policy; import org.wyona.security.core.api.PolicyManager; /* import org.wyona.security.core.GroupPolicy; import org.wyona.security.core.api.Identity; */ import org.wyona.commons.io.PathUtil; import org.apache.log4j.Logger; /** * Utility class to aggregate policies based on their parent policies */ public class PolicyAggregator { private static Logger log = Logger.getLogger(PolicyAggregator.class); /** * */ public static Policy aggregatePolicy(Policy policy) throws AuthorizationException { return policy; } /** * */ public static Policy aggregatePolicy(String path, PolicyManager pm) throws AuthorizationException { Policy policy = pm.getPolicy(path, false); if (policy == null) { if (!path.equals("/")) { return aggregatePolicy(PathUtil.getParent(path), pm); } else { log.warn("No policies found at all, not even a root policy!"); return null; } } else { if (!policy.useInheritedPolicies()) { return policy; } else { if (!path.equals("/")) { Policy parentPolicy = aggregatePolicy(PathUtil.getParent(path), pm); UsecasePolicy[] usecasePolicies = policy.getUsecasePolicies(); UsecasePolicy[] parentUsecasePolicies = parentPolicy.getUsecasePolicies(); for (int i = 0; i < parentUsecasePolicies.length; i++) { boolean usecaseAlreadyExists = false; for (int k = 0; k < usecasePolicies.length; k++) { if (parentUsecasePolicies[i].getName().equals(usecasePolicies[k].getName())) { usecaseAlreadyExists = true; + usecasePolicies[k].merge(parentUsecasePolicies[i]); break; } } if(!usecaseAlreadyExists) { try { policy.addUsecasePolicy(parentUsecasePolicies[i]); } catch(Exception e) { log.error(e, e); throw new AuthorizationException(e.getMessage()); } - } else { - // TODO: Add additional world, identities, groups ... - log.warn("TODO: Merge policy " + path + " with parent " + PathUtil.getParent(path) + " for usecase: " + parentUsecasePolicies[i].getName()); } } return policy; } else { return policy; } } } } }
false
true
public static Policy aggregatePolicy(String path, PolicyManager pm) throws AuthorizationException { Policy policy = pm.getPolicy(path, false); if (policy == null) { if (!path.equals("/")) { return aggregatePolicy(PathUtil.getParent(path), pm); } else { log.warn("No policies found at all, not even a root policy!"); return null; } } else { if (!policy.useInheritedPolicies()) { return policy; } else { if (!path.equals("/")) { Policy parentPolicy = aggregatePolicy(PathUtil.getParent(path), pm); UsecasePolicy[] usecasePolicies = policy.getUsecasePolicies(); UsecasePolicy[] parentUsecasePolicies = parentPolicy.getUsecasePolicies(); for (int i = 0; i < parentUsecasePolicies.length; i++) { boolean usecaseAlreadyExists = false; for (int k = 0; k < usecasePolicies.length; k++) { if (parentUsecasePolicies[i].getName().equals(usecasePolicies[k].getName())) { usecaseAlreadyExists = true; break; } } if(!usecaseAlreadyExists) { try { policy.addUsecasePolicy(parentUsecasePolicies[i]); } catch(Exception e) { log.error(e, e); throw new AuthorizationException(e.getMessage()); } } else { // TODO: Add additional world, identities, groups ... log.warn("TODO: Merge policy " + path + " with parent " + PathUtil.getParent(path) + " for usecase: " + parentUsecasePolicies[i].getName()); } } return policy; } else { return policy; } } } }
public static Policy aggregatePolicy(String path, PolicyManager pm) throws AuthorizationException { Policy policy = pm.getPolicy(path, false); if (policy == null) { if (!path.equals("/")) { return aggregatePolicy(PathUtil.getParent(path), pm); } else { log.warn("No policies found at all, not even a root policy!"); return null; } } else { if (!policy.useInheritedPolicies()) { return policy; } else { if (!path.equals("/")) { Policy parentPolicy = aggregatePolicy(PathUtil.getParent(path), pm); UsecasePolicy[] usecasePolicies = policy.getUsecasePolicies(); UsecasePolicy[] parentUsecasePolicies = parentPolicy.getUsecasePolicies(); for (int i = 0; i < parentUsecasePolicies.length; i++) { boolean usecaseAlreadyExists = false; for (int k = 0; k < usecasePolicies.length; k++) { if (parentUsecasePolicies[i].getName().equals(usecasePolicies[k].getName())) { usecaseAlreadyExists = true; usecasePolicies[k].merge(parentUsecasePolicies[i]); break; } } if(!usecaseAlreadyExists) { try { policy.addUsecasePolicy(parentUsecasePolicies[i]); } catch(Exception e) { log.error(e, e); throw new AuthorizationException(e.getMessage()); } } } return policy; } else { return policy; } } } }
diff --git a/zico-core/src/main/java/com/jitlogic/zico/core/rest/SystemService.java b/zico-core/src/main/java/com/jitlogic/zico/core/rest/SystemService.java index 22a96cd3..db7600d9 100644 --- a/zico-core/src/main/java/com/jitlogic/zico/core/rest/SystemService.java +++ b/zico-core/src/main/java/com/jitlogic/zico/core/rest/SystemService.java @@ -1,89 +1,89 @@ /** * Copyright 2012-2013 Rafal Lewczuk <[email protected]> * <p/> * This 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. * <p/> * 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 General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ package com.jitlogic.zico.core.rest; import com.jitlogic.zico.core.ZicoConfig; import com.jitlogic.zorka.common.ZorkaAgent; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Path("system") public class SystemService { private ZicoConfig config; @Inject public SystemService(ZicoConfig config) { this.config = config; } @GET @Path("/info") @Produces(MediaType.APPLICATION_JSON) public List<String> systemInfo() { List<String> info = new ArrayList<String>(); // TODO use agent to present these things - it's already there :) info.add("Version: " + config.stringCfg("zico.version", "<null>")); MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); MemoryUsage hmu = mem.getHeapMemoryUsage(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000; - long ss = uptime % 60, mm = ((uptime - ss) / 60) % 60, hh = ((uptime - mm * 60 - ss) / 3600) % 60, + long ss = uptime % 60, mm = ((uptime - ss) / 60) % 60, hh = ((uptime - mm * 60 - ss) / 3600) % 24, dd = ((uptime - hh * 3600 - mm * 60 - ss) / 86400); info.add("Uptime: " + String.format("%dd %02d:%02d:%02d", dd, hh, mm, ss)); info.add("Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", hmu.getUsed() / MB, hmu.getMax() / MB, 100.0 * hmu.getUsed() / hmu.getMax())); MemoryUsage nmu = mem.getNonHeapMemoryUsage(); info.add("Non-Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", nmu.getUsed() / MB, nmu.getMax() / MB, 100.0 * nmu.getUsed() / nmu.getMax())); try { if (agent != null) { info.addAll(Arrays.asList(agent.query("zico.info()").split("\n"))); } } catch (Exception e) { //log.warn("Call to self-monitoring agent failed.", e); } return info; } private static final long MB = 1024 * 1024; private ZorkaAgent agent; public void setAgent(ZorkaAgent agent) { this.agent = agent; } }
true
true
public List<String> systemInfo() { List<String> info = new ArrayList<String>(); // TODO use agent to present these things - it's already there :) info.add("Version: " + config.stringCfg("zico.version", "<null>")); MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); MemoryUsage hmu = mem.getHeapMemoryUsage(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000; long ss = uptime % 60, mm = ((uptime - ss) / 60) % 60, hh = ((uptime - mm * 60 - ss) / 3600) % 60, dd = ((uptime - hh * 3600 - mm * 60 - ss) / 86400); info.add("Uptime: " + String.format("%dd %02d:%02d:%02d", dd, hh, mm, ss)); info.add("Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", hmu.getUsed() / MB, hmu.getMax() / MB, 100.0 * hmu.getUsed() / hmu.getMax())); MemoryUsage nmu = mem.getNonHeapMemoryUsage(); info.add("Non-Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", nmu.getUsed() / MB, nmu.getMax() / MB, 100.0 * nmu.getUsed() / nmu.getMax())); try { if (agent != null) { info.addAll(Arrays.asList(agent.query("zico.info()").split("\n"))); } } catch (Exception e) { //log.warn("Call to self-monitoring agent failed.", e); } return info; }
public List<String> systemInfo() { List<String> info = new ArrayList<String>(); // TODO use agent to present these things - it's already there :) info.add("Version: " + config.stringCfg("zico.version", "<null>")); MemoryMXBean mem = ManagementFactory.getMemoryMXBean(); MemoryUsage hmu = mem.getHeapMemoryUsage(); long uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000; long ss = uptime % 60, mm = ((uptime - ss) / 60) % 60, hh = ((uptime - mm * 60 - ss) / 3600) % 24, dd = ((uptime - hh * 3600 - mm * 60 - ss) / 86400); info.add("Uptime: " + String.format("%dd %02d:%02d:%02d", dd, hh, mm, ss)); info.add("Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", hmu.getUsed() / MB, hmu.getMax() / MB, 100.0 * hmu.getUsed() / hmu.getMax())); MemoryUsage nmu = mem.getNonHeapMemoryUsage(); info.add("Non-Heap Memory: " + String.format("%dMB/%dMB (%.1f%%)", nmu.getUsed() / MB, nmu.getMax() / MB, 100.0 * nmu.getUsed() / nmu.getMax())); try { if (agent != null) { info.addAll(Arrays.asList(agent.query("zico.info()").split("\n"))); } } catch (Exception e) { //log.warn("Call to self-monitoring agent failed.", e); } return info; }
diff --git a/src/xandrew/game/light/LightBeam.java b/src/xandrew/game/light/LightBeam.java index 0a05fa9..b174c62 100644 --- a/src/xandrew/game/light/LightBeam.java +++ b/src/xandrew/game/light/LightBeam.java @@ -1,106 +1,106 @@ package xandrew.game.light; import javax.media.opengl.GL; import scene.GLRenderable; import scene.shapes.GLSquare; /** * Defines a light beam * @author Andrew */ public class LightBeam implements GLRenderable { /** Point of origin */ public float xPos, yPos; public float destX, destY; public float rotation; public boolean isPowered; public boolean isSourceLight; /** * Creates a light beam from a central point * @param x * @param y */ public LightBeam(float x, float y) { this(x, y, false); } public LightBeam(float x, float y, boolean sourceLight) { this.xPos = x; this.yPos = y; destX = x; destY = y; rotation = (float) (Math.random() * 360); isPowered = false; isSourceLight = sourceLight; } /** The square to draw at the source */ private static final GLSquare square = new GLSquare(); private static boolean inited = false; public void init(GL gl) { if(!inited) { square.setFileName("images/LightTurret.png"); square.init(gl); inited = true; } } public void update() { } public boolean isEmitting() { return isPowered; } public float getScale() { return 8.0f; } public void draw(GL gl) { square.setColour(new float[] {1.0f, 1.0f, 0.0f, 1.0f}); gl.glPushMatrix(); gl.glTranslatef(xPos, yPos, 0.0f); if(!isEmitting()) - gl.glTranslatef(0.0f, 0.0f, -6f); + gl.glTranslatef(0.0f, 0.0f, -1f); //square.setColour(new float[] {0.0f, 0.0f, 0.0f, 1.0f}); gl.glScaled(getScale(), getScale(), 1.0); //8x8 square square.draw(gl); gl.glPopMatrix(); if(isEmitting()) { gl.glLineWidth(2); gl.glBegin(GL.GL_LINES); gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertex2f(xPos, yPos); gl.glVertex2f(destX,destY); gl.glEnd(); } } }
true
true
public void draw(GL gl) { square.setColour(new float[] {1.0f, 1.0f, 0.0f, 1.0f}); gl.glPushMatrix(); gl.glTranslatef(xPos, yPos, 0.0f); if(!isEmitting()) gl.glTranslatef(0.0f, 0.0f, -6f); //square.setColour(new float[] {0.0f, 0.0f, 0.0f, 1.0f}); gl.glScaled(getScale(), getScale(), 1.0); //8x8 square square.draw(gl); gl.glPopMatrix(); if(isEmitting()) { gl.glLineWidth(2); gl.glBegin(GL.GL_LINES); gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertex2f(xPos, yPos); gl.glVertex2f(destX,destY); gl.glEnd(); } }
public void draw(GL gl) { square.setColour(new float[] {1.0f, 1.0f, 0.0f, 1.0f}); gl.glPushMatrix(); gl.glTranslatef(xPos, yPos, 0.0f); if(!isEmitting()) gl.glTranslatef(0.0f, 0.0f, -1f); //square.setColour(new float[] {0.0f, 0.0f, 0.0f, 1.0f}); gl.glScaled(getScale(), getScale(), 1.0); //8x8 square square.draw(gl); gl.glPopMatrix(); if(isEmitting()) { gl.glLineWidth(2); gl.glBegin(GL.GL_LINES); gl.glColor4f(1.0f, 0.0f, 0.0f, 1.0f); gl.glVertex2f(xPos, yPos); gl.glVertex2f(destX,destY); gl.glEnd(); } }
diff --git a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java index e011dc421..f45749c42 100644 --- a/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java +++ b/core/src/main/java/org/apache/mahout/clustering/kmeans/KMeansClusterMapper.java @@ -1,69 +1,69 @@ /** * 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.mahout.clustering.kmeans; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Mapper; import org.apache.mahout.clustering.WeightedVectorWritable; import org.apache.mahout.common.distance.DistanceMeasure; import org.apache.mahout.math.VectorWritable; public class KMeansClusterMapper extends Mapper<WritableComparable<?>,VectorWritable,IntWritable,WeightedVectorWritable> { private final List<Cluster> clusters = new ArrayList<Cluster>(); private KMeansClusterer clusterer; @Override protected void map(WritableComparable<?> key, VectorWritable point, Context context) throws IOException, InterruptedException { clusterer.outputPointWithClusterInfo(point.get(), clusters, context); } @Override protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); Configuration conf = context.getConfiguration(); try { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY)) .asSubclass(DistanceMeasure.class).newInstance(); measure.configure(conf); String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY); if ((clusterPath != null) && (clusterPath.length() > 0)) { KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters); if (clusters.isEmpty()) { - throw new IllegalStateException("Cluster is empty!"); + throw new IllegalStateException("No clusters found. Check your -c path."); } } this.clusterer = new KMeansClusterer(measure); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } } }
true
true
protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); Configuration conf = context.getConfiguration(); try { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY)) .asSubclass(DistanceMeasure.class).newInstance(); measure.configure(conf); String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY); if ((clusterPath != null) && (clusterPath.length() > 0)) { KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters); if (clusters.isEmpty()) { throw new IllegalStateException("Cluster is empty!"); } } this.clusterer = new KMeansClusterer(measure); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } }
protected void setup(Context context) throws IOException, InterruptedException { super.setup(context); Configuration conf = context.getConfiguration(); try { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); DistanceMeasure measure = ccl.loadClass(conf.get(KMeansConfigKeys.DISTANCE_MEASURE_KEY)) .asSubclass(DistanceMeasure.class).newInstance(); measure.configure(conf); String clusterPath = conf.get(KMeansConfigKeys.CLUSTER_PATH_KEY); if ((clusterPath != null) && (clusterPath.length() > 0)) { KMeansUtil.configureWithClusterInfo(new Path(clusterPath), clusters); if (clusters.isEmpty()) { throw new IllegalStateException("No clusters found. Check your -c path."); } } this.clusterer = new KMeansClusterer(measure); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (InstantiationException e) { throw new IllegalStateException(e); } }
diff --git a/src/main/ed/lang/python/Python.java b/src/main/ed/lang/python/Python.java index e834d8546..ba9a46c4d 100644 --- a/src/main/ed/lang/python/Python.java +++ b/src/main/ed/lang/python/Python.java @@ -1,487 +1,493 @@ // Python.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ed.lang.python; import java.io.*; import java.util.*; import org.python.core.*; import org.python.antlr.*; import org.python.antlr.ast.*; import org.python.modules.sre.PatternObject; import org.python.modules.sre.SRE_STATE; import org.python.expose.*; import org.python.expose.generate.*; import ed.db.*; import ed.util.*; import ed.js.*; import ed.js.engine.*; import ed.js.func.*; import ed.lang.*; import ed.appserver.*; import static ed.lang.python.PythonSmallWrappers.*; public class Python extends Language { public Python(){ super( "python" ); } static final boolean D = Boolean.getBoolean( "DEBUG.PY" ); static { Options.includeJavaStackInExceptions = true; PySystemState.initialize(); } public static PyCode compile( File f ) throws IOException { return (PyCode)(Py.compile( new FileInputStream( f ) , f.toString() , "exec" )); } public static void deleteCachedJythonFiles( File dir ){ for( File child : dir.listFiles() ){ if( child.getName().endsWith( "$py.class") ){ child.delete(); } if( child.isDirectory() ){ deleteCachedJythonFiles( child ); } } } public static Object toJS( Object p ){ if( D ) System.out.println( "toJS " + p + " " + p.getClass()); if ( p == null || p instanceof PyNone ) return null; if ( p instanceof JSObject || p instanceof JSString || p instanceof ed.log.Level || p instanceof Number ) return p; if ( p instanceof String ) return new JSString( p.toString() ); if ( p instanceof PyJSStringWrapper ) p = ((PyJSStringWrapper)p)._p; if ( p instanceof PyJSObjectWrapper ){ if( D ) System.out.println( "unwrapping " + p ); return ((PyJSObjectWrapper)p)._js; } if ( p instanceof PyJSLogLevelWrapper ) return ((PyJSLogLevelWrapper)p)._level; if ( p instanceof PyJSArrayWrapper ) return ((PyJSArrayWrapper)p)._js; if ( p instanceof PyBoolean ) return ((PyBoolean)p).getValue() == 1; if ( p instanceof PyInteger ) return ((PyInteger)p).getValue(); if ( p instanceof PyFloat ) return ((PyFloat)p).getValue(); if ( p instanceof PyString ) return new JSString( p.toString() ); if ( p instanceof PyObjectId ) return ((PyObjectId)p)._id; if ( p instanceof PyClass || p instanceof PyType ){ return new JSPyClassWrapper( (PyObject)p ); } if ( p instanceof PySequenceList ){ return new JSPySequenceListWrapper((PySequenceList)p); } // TODO: this doesn't support several of the Python extensions // known things that won't work: // (?iLmsux) // (?P<name>...) // (?P=name) // (?#...) // (?<=...) // (?<!...) // (?(id/name)yes-pattern|no-pattern) // LOCALE, UNICODE and VERBOSE flags // either of MULTILINE or DOTALL will be translated to both MULTILINE and DOTALL // {,n} doesn't work. can be written as {0,n} which will work // other stuff could be broken as well... if (p instanceof PatternObject) { PatternObject re = (PatternObject)p; // all Python re's get the JS global match flag String flags = "g"; if ((re.flags & SRE_STATE.SRE_FLAG_IGNORECASE) > 0) { flags = flags + "i"; } if ((re.flags & SRE_STATE.SRE_FLAG_MULTILINE) > 0 || (re.flags & SRE_STATE.SRE_FLAG_DOTALL) > 0) { flags = flags + "m"; } return new JSRegex(re.pattern.toString(), flags); } // Insufficiently Pythonic? - if ( p instanceof PyObjectDerived && ((PyObject)p).getType().fastGetName().equals( "datetime" ) ){ - Object cal = ((PyObject)p).__tojava__( Calendar.class ); - if( cal != Py.NoConversion ){ - return new JSDate( (Calendar)cal ); + if ( p instanceof PyObjectDerived ){ + PyType type = ((PyObject)p).getType(); + if( type != null && type.fastGetName() != null ){ + String name = type.fastGetName(); + if( name != null && name.equals( "datetime" ) ){ + Object cal = ((PyObject)p).__tojava__( Calendar.class ); + if( cal != Py.NoConversion ){ + return new JSDate( (Calendar)cal ); + } + } } } // this needs to be last if ( p instanceof PyObject ) return new JSPyObjectWrapper( (PyObject)p ); throw new RuntimeException( "can't convert [" + p.getClass().getName() + "] from py to js" ); } public static PyObject toPython( Object o ){ return toPython( o , null ); } public static PyObject toPython( Object o , Object useThis ){ if ( o == null ) return Py.None; if ( o instanceof DBRef ) o = ((DBRef)o).doLoad(); if ( o == null ) return Py.None; if ( o instanceof JSPyObjectWrapper ) return ((JSPyObjectWrapper)o).getContained(); if ( o instanceof PyObject ) return (PyObject)o; if ( o instanceof Boolean ) return new PyBoolean( (Boolean)o ); if ( o instanceof Integer ) return new PyInteger( ((Integer)o).intValue() ); if ( o instanceof Number ) return new PyFloat( ((Number)o).doubleValue() ); if ( o instanceof String ) return new PyString( (String)o ); if ( o instanceof JSString ) return new PyJSStringWrapper( (JSString)o ); if ( o instanceof ed.db.ObjectId ) return new PyObjectId( (ed.db.ObjectId)o ); // FILL IN MORE HERE if (o instanceof JSRegex) { PyObject re = __builtin__.__import__("re"); JSRegex regex = (JSRegex)o; ArrayList<PyObject> args = new ArrayList<PyObject>(); args.add(new PyString(regex.getPattern())); if (regex.getFlags().contains("i")) { args.add(re.__findattr__("I".intern())); } if (regex.getFlags().contains("m")) { args.add(re.__findattr__("M".intern())); args.add(re.__findattr__("S".intern())); } PyObject compile = re.__findattr__("compile".intern()); return compile.__call__(args.toArray(new PyObject[1])); } if ( o instanceof JSArray ){ return new PyJSArrayWrapper( (JSArray)o ); } if ( o instanceof ed.log.Level ){ return new PyJSLogLevelWrapper( (ed.log.Level)o ); } // these should be at the bottom if ( o instanceof JSFunction ){ Object p = ((JSFunction)o).getPrototype(); if( p instanceof JSObject ){ JSObject jsp = (JSObject)p; if( ! jsp.keySet().isEmpty() ) return new PyJSClassWrapper( (JSFunction)o ); } return new PyJSFunctionWrapper( (JSFunction)o , useThis ); } if ( o instanceof JSObject ) return new PyJSObjectWrapper( (JSObject)o ); throw new RuntimeException( "can't convert [" + o.getClass().getName() + "] from js to py" ); } public JSFunction compileLambda( final String source ){ return extractLambda( source ); } public Object eval( Scope s , String code , boolean[] hasReturn ){ if( D ) System.out.println( "Doing eval on " + code ); PyObject globals = getGlobals( s ); code = code+ "\n"; PyCode pycode; String filename = "<input>"; // Hideous antlr code to figure out if this is a module or an expression ModuleParser m = new ModuleParser( new org.antlr.runtime.ANTLRStringStream( code ) , filename , false ); modType tree = m.file_input(); if( ! ( tree instanceof org.python.antlr.ast.Module ) ){ // no idea what this would mean -- tell Ethan throw new RuntimeException( "can't happen -- blame Ethan" ); } // Module is the class meaning "toplevel sequence of statements" org.python.antlr.ast.Module mod = (org.python.antlr.ast.Module)tree; // If there's only one statement and it's an expression statement, // compile just that expression as its own module. hasReturn[0] = mod.body != null && mod.body.length == 1 && (mod.body[0] instanceof Expr ); if( hasReturn[0] ){ // I guess this class is treated specially, has a return value, etc. Expression expr = new Expression( new PythonTree() , ((Expr)mod.body[0]).value ); pycode = (PyCode)Py.compile( expr , filename ); } else { // Otherwise compile the whole module pycode = (PyCode)Py.compile( mod , filename ); } return toJS( __builtin__.eval( pycode , globals ) ); } public static PyObject getGlobals( Scope s ){ if( s == null ) throw new RuntimeException("can't construct globals for null"); Scope pyglobals = s.child( "scope to hold python builtins" ); PyObject globals = new PyJSScopeWrapper( pyglobals , false ); Scope tl = pyglobals.getTLPreferred(); pyglobals.setGlobal( true ); __builtin__.fillWithBuiltins( globals ); globals.invoke( "update", PySystemState.builtins ); pyglobals.setGlobal( false ); return globals; } public static JSFunction extractLambda( final String source ){ final PyCode code = (PyCode)(Py.compile( new ByteArrayInputStream( source.getBytes() ) , "anon" , "exec" ) ); if ( _extractGlobals == null ) _extractGlobals = Scope.newGlobal(); Scope s = _extractGlobals.child(); s.setGlobal( true ); PyObject globals = new PyJSScopeWrapper( s , false ); PyModule module = new PyModule( "__main__" , globals ); PyObject locals = module.__dict__; Set<String> before = new HashSet<String>( s.keySet() ); Py.runCode( code, locals, globals ); Set<String> added = new HashSet<String>( s.keySet() ); added.removeAll( before ); JSPyObjectWrapper theFunc = null; for ( String n : added ){ if ( s.get( n ) == null ) continue; Object foo = s.get( n ); if ( ! ( foo instanceof JSPyObjectWrapper ) ) continue; JSPyObjectWrapper p = (JSPyObjectWrapper)foo; if ( ! p.isCallable() ) continue; if ( p.getPyCode() == null ) continue; theFunc = p; } return new JSPyObjectWrapper( (PyFunction)(theFunc.getContained()) , true ); } /** * Get a sensible site-specific state for either the given app * context or the given scope. * * Given a Scope, get the Python site-specific state for that scope. * If one does not exist, create one with the given AppContext and Scope. * If the Scope is null, it will be obtained from the AppContext. * * The Scope will store the Python state, so if possible make it an * AppContext (or suitably long-lived) scope. * * @return an already-existing SiteSystemState for the given site * or a new one if needed */ public static SiteSystemState getSiteSystemState( AppContext ac , Scope s ){ if( ac == null && s == null ){ throw new RuntimeException( "can't get site-specific state for null site with no context" ); } if( s == null ){ // but ac != null, or we'd throw above s = ac.getScope(); } Object __python__ = s.get( "__python__" ); if( __python__ != null && __python__ instanceof SiteSystemState ){ return (SiteSystemState)__python__; } SiteSystemState state = new SiteSystemState( ac , getGlobals( s ) , s ); if( D ) System.out.println("Making a new PySystemState "+ __python__ + " in " + s + " " + __builtin__.id( state.getPyState() )); s.putExplicit( "__python__" , state ); if( _rmap == null ){ _rmap = new HashMap<PySystemState, SiteSystemState>(); } _rmap.put( state.getPyState(), state ); return state; } /** * Get the already-existing SiteSystemState that wraps the given * PySystemState. * * This assumes you've already passed through the other * getSiteSystemState code path at some point and are returning a * PySystemState wrapped by a SiteSystemState. */ public static SiteSystemState getSiteSystemState( PySystemState py ){ return _rmap.get( py ); } public static long size( PyObject o , IdentitySet seen ){ return _size( o , seen ); } public static long _size( PyObject o , IdentitySet seen ){ // PyObject: private PyType objtype // PyInteger: private int value if ( o instanceof PyBoolean || o instanceof PyInteger ) return JSObjectSize.OBJ_OVERHEAD + 8; // PySequence // public int gListAllocatedStatus // PyString // transient int cached_hashcode // transient boolean interned if ( o instanceof PyString ){ PyString s = (PyString)o; return JSObjectSize.OBJ_OVERHEAD + (long)(s.toString().length() * 2) + 12; } // PyList // PySequenceList: protected PyObjectList list // PyObjectList: PyObjectArray array // PyObjectArray: // protected int capacity // protected int size // protected int modCountIncr // PySequence: public int gListAllocatedStatus if( o instanceof PyList ){ PyList l = (PyList)o; int n = l.size(); long size = 0; for( int i = 0; i < n; ++i){ PyObject foo = l.pyget(i); size += JSObjectSize.size( foo, seen ); } return size; } // PyDictionary: protected final ConcurrentMap table if( o instanceof PyDictionary ){ long temp = 0; temp += 32; // sizeof ConcurrentMap? temp += JSObjectSize.size( ((PyDictionary)o).keys() , seen ); temp += JSObjectSize.size( ((PyDictionary)o).values() , seen ); return temp; } String blah = o.getClass().toString(); if ( ! _seenClasses.contains( blah ) ){ System.out.println("Python bridge couldn't figure out size of " + blah); _seenClasses.add( blah ); } return 0; } /** * Exposes a Java type to Jython using the ExposedTypeProcessor. * * The alternative is to use PyType.fromClass(), which seems to be more * for "ordinary" Java classes. */ public static PyType exposeClass( Class c ){ String fileName = c.getName().replaceAll( "\\.", "/" ) + ".class"; try { ExposedTypeProcessor etp = new ExposedTypeProcessor( c.getClassLoader() .getResourceAsStream( fileName )); TypeBuilder t = etp.getTypeExposer().makeBuilder(); PyType.addBuilder( c, t ); } catch( IOException e ){ throw new RuntimeException( "Couldn't expose " + c.getName() ); } return PyType.fromClass( c ); } private static Scope _extractGlobals; private static Map<PySystemState, SiteSystemState> _rmap; private static Set<String> _seenClasses = Collections.synchronizedSet( new HashSet<String>() ); }
true
true
public static Object toJS( Object p ){ if( D ) System.out.println( "toJS " + p + " " + p.getClass()); if ( p == null || p instanceof PyNone ) return null; if ( p instanceof JSObject || p instanceof JSString || p instanceof ed.log.Level || p instanceof Number ) return p; if ( p instanceof String ) return new JSString( p.toString() ); if ( p instanceof PyJSStringWrapper ) p = ((PyJSStringWrapper)p)._p; if ( p instanceof PyJSObjectWrapper ){ if( D ) System.out.println( "unwrapping " + p ); return ((PyJSObjectWrapper)p)._js; } if ( p instanceof PyJSLogLevelWrapper ) return ((PyJSLogLevelWrapper)p)._level; if ( p instanceof PyJSArrayWrapper ) return ((PyJSArrayWrapper)p)._js; if ( p instanceof PyBoolean ) return ((PyBoolean)p).getValue() == 1; if ( p instanceof PyInteger ) return ((PyInteger)p).getValue(); if ( p instanceof PyFloat ) return ((PyFloat)p).getValue(); if ( p instanceof PyString ) return new JSString( p.toString() ); if ( p instanceof PyObjectId ) return ((PyObjectId)p)._id; if ( p instanceof PyClass || p instanceof PyType ){ return new JSPyClassWrapper( (PyObject)p ); } if ( p instanceof PySequenceList ){ return new JSPySequenceListWrapper((PySequenceList)p); } // TODO: this doesn't support several of the Python extensions // known things that won't work: // (?iLmsux) // (?P<name>...) // (?P=name) // (?#...) // (?<=...) // (?<!...) // (?(id/name)yes-pattern|no-pattern) // LOCALE, UNICODE and VERBOSE flags // either of MULTILINE or DOTALL will be translated to both MULTILINE and DOTALL // {,n} doesn't work. can be written as {0,n} which will work // other stuff could be broken as well... if (p instanceof PatternObject) { PatternObject re = (PatternObject)p; // all Python re's get the JS global match flag String flags = "g"; if ((re.flags & SRE_STATE.SRE_FLAG_IGNORECASE) > 0) { flags = flags + "i"; } if ((re.flags & SRE_STATE.SRE_FLAG_MULTILINE) > 0 || (re.flags & SRE_STATE.SRE_FLAG_DOTALL) > 0) { flags = flags + "m"; } return new JSRegex(re.pattern.toString(), flags); } // Insufficiently Pythonic? if ( p instanceof PyObjectDerived && ((PyObject)p).getType().fastGetName().equals( "datetime" ) ){ Object cal = ((PyObject)p).__tojava__( Calendar.class ); if( cal != Py.NoConversion ){ return new JSDate( (Calendar)cal ); } } // this needs to be last if ( p instanceof PyObject ) return new JSPyObjectWrapper( (PyObject)p ); throw new RuntimeException( "can't convert [" + p.getClass().getName() + "] from py to js" ); }
public static Object toJS( Object p ){ if( D ) System.out.println( "toJS " + p + " " + p.getClass()); if ( p == null || p instanceof PyNone ) return null; if ( p instanceof JSObject || p instanceof JSString || p instanceof ed.log.Level || p instanceof Number ) return p; if ( p instanceof String ) return new JSString( p.toString() ); if ( p instanceof PyJSStringWrapper ) p = ((PyJSStringWrapper)p)._p; if ( p instanceof PyJSObjectWrapper ){ if( D ) System.out.println( "unwrapping " + p ); return ((PyJSObjectWrapper)p)._js; } if ( p instanceof PyJSLogLevelWrapper ) return ((PyJSLogLevelWrapper)p)._level; if ( p instanceof PyJSArrayWrapper ) return ((PyJSArrayWrapper)p)._js; if ( p instanceof PyBoolean ) return ((PyBoolean)p).getValue() == 1; if ( p instanceof PyInteger ) return ((PyInteger)p).getValue(); if ( p instanceof PyFloat ) return ((PyFloat)p).getValue(); if ( p instanceof PyString ) return new JSString( p.toString() ); if ( p instanceof PyObjectId ) return ((PyObjectId)p)._id; if ( p instanceof PyClass || p instanceof PyType ){ return new JSPyClassWrapper( (PyObject)p ); } if ( p instanceof PySequenceList ){ return new JSPySequenceListWrapper((PySequenceList)p); } // TODO: this doesn't support several of the Python extensions // known things that won't work: // (?iLmsux) // (?P<name>...) // (?P=name) // (?#...) // (?<=...) // (?<!...) // (?(id/name)yes-pattern|no-pattern) // LOCALE, UNICODE and VERBOSE flags // either of MULTILINE or DOTALL will be translated to both MULTILINE and DOTALL // {,n} doesn't work. can be written as {0,n} which will work // other stuff could be broken as well... if (p instanceof PatternObject) { PatternObject re = (PatternObject)p; // all Python re's get the JS global match flag String flags = "g"; if ((re.flags & SRE_STATE.SRE_FLAG_IGNORECASE) > 0) { flags = flags + "i"; } if ((re.flags & SRE_STATE.SRE_FLAG_MULTILINE) > 0 || (re.flags & SRE_STATE.SRE_FLAG_DOTALL) > 0) { flags = flags + "m"; } return new JSRegex(re.pattern.toString(), flags); } // Insufficiently Pythonic? if ( p instanceof PyObjectDerived ){ PyType type = ((PyObject)p).getType(); if( type != null && type.fastGetName() != null ){ String name = type.fastGetName(); if( name != null && name.equals( "datetime" ) ){ Object cal = ((PyObject)p).__tojava__( Calendar.class ); if( cal != Py.NoConversion ){ return new JSDate( (Calendar)cal ); } } } } // this needs to be last if ( p instanceof PyObject ) return new JSPyObjectWrapper( (PyObject)p ); throw new RuntimeException( "can't convert [" + p.getClass().getName() + "] from py to js" ); }
diff --git a/src/main/java/pl/gsobczyk/rtconnector/ui/MainWindow.java b/src/main/java/pl/gsobczyk/rtconnector/ui/MainWindow.java index d9e0338..29220bf 100644 --- a/src/main/java/pl/gsobczyk/rtconnector/ui/MainWindow.java +++ b/src/main/java/pl/gsobczyk/rtconnector/ui/MainWindow.java @@ -1,249 +1,249 @@ package pl.gsobczyk.rtconnector.ui; import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.math.BigDecimal; import javax.annotation.PostConstruct; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @Component public class MainWindow { @Autowired private ExitAction exitAction; @Autowired private ReportAction reportAction; @Autowired @Qualifier("tableHolder") private ComponentHolder<JTable> tableHolder; @Autowired @Qualifier("comboBoxHolder") private ComponentHolder<JComboBox> comboBoxHolder; @Autowired @Qualifier("commentHolder") private ComponentHolder<JTextField> txtCommentHolder; private JFrame frmRtConnector; private JPanel panel; private JScrollPane scrollPane; private JButton btnClean; private JComboBox comboBox; private JTable table; private JTextField txtComment; private JButton addButton; private JButton removeButton; /** * @wbp.parser.entryPoint */ @PostConstruct public void postConstruct() { comboBox=comboBoxHolder.get(); table=tableHolder.get(); txtComment=txtCommentHolder.get(); initialize(); EventQueue.invokeLater(new Runnable() { public void run() { try { frmRtConnector.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Initialize the contents of the frame. */ private void initialize() { frmRtConnector = new JFrame(); frmRtConnector.setTitle(Messages.getString("MainWindow.title")); //$NON-NLS-1$ frmRtConnector.setBounds(100, 100, 650, 300); frmRtConnector.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmRtConnector.addWindowListener(exitAction); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 0}; gridBagLayout.rowHeights = new int[]{0, 0}; gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE}; frmRtConnector.getContentPane().setLayout(gridBagLayout); panel = new JPanel(); panel.setBorder(new EmptyBorder(7, 7, 7, 7)); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 0; gbc_panel.gridy = 0; frmRtConnector.getContentPane().add(panel, gbc_panel); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[]{0, 0, 0, 0}; gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0}; gbl_panel.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_panel.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panel.setLayout(gbl_panel); scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridheight = 5; gbc_scrollPane.insets = new Insets(0, 0, 5, 5); gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 0; panel.add(scrollPane, gbc_scrollPane); scrollPane.setViewportView(table); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); createEmptyDataModel(table); table.addKeyListener(new ClipboardKeyAdapter(table)); comboBox.setModel(new DefaultComboBoxModel(TimeUnit.values())); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.gridx = 1; gbc_comboBox.gridy = 3; gbc_comboBox.gridwidth = 2; panel.add(comboBox, gbc_comboBox); addButton = new JButton(Messages.getString("MainWindow.addRow")); //$NON-NLS-1$ addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[]{null, null}); } }); GridBagConstraints gbc_addButton = new GridBagConstraints(); gbc_addButton.insets = new Insets(0, 0, 5, 5); gbc_addButton.gridx = 1; gbc_addButton.gridy = 0; panel.add(addButton, gbc_addButton); removeButton = new JButton(Messages.getString("MainWindow.removeRow")); //$NON-NLS-1$ removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); int row = table.getSelectedRow(); if (row<0){ row = table.getRowCount()-1; } model.removeRow(row); int newSelectedRow = Math.min(row, table.getRowCount()-1); table.setRowSelectionInterval(newSelectedRow, newSelectedRow); } }); GridBagConstraints gbc_removeButton = new GridBagConstraints(); gbc_removeButton.insets = new Insets(0, 0, 5, 0); gbc_removeButton.gridx = 2; gbc_removeButton.gridy = 0; panel.add(removeButton, gbc_removeButton); btnClean = new JButton(Messages.getString("MainWindow.clean")); //$NON-NLS-1$ btnClean.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createEmptyDataModel(table); } }); GridBagConstraints gbc_btnClean = new GridBagConstraints(); gbc_btnClean.gridwidth = 2; gbc_btnClean.fill = GridBagConstraints.HORIZONTAL; gbc_btnClean.anchor = GridBagConstraints.WEST; gbc_btnClean.insets = new Insets(0, 0, 5, 0); gbc_btnClean.gridx = 1; gbc_btnClean.gridy = 1; panel.add(btnClean, gbc_btnClean); JButton btnReport = new JButton(Messages.getString("MainWindow.report")); //$NON-NLS-1$ GridBagConstraints gbc_btnReport = new GridBagConstraints(); gbc_btnReport.gridwidth = 2; gbc_btnReport.fill = GridBagConstraints.HORIZONTAL; gbc_btnReport.anchor = GridBagConstraints.WEST; gbc_btnReport.insets = new Insets(0, 0, 5, 0); gbc_btnReport.gridx = 1; gbc_btnReport.gridy = 4; panel.add(btnReport, gbc_btnReport); JButton btnExit = new JButton(Messages.getString("MainWindow.exit")); //$NON-NLS-1$ btnExit.addActionListener(exitAction); txtComment.setText(Messages.getString("MainWindow.txtComment.text")); //$NON-NLS-1$ GridBagConstraints gbc_txtComment = new GridBagConstraints(); gbc_txtComment.insets = new Insets(0, 0, 0, 5); gbc_txtComment.fill = GridBagConstraints.HORIZONTAL; gbc_txtComment.gridx = 0; - gbc_txtComment.gridy = 4; + gbc_txtComment.gridy = 5; panel.add(txtComment, gbc_txtComment); txtComment.setColumns(10); GridBagConstraints gbc_btnExit = new GridBagConstraints(); gbc_btnExit.gridwidth = 2; gbc_btnExit.fill = GridBagConstraints.HORIZONTAL; gbc_btnExit.anchor = GridBagConstraints.WEST; gbc_btnExit.gridx = 1; gbc_btnExit.gridy = 5; panel.add(btnExit, gbc_btnExit); btnReport.addActionListener(reportAction); } public DefaultTableModel createEmptyDataModel(final JTable table) { DefaultTableModel model = new DefaultTableModel( new Object[][] {{null, null}}, new String[] { Messages.getString("MainWindow.ticketColumn"), Messages.getString("MainWindow.timeColumn") //$NON-NLS-1$ //$NON-NLS-2$ } ){ private static final long serialVersionUID = 2214700486786076489L; Class<?>[] columnTypes = new Class[] { String.class, BigDecimal.class }; public Class<?> getColumnClass(int columnIndex) { return columnTypes[columnIndex]; }; }; TableModelListener listener = new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); int rowsCount = table.getRowCount(); boolean add = false; if (rowsCount==0){ add=true; } else { String ticket = (String) model.getValueAt(rowsCount-1, 0); BigDecimal value = (BigDecimal) model.getValueAt(rowsCount-1, 1); if (StringUtils.hasText(ticket) || value!=null){ add = true; } } if (add){ model.addRow(new Object[]{null, null}); } } }; model.addTableModelListener(listener); table.setModel(model); table.getColumnModel().getColumn(0).setPreferredWidth(550); table.getColumnModel().getColumn(1).setPreferredWidth(70); return model; } }
true
true
private void initialize() { frmRtConnector = new JFrame(); frmRtConnector.setTitle(Messages.getString("MainWindow.title")); //$NON-NLS-1$ frmRtConnector.setBounds(100, 100, 650, 300); frmRtConnector.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmRtConnector.addWindowListener(exitAction); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 0}; gridBagLayout.rowHeights = new int[]{0, 0}; gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE}; frmRtConnector.getContentPane().setLayout(gridBagLayout); panel = new JPanel(); panel.setBorder(new EmptyBorder(7, 7, 7, 7)); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 0; gbc_panel.gridy = 0; frmRtConnector.getContentPane().add(panel, gbc_panel); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[]{0, 0, 0, 0}; gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0}; gbl_panel.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_panel.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panel.setLayout(gbl_panel); scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridheight = 5; gbc_scrollPane.insets = new Insets(0, 0, 5, 5); gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 0; panel.add(scrollPane, gbc_scrollPane); scrollPane.setViewportView(table); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); createEmptyDataModel(table); table.addKeyListener(new ClipboardKeyAdapter(table)); comboBox.setModel(new DefaultComboBoxModel(TimeUnit.values())); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.gridx = 1; gbc_comboBox.gridy = 3; gbc_comboBox.gridwidth = 2; panel.add(comboBox, gbc_comboBox); addButton = new JButton(Messages.getString("MainWindow.addRow")); //$NON-NLS-1$ addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[]{null, null}); } }); GridBagConstraints gbc_addButton = new GridBagConstraints(); gbc_addButton.insets = new Insets(0, 0, 5, 5); gbc_addButton.gridx = 1; gbc_addButton.gridy = 0; panel.add(addButton, gbc_addButton); removeButton = new JButton(Messages.getString("MainWindow.removeRow")); //$NON-NLS-1$ removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); int row = table.getSelectedRow(); if (row<0){ row = table.getRowCount()-1; } model.removeRow(row); int newSelectedRow = Math.min(row, table.getRowCount()-1); table.setRowSelectionInterval(newSelectedRow, newSelectedRow); } }); GridBagConstraints gbc_removeButton = new GridBagConstraints(); gbc_removeButton.insets = new Insets(0, 0, 5, 0); gbc_removeButton.gridx = 2; gbc_removeButton.gridy = 0; panel.add(removeButton, gbc_removeButton); btnClean = new JButton(Messages.getString("MainWindow.clean")); //$NON-NLS-1$ btnClean.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createEmptyDataModel(table); } }); GridBagConstraints gbc_btnClean = new GridBagConstraints(); gbc_btnClean.gridwidth = 2; gbc_btnClean.fill = GridBagConstraints.HORIZONTAL; gbc_btnClean.anchor = GridBagConstraints.WEST; gbc_btnClean.insets = new Insets(0, 0, 5, 0); gbc_btnClean.gridx = 1; gbc_btnClean.gridy = 1; panel.add(btnClean, gbc_btnClean); JButton btnReport = new JButton(Messages.getString("MainWindow.report")); //$NON-NLS-1$ GridBagConstraints gbc_btnReport = new GridBagConstraints(); gbc_btnReport.gridwidth = 2; gbc_btnReport.fill = GridBagConstraints.HORIZONTAL; gbc_btnReport.anchor = GridBagConstraints.WEST; gbc_btnReport.insets = new Insets(0, 0, 5, 0); gbc_btnReport.gridx = 1; gbc_btnReport.gridy = 4; panel.add(btnReport, gbc_btnReport); JButton btnExit = new JButton(Messages.getString("MainWindow.exit")); //$NON-NLS-1$ btnExit.addActionListener(exitAction); txtComment.setText(Messages.getString("MainWindow.txtComment.text")); //$NON-NLS-1$ GridBagConstraints gbc_txtComment = new GridBagConstraints(); gbc_txtComment.insets = new Insets(0, 0, 0, 5); gbc_txtComment.fill = GridBagConstraints.HORIZONTAL; gbc_txtComment.gridx = 0; gbc_txtComment.gridy = 4; panel.add(txtComment, gbc_txtComment); txtComment.setColumns(10); GridBagConstraints gbc_btnExit = new GridBagConstraints(); gbc_btnExit.gridwidth = 2; gbc_btnExit.fill = GridBagConstraints.HORIZONTAL; gbc_btnExit.anchor = GridBagConstraints.WEST; gbc_btnExit.gridx = 1; gbc_btnExit.gridy = 5; panel.add(btnExit, gbc_btnExit); btnReport.addActionListener(reportAction); }
private void initialize() { frmRtConnector = new JFrame(); frmRtConnector.setTitle(Messages.getString("MainWindow.title")); //$NON-NLS-1$ frmRtConnector.setBounds(100, 100, 650, 300); frmRtConnector.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmRtConnector.addWindowListener(exitAction); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 0}; gridBagLayout.rowHeights = new int[]{0, 0}; gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gridBagLayout.rowWeights = new double[]{1.0, Double.MIN_VALUE}; frmRtConnector.getContentPane().setLayout(gridBagLayout); panel = new JPanel(); panel.setBorder(new EmptyBorder(7, 7, 7, 7)); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 0; gbc_panel.gridy = 0; frmRtConnector.getContentPane().add(panel, gbc_panel); GridBagLayout gbl_panel = new GridBagLayout(); gbl_panel.columnWidths = new int[]{0, 0, 0, 0}; gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0}; gbl_panel.columnWeights = new double[]{1.0, 0.0, 0.0, Double.MIN_VALUE}; gbl_panel.rowWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; panel.setLayout(gbl_panel); scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridheight = 5; gbc_scrollPane.insets = new Insets(0, 0, 5, 5); gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 0; panel.add(scrollPane, gbc_scrollPane); scrollPane.setViewportView(table); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); createEmptyDataModel(table); table.addKeyListener(new ClipboardKeyAdapter(table)); comboBox.setModel(new DefaultComboBoxModel(TimeUnit.values())); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.insets = new Insets(0, 0, 5, 0); gbc_comboBox.gridx = 1; gbc_comboBox.gridy = 3; gbc_comboBox.gridwidth = 2; panel.add(comboBox, gbc_comboBox); addButton = new JButton(Messages.getString("MainWindow.addRow")); //$NON-NLS-1$ addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[]{null, null}); } }); GridBagConstraints gbc_addButton = new GridBagConstraints(); gbc_addButton.insets = new Insets(0, 0, 5, 5); gbc_addButton.gridx = 1; gbc_addButton.gridy = 0; panel.add(addButton, gbc_addButton); removeButton = new JButton(Messages.getString("MainWindow.removeRow")); //$NON-NLS-1$ removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel model = (DefaultTableModel) table.getModel(); int row = table.getSelectedRow(); if (row<0){ row = table.getRowCount()-1; } model.removeRow(row); int newSelectedRow = Math.min(row, table.getRowCount()-1); table.setRowSelectionInterval(newSelectedRow, newSelectedRow); } }); GridBagConstraints gbc_removeButton = new GridBagConstraints(); gbc_removeButton.insets = new Insets(0, 0, 5, 0); gbc_removeButton.gridx = 2; gbc_removeButton.gridy = 0; panel.add(removeButton, gbc_removeButton); btnClean = new JButton(Messages.getString("MainWindow.clean")); //$NON-NLS-1$ btnClean.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createEmptyDataModel(table); } }); GridBagConstraints gbc_btnClean = new GridBagConstraints(); gbc_btnClean.gridwidth = 2; gbc_btnClean.fill = GridBagConstraints.HORIZONTAL; gbc_btnClean.anchor = GridBagConstraints.WEST; gbc_btnClean.insets = new Insets(0, 0, 5, 0); gbc_btnClean.gridx = 1; gbc_btnClean.gridy = 1; panel.add(btnClean, gbc_btnClean); JButton btnReport = new JButton(Messages.getString("MainWindow.report")); //$NON-NLS-1$ GridBagConstraints gbc_btnReport = new GridBagConstraints(); gbc_btnReport.gridwidth = 2; gbc_btnReport.fill = GridBagConstraints.HORIZONTAL; gbc_btnReport.anchor = GridBagConstraints.WEST; gbc_btnReport.insets = new Insets(0, 0, 5, 0); gbc_btnReport.gridx = 1; gbc_btnReport.gridy = 4; panel.add(btnReport, gbc_btnReport); JButton btnExit = new JButton(Messages.getString("MainWindow.exit")); //$NON-NLS-1$ btnExit.addActionListener(exitAction); txtComment.setText(Messages.getString("MainWindow.txtComment.text")); //$NON-NLS-1$ GridBagConstraints gbc_txtComment = new GridBagConstraints(); gbc_txtComment.insets = new Insets(0, 0, 0, 5); gbc_txtComment.fill = GridBagConstraints.HORIZONTAL; gbc_txtComment.gridx = 0; gbc_txtComment.gridy = 5; panel.add(txtComment, gbc_txtComment); txtComment.setColumns(10); GridBagConstraints gbc_btnExit = new GridBagConstraints(); gbc_btnExit.gridwidth = 2; gbc_btnExit.fill = GridBagConstraints.HORIZONTAL; gbc_btnExit.anchor = GridBagConstraints.WEST; gbc_btnExit.gridx = 1; gbc_btnExit.gridy = 5; panel.add(btnExit, gbc_btnExit); btnReport.addActionListener(reportAction); }
diff --git a/src/paulscode/android/mupen64plusae/persistent/AppData.java b/src/paulscode/android/mupen64plusae/persistent/AppData.java index 26ff803f..cfdb4a07 100644 --- a/src/paulscode/android/mupen64plusae/persistent/AppData.java +++ b/src/paulscode/android/mupen64plusae/persistent/AppData.java @@ -1,511 +1,491 @@ /** * Mupen64PlusAE, an N64 emulator for the Android platform * * Copyright (C) 2013 Paul Lamb * * This file is part of Mupen64PlusAE. * * Mupen64PlusAE 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. * * Mupen64PlusAE 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 Mupen64PlusAE. If * not, see <http://www.gnu.org/licenses/>. * * Authors: Paul Lamb, littleguy77 */ package paulscode.android.mupen64plusae.persistent; import java.io.File; import java.util.Locale; import org.acra.ACRA; import org.acra.ErrorReporter; import paulscode.android.mupen64plusae.util.DeviceUtil; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Environment; import android.util.Log; /** * A convenience class for retrieving and persisting data defined internally by the application. * <p> * <b>Developers:</b> Use this class to persist small bits of application data across sessions and * reboots. (For large data sets, consider using databases or files.) To add a new variable to * persistent storage, use the following pattern: * * <pre> * {@code * // Define keys for each variable * private static final String KEY_FOO = "foo"; * private static final String KEY_BAR = "bar"; * * // Define default values for each variable * private static final float DEFAULT_FOO = 3.14f; * private static final boolean DEFAULT_BAR = false; * * // Create getters * public float getFoo() * { * return mPreferences.getFloat( KEY_FOO, DEFAULT_FOO ); * } * * public boolean getBar() * { * return mPreferences.getBoolean( KEY_BAR, DEFAULT_BAR ); * } * * // Create setters * public void setFoo( float value ) * { * mPreferences.edit().putFloat( KEY_FOO, value ).commit(); * } * * public void setBar( boolean value ) * { * mPreferences.edit().putBoolean( KEY_BAR, value ).commit(); * } * </pre> */ public class AppData { /** True if device is running Gingerbread or later (9 - Android 2.3.x) */ public static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; /** True if device is running Honeycomb or later (11 - Android 3.0.x) */ public static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; /** True if device is running Honeycomb MR1 or later (12 - Android 3.1.x) */ public static final boolean IS_HONEYCOMB_MR1 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1; /** True if device is running Ice Cream Sandwich or later (14 - Android 4.0.x) */ public static final boolean IS_ICE_CREAM_SANDWICH = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; /** True if device is running Jellybean or later (16 - Android 4.1.x) */ public static final boolean IS_JELLY_BEAN = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; /** Debug option: download data to SD card (default true). */ public static final boolean DOWNLOAD_TO_SDCARD = true; /** The hardware info, refreshed at the beginning of every session. */ public final HardwareInfo hardwareInfo; /** The package name. */ public final String packageName; /** The app version string. */ public final String appVersion; /** The app version code. */ public final int appVersionCode; /** The user storage directory (typically the external storage directory). */ public final String storageDir; /** The directory for storing internal app data. */ public final String dataDir; /** The directory where app data was stored in the old version. */ public final String oldDataDir; /** The directory containing the native Mupen64Plus libraries. */ public final String libsDir; /** The directory containing all touchscreen layout folders. */ public final String touchscreenLayoutsDir; /** The directory containing all Xperia Play layout folders. */ public final String touchpadLayoutsDir; /** The directory containing all fonts. */ public final String fontsDir; /** The name of the mupen64 core configuration file. */ public final String mupen64plus_cfg; /** The name of the gles2n64 configuration file. */ public final String gles2n64_conf; /** The name of the error log file. */ public final String error_log; /** The object used to persist the settings. */ private final SharedPreferences mPreferences; // Shared preferences keys private static final String KEY_ASSET_VERSION = "assetVersion"; private static final String KEY_LAST_APP_VERSION_CODE = "lastAppVersion"; private static final String KEY_LAST_SLOT = "lastSlot"; private static final String KEY_LAST_ROM = "lastRom"; private static final String KEY_LAST_CRC = "lastCrc"; // ... add more as needed // Shared preferences default values private static final int DEFAULT_ASSET_VERSION = 0; private static final int DEFAULT_LAST_APP_VERSION_CODE = 0; private static final int DEFAULT_LAST_SLOT = 0; private static final String DEFAULT_LAST_ROM = ""; private static final String DEFAULT_LAST_CRC = ""; // ... add more as needed /** * Instantiates a new object to retrieve and persist app data. * * @param context The application context. */ public AppData( Context context ) { hardwareInfo = new HardwareInfo(); packageName = context.getPackageName(); PackageInfo info; String version = ""; int versionCode = -1; try { info = context.getPackageManager().getPackageInfo( packageName, 0 ); version = info.versionName; versionCode = info.versionCode; } catch( NameNotFoundException e ) { Log.e( "AppData", e.getMessage() ); } appVersion = version; appVersionCode = versionCode; // Directories if( DOWNLOAD_TO_SDCARD ) { storageDir = Environment.getExternalStorageDirectory().getAbsolutePath(); dataDir = storageDir + "/Android/data/" + packageName; } else { storageDir = context.getFilesDir().getAbsolutePath(); dataDir = storageDir; } oldDataDir = storageDir + "/Android/data/trev.android.mupen64plusae"; libsDir = "/data/data/" + packageName + "/lib/"; touchscreenLayoutsDir = dataDir + "/skins/gamepads/"; touchpadLayoutsDir = dataDir + "/skins/touchpads/"; fontsDir = dataDir + "/skins/fonts/"; // Files mupen64plus_cfg = dataDir + "/mupen64plus.cfg"; gles2n64_conf = dataDir + "/data/gles2n64.conf"; error_log = dataDir + "/error.log"; // Preference object for persisting app data String appDataFilename = packageName + "_appdata"; mPreferences = context.getSharedPreferences( appDataFilename, Context.MODE_PRIVATE ); // Record some info in the crash reporter ErrorReporter reporter = ACRA.getErrorReporter(); reporter.putCustomData( "CPU Features", hardwareInfo.features ); reporter.putCustomData( "CPU Hardware", hardwareInfo.hardware ); reporter.putCustomData( "CPU Processor", hardwareInfo.processor ); reportMultilineText( reporter, "Axis Report", DeviceUtil.getAxisInfo() ); reportMultilineText( reporter, "CPU Report", DeviceUtil.getCpuInfo() ); reportMultilineText( reporter, "HID Report", DeviceUtil.getPeripheralInfo() ); } public static void reportMultilineText( ErrorReporter reporter, String key, String multilineText ) { final String[] lines = multilineText.split( "\n" ); int numLines = lines.length; int padding = 1; while( numLines > 9 ) { numLines /= 10; padding++; } final String template = "%s.%0" + padding + "d"; for( int i = 0; i < lines.length; i++ ) { reporter.putCustomData( String.format( template, key, i ), lines[i].trim() ); } } /** * Checks if the storage directory is accessible. * * @return True, if the storage directory is accessible. */ public boolean isSdCardAccessible() { return ( new File( storageDir ) ).exists(); } /** * Gets the asset version. * * @return The asset version. */ public int getAssetVersion() { return getInt( KEY_ASSET_VERSION, DEFAULT_ASSET_VERSION ); } /** * Gets the version code when the user last ran the app * * @return The app version. */ public int getLastAppVersionCode() { return getInt( KEY_LAST_APP_VERSION_CODE, DEFAULT_LAST_APP_VERSION_CODE ); } /** * Gets the last savegame slot. * * @return The last slot. */ public int getLastSlot() { return getInt( KEY_LAST_SLOT, DEFAULT_LAST_SLOT ); } /** * Gets the last ROM that the CRC was computed for. * * @return The last ROM. */ public String getLastRom() { return getString( KEY_LAST_ROM, DEFAULT_LAST_ROM ); } /** * Gets the last CRC computed. * * @return The last CRC. */ public String getLastCrc() { return getString( KEY_LAST_CRC, DEFAULT_LAST_CRC ); } /** * Persists the asset version. * * @param value The asset version. */ public void putAssetVersion( int value ) { putInt( KEY_ASSET_VERSION, value ); } /** * Persists the version code when the user last ran the app. * * @param value The app version code. */ public void putLastAppVersionCode( int value ) { putInt( KEY_LAST_APP_VERSION_CODE, value ); } /** * Persists the last savegame slot. * * @param value The last slot. */ public void putLastSlot( int value ) { putInt( KEY_LAST_SLOT, value ); } /** * Persists the last ROM that the CRC was computed for. * * @param value The last ROM. */ public void putLastRom( String value ) { putString( KEY_LAST_ROM, value ); } /** * Persists the last CRC computed. * * @param value The last CRC. */ public void putLastCrc( String value ) { putString( KEY_LAST_CRC, value ); } private int getInt( String key, int defaultValue ) { return mPreferences.getInt( key, defaultValue ); } private String getString( String key, String defaultValue ) { return mPreferences.getString( key, defaultValue ); } private void putInt( String key, int value ) { mPreferences.edit().putInt( key, value ).commit(); } private void putString( String key, String value ) { mPreferences.edit().putString( key, value ).commit(); } /** * Small class that summarizes the info provided by /proc/cpuinfo. * <p> * <b>Developers:</b> Hardware types are used to apply device-specific fixes for missing shadows * and decals, and must match the #defines in OpenGL.cpp. */ public static class HardwareInfo { /** Unknown hardware configuration. */ public static final int HARDWARE_TYPE_UNKNOWN = 0; /** OMAP-based hardware. */ public static final int HARDWARE_TYPE_OMAP = 1; /** OMAP-based hardware, type #2. */ public static final int HARDWARE_TYPE_OMAP_2 = 2; /** QualComm-based hardware. */ public static final int HARDWARE_TYPE_QUALCOMM = 3; /** IMAP-based hardware. */ public static final int HARDWARE_TYPE_IMAP = 4; /** Tegra-based hardware. */ public static final int HARDWARE_TYPE_TEGRA = 5; /** Default hardware type */ private static final int DEFAULT_HARDWARE_TYPE = HARDWARE_TYPE_UNKNOWN; public final String hardware; public final String processor; public final String features; public final int hardwareType; public final boolean isXperiaPlay; public final boolean isOUYA; public HardwareInfo() { // Identify the hardware, features, and processor strings { // Temporaries since we can't assign the final fields this way String _hardware = ""; String _features = ""; String _processor = ""; // Parse a long string of information from the operating system String hwString = DeviceUtil.getCpuInfo().toLowerCase( Locale.US ); String[] lines = hwString.split( "\\r\\n|\\n|\\r" ); for( String line : lines ) { String[] splitLine = line.split( ":" ); if( splitLine.length == 2 ) { String arg = splitLine[0].trim(); String val = splitLine[1].trim(); if( arg.equals( "processor" ) && val.length() > 1 ) _processor = val; else if( arg.equals( "features" ) ) _features = val; else if( arg.equals( "hardware" ) ) _hardware = val; } } // Assign the final fields hardware = _hardware; processor = _processor; features = _features; } // Identify the hardware type from the substrings //@formatter:off if( ( hardware.contains( "mapphone" ) && !processor.contains( "rev 3" ) ) || hardware.contains( "smdkv" ) || hardware.contains( "herring" ) || hardware.contains( "aries" ) || hardware.contains( "expresso10" ) || ( hardware.contains( "tuna" ) && !IS_JELLY_BEAN ) ) hardwareType = HARDWARE_TYPE_OMAP; else if( hardware.contains( "tuna" ) || hardware.contains( "mapphone" ) || hardware.contains( "amlogic meson3" ) || hardware.contains( "rk30board" ) || hardware.contains( "smdk4210" ) || hardware.contains( "riogrande" ) || hardware.contains( "cardhu" ) ) hardwareType = HARDWARE_TYPE_OMAP_2; else if( hardware.contains( "liberty" ) || hardware.contains( "gt-s5830" ) || hardware.contains( "zeus" ) ) hardwareType = HARDWARE_TYPE_QUALCOMM; else if( hardware.contains( "imap" ) ) hardwareType = HARDWARE_TYPE_IMAP; else if( hardware.contains( "tegra 2" ) || hardware.contains( "grouper" ) || hardware.contains( "meson-m1" ) || hardware.contains( "smdkc" ) || hardware.contains( "smdk4x12" ) || hardware.contains( "sun6i" ) || ( features != null && features.contains( "vfpv3d16" ) ) ) hardwareType = HARDWARE_TYPE_TEGRA; else hardwareType = DEFAULT_HARDWARE_TYPE; //@formatter:on // Identify whether this is an Xperia PLAY isXperiaPlay = hardware.contains( "zeus" ); // Identify whether this is an OUYA - boolean hardwareOUYA = false; - // Check for ICS, just in case OuyaFacade.isRunningOnOUYAHardware does anything API-specific - if( IS_ICE_CREAM_SANDWICH ) - { - // Retrieve the result from OuyaFacade.isRunningOnOUYAHardware - try - { - Class<?> OuyaFacadeClass = Class.forName( "tv.ouya.console.api.OuyaFacade" ); - hardwareOUYA = ( OuyaFacadeClass.getMethod( "isRunningOnOUYAHardware", OuyaFacadeClass ).invoke( null ).toString().equals( "true" ) ); - } - // Don't care if it fails (must not be OUYA) - catch( ClassNotFoundException cnfe ) - {} - catch( NoSuchMethodException nsme ) - {} - catch( IllegalAccessException iae ) - {} - catch( java.lang.reflect.InvocationTargetException ite ) - {} - } - isOUYA = hardwareOUYA; + isOUYA = IS_ICE_CREAM_SANDWICH && tv.ouya.console.api.OuyaFacade.getInstance().isRunningOnOUYAHardware(); // TODO: Would be useful to also check for OUYA framework, for determining when to show OUYA storefront components } } }
true
true
public HardwareInfo() { // Identify the hardware, features, and processor strings { // Temporaries since we can't assign the final fields this way String _hardware = ""; String _features = ""; String _processor = ""; // Parse a long string of information from the operating system String hwString = DeviceUtil.getCpuInfo().toLowerCase( Locale.US ); String[] lines = hwString.split( "\\r\\n|\\n|\\r" ); for( String line : lines ) { String[] splitLine = line.split( ":" ); if( splitLine.length == 2 ) { String arg = splitLine[0].trim(); String val = splitLine[1].trim(); if( arg.equals( "processor" ) && val.length() > 1 ) _processor = val; else if( arg.equals( "features" ) ) _features = val; else if( arg.equals( "hardware" ) ) _hardware = val; } } // Assign the final fields hardware = _hardware; processor = _processor; features = _features; } // Identify the hardware type from the substrings //@formatter:off if( ( hardware.contains( "mapphone" ) && !processor.contains( "rev 3" ) ) || hardware.contains( "smdkv" ) || hardware.contains( "herring" ) || hardware.contains( "aries" ) || hardware.contains( "expresso10" ) || ( hardware.contains( "tuna" ) && !IS_JELLY_BEAN ) ) hardwareType = HARDWARE_TYPE_OMAP; else if( hardware.contains( "tuna" ) || hardware.contains( "mapphone" ) || hardware.contains( "amlogic meson3" ) || hardware.contains( "rk30board" ) || hardware.contains( "smdk4210" ) || hardware.contains( "riogrande" ) || hardware.contains( "cardhu" ) ) hardwareType = HARDWARE_TYPE_OMAP_2; else if( hardware.contains( "liberty" ) || hardware.contains( "gt-s5830" ) || hardware.contains( "zeus" ) ) hardwareType = HARDWARE_TYPE_QUALCOMM; else if( hardware.contains( "imap" ) ) hardwareType = HARDWARE_TYPE_IMAP; else if( hardware.contains( "tegra 2" ) || hardware.contains( "grouper" ) || hardware.contains( "meson-m1" ) || hardware.contains( "smdkc" ) || hardware.contains( "smdk4x12" ) || hardware.contains( "sun6i" ) || ( features != null && features.contains( "vfpv3d16" ) ) ) hardwareType = HARDWARE_TYPE_TEGRA; else hardwareType = DEFAULT_HARDWARE_TYPE; //@formatter:on // Identify whether this is an Xperia PLAY isXperiaPlay = hardware.contains( "zeus" ); // Identify whether this is an OUYA boolean hardwareOUYA = false; // Check for ICS, just in case OuyaFacade.isRunningOnOUYAHardware does anything API-specific if( IS_ICE_CREAM_SANDWICH ) { // Retrieve the result from OuyaFacade.isRunningOnOUYAHardware try { Class<?> OuyaFacadeClass = Class.forName( "tv.ouya.console.api.OuyaFacade" ); hardwareOUYA = ( OuyaFacadeClass.getMethod( "isRunningOnOUYAHardware", OuyaFacadeClass ).invoke( null ).toString().equals( "true" ) ); } // Don't care if it fails (must not be OUYA) catch( ClassNotFoundException cnfe ) {} catch( NoSuchMethodException nsme ) {} catch( IllegalAccessException iae ) {} catch( java.lang.reflect.InvocationTargetException ite ) {} } isOUYA = hardwareOUYA; // TODO: Would be useful to also check for OUYA framework, for determining when to show OUYA storefront components }
public HardwareInfo() { // Identify the hardware, features, and processor strings { // Temporaries since we can't assign the final fields this way String _hardware = ""; String _features = ""; String _processor = ""; // Parse a long string of information from the operating system String hwString = DeviceUtil.getCpuInfo().toLowerCase( Locale.US ); String[] lines = hwString.split( "\\r\\n|\\n|\\r" ); for( String line : lines ) { String[] splitLine = line.split( ":" ); if( splitLine.length == 2 ) { String arg = splitLine[0].trim(); String val = splitLine[1].trim(); if( arg.equals( "processor" ) && val.length() > 1 ) _processor = val; else if( arg.equals( "features" ) ) _features = val; else if( arg.equals( "hardware" ) ) _hardware = val; } } // Assign the final fields hardware = _hardware; processor = _processor; features = _features; } // Identify the hardware type from the substrings //@formatter:off if( ( hardware.contains( "mapphone" ) && !processor.contains( "rev 3" ) ) || hardware.contains( "smdkv" ) || hardware.contains( "herring" ) || hardware.contains( "aries" ) || hardware.contains( "expresso10" ) || ( hardware.contains( "tuna" ) && !IS_JELLY_BEAN ) ) hardwareType = HARDWARE_TYPE_OMAP; else if( hardware.contains( "tuna" ) || hardware.contains( "mapphone" ) || hardware.contains( "amlogic meson3" ) || hardware.contains( "rk30board" ) || hardware.contains( "smdk4210" ) || hardware.contains( "riogrande" ) || hardware.contains( "cardhu" ) ) hardwareType = HARDWARE_TYPE_OMAP_2; else if( hardware.contains( "liberty" ) || hardware.contains( "gt-s5830" ) || hardware.contains( "zeus" ) ) hardwareType = HARDWARE_TYPE_QUALCOMM; else if( hardware.contains( "imap" ) ) hardwareType = HARDWARE_TYPE_IMAP; else if( hardware.contains( "tegra 2" ) || hardware.contains( "grouper" ) || hardware.contains( "meson-m1" ) || hardware.contains( "smdkc" ) || hardware.contains( "smdk4x12" ) || hardware.contains( "sun6i" ) || ( features != null && features.contains( "vfpv3d16" ) ) ) hardwareType = HARDWARE_TYPE_TEGRA; else hardwareType = DEFAULT_HARDWARE_TYPE; //@formatter:on // Identify whether this is an Xperia PLAY isXperiaPlay = hardware.contains( "zeus" ); // Identify whether this is an OUYA isOUYA = IS_ICE_CREAM_SANDWICH && tv.ouya.console.api.OuyaFacade.getInstance().isRunningOnOUYAHardware(); // TODO: Would be useful to also check for OUYA framework, for determining when to show OUYA storefront components }
diff --git a/src/org/mozilla/javascript/TokenStream.java b/src/org/mozilla/javascript/TokenStream.java index e8beda37..172a0876 100644 --- a/src/org/mozilla/javascript/TokenStream.java +++ b/src/org/mozilla/javascript/TokenStream.java @@ -1,1391 +1,1385 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Roger Lawrence * Mike McCabe * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript; import java.io.*; /** * This class implements the JavaScript scanner. * * It is based on the C source files jsscan.c and jsscan.h * in the jsref package. * * @see org.mozilla.javascript.Parser * * @author Mike McCabe * @author Brendan Eich */ public class TokenStream { /* * JSTokenStream flags, mirroring those in jsscan.h. These are used * by the parser to change/check the state of the scanner. */ public final static int TSF_NEWLINES = 0x0001, // tokenize newlines TSF_FUNCTION = 0x0002, // scanning inside function body TSF_RETURN_EXPR = 0x0004, // function has 'return expr;' TSF_RETURN_VOID = 0x0008, // function has 'return;' TSF_REGEXP = 0x0010; // looking for a regular expression /* * For chars - because we need something out-of-range * to check. (And checking EOF by exception is annoying.) * Note distinction from EOF token type! */ private final static int EOF_CHAR = -1; /** * Token types. These values correspond to JSTokenType values in * jsscan.c. */ public final static int // start enum ERROR = -1, // well-known as the only code < EOF EOF = 0, // end of file token - (not EOF_CHAR) EOL = 1, // end of line // Beginning here are interpreter bytecodes. Their values // must not exceed 127. POPV = 2, ENTERWITH = 3, LEAVEWITH = 4, RETURN = 5, GOTO = 6, IFEQ = 7, IFNE = 8, DUP = 9, SETNAME = 10, BITOR = 11, BITXOR = 12, BITAND = 13, EQ = 14, NE = 15, LT = 16, LE = 17, GT = 18, GE = 19, LSH = 20, RSH = 21, URSH = 22, ADD = 23, SUB = 24, MUL = 25, DIV = 26, MOD = 27, BITNOT = 28, NEG = 29, NEW = 30, DELPROP = 31, TYPEOF = 32, NAMEINC = 33, PROPINC = 34, ELEMINC = 35, NAMEDEC = 36, PROPDEC = 37, ELEMDEC = 38, GETPROP = 39, SETPROP = 40, GETELEM = 41, SETELEM = 42, CALL = 43, NAME = 44, NUMBER = 45, STRING = 46, ZERO = 47, ONE = 48, NULL = 49, THIS = 50, FALSE = 51, TRUE = 52, SHEQ = 53, // shallow equality (===) SHNE = 54, // shallow inequality (!==) CLOSURE = 55, OBJECT = 56, POP = 57, POS = 58, VARINC = 59, VARDEC = 60, BINDNAME = 61, THROW = 62, IN = 63, INSTANCEOF = 64, GOSUB = 65, RETSUB = 66, CALLSPECIAL = 67, GETTHIS = 68, NEWTEMP = 69, USETEMP = 70, GETBASE = 71, GETVAR = 72, SETVAR = 73, UNDEFINED = 74, TRY = 75, ENDTRY = 76, NEWSCOPE = 77, TYPEOFNAME = 78, ENUMINIT = 79, ENUMNEXT = 80, GETPROTO = 81, GETPARENT = 82, SETPROTO = 83, SETPARENT = 84, SCOPE = 85, GETSCOPEPARENT = 86, THISFN = 87, JTHROW = 88, // End of interpreter bytecodes SEMI = 89, // semicolon LB = 90, // left and right brackets RB = 91, LC = 92, // left and right curlies (braces) RC = 93, LP = 94, // left and right parentheses RP = 95, COMMA = 96, // comma operator ASSIGN = 97, // assignment ops (= += -= etc.) HOOK = 98, // conditional (?:) COLON = 99, OR = 100, // logical or (||) AND = 101, // logical and (&&) EQOP = 102, // equality ops (== !=) RELOP = 103, // relational ops (< <= > >=) SHOP = 104, // shift ops (<< >> >>>) UNARYOP = 105, // unary prefix operator INC = 106, // increment/decrement (++ --) DEC = 107, DOT = 108, // member operator (.) PRIMARY = 109, // true, false, null, this FUNCTION = 110, // function keyword EXPORT = 111, // export keyword IMPORT = 112, // import keyword IF = 113, // if keyword ELSE = 114, // else keyword SWITCH = 115, // switch keyword CASE = 116, // case keyword DEFAULT = 117, // default keyword WHILE = 118, // while keyword DO = 119, // do keyword FOR = 120, // for keyword BREAK = 121, // break keyword CONTINUE = 122, // continue keyword VAR = 123, // var keyword WITH = 124, // with keyword CATCH = 125, // catch keyword FINALLY = 126, // finally keyword RESERVED = 127, // reserved keywords /** Added by Mike - these are JSOPs in the jsref, but I * don't have them yet in the java implementation... * so they go here. Also whatever I needed. * Most of these go in the 'op' field when returning * more general token types, eg. 'DIV' as the op of 'ASSIGN'. */ NOP = 128, // NOP NOT = 129, // etc. PRE = 130, // for INC, DEC nodes. POST = 131, /** * For JSOPs associated with keywords... * eg. op = THIS; token = PRIMARY */ VOID = 132, /* types used for the parse tree - these never get returned * by the scanner. */ BLOCK = 133, // statement block ARRAYLIT = 134, // array literal OBJLIT = 135, // object literal LABEL = 136, // label TARGET = 137, LOOP = 138, ENUMDONE = 139, EXPRSTMT = 140, PARENT = 141, CONVERT = 142, JSR = 143, NEWLOCAL = 144, USELOCAL = 145, SCRIPT = 146, // top-level node for entire script /** * For the interpreted mode indicating a line number change in icodes. */ LINE = 147, SOURCEFILE = 148, // For debugger BREAKPOINT = 149, // For Interpreter to store shorts and ints inline SHORTNUMBER = 150, INTNUMBER = 151; // end enum /* for mapping int token types to printable strings. * make sure to add 1 to index before using these! */ private static String names[]; private static void checkNames() { if (Context.printTrees && names == null) { String[] a = { "error", "eof", "eol", "popv", "enterwith", "leavewith", "return", "goto", "ifeq", "ifne", "dup", "setname", "bitor", "bitxor", "bitand", "eq", "ne", "lt", "le", "gt", "ge", "lsh", "rsh", "ursh", "add", "sub", "mul", "div", "mod", "bitnot", "neg", "new", "delprop", "typeof", "nameinc", "propinc", "eleminc", "namedec", "propdec", "elemdec", "getprop", "setprop", "getelem", "setelem", "call", "name", "number", "string", "zero", "one", "null", "this", "false", "true", "sheq", "shne", "closure", "object", "pop", "pos", "varinc", "vardec", "bindname", "throw", "in", "instanceof", "gosub", "retsub", "callspecial", "getthis", "newtemp", "usetemp", "getbase", "getvar", "setvar", "undefined", "try", "endtry", "newscope", "typeofname", "enuminit", "enumnext", "getproto", "getparent", "setproto", "setparent", "scope", "getscopeparent", "thisfn", "jthrow", "semi", "lb", "rb", "lc", "rc", "lp", "rp", "comma", "assign", "hook", "colon", "or", "and", "eqop", "relop", "shop", "unaryop", "inc", "dec", "dot", "primary", "function", "export", "import", "if", "else", "switch", "case", "default", "while", "do", "for", "break", "continue", "var", "with", "catch", "finally", "reserved", "nop", "not", "pre", "post", "void", "block", "arraylit", "objlit", "label", "target", "loop", "enumdone", "exprstmt", "parent", "convert", "jsr", "newlocal", "uselocal", "script", "line", "sourcefile", "breakpoint", "shortnumber", "intnumber", }; names = a; } } /* This function uses the cached op, string and number fields in * TokenStream; if getToken has been called since the passed token * was scanned, the op or string printed may be incorrect. */ public String tokenToString(int token) { if (Context.printTrees) { checkNames(); if (token + 1 >= names.length) return null; if (token == UNARYOP || token == ASSIGN || token == PRIMARY || token == EQOP || token == SHOP || token == RELOP) { return names[token + 1] + " " + names[this.op + 1]; } if (token == STRING || token == OBJECT || token == NAME) return names[token + 1] + " `" + this.string + "'"; if (token == NUMBER) return "NUMBER " + this.number; return names[token + 1]; } return ""; } public static String tokenToName(int type) { checkNames(); return names == null ? "" : names[type + 1]; } private int stringToKeyword(String name) { // #string_id_map# // The following assumes that EOF == 0 final int Id_break = BREAK, Id_case = CASE, Id_continue = CONTINUE, Id_default = DEFAULT, Id_delete = DELPROP, Id_do = DO, Id_else = ELSE, Id_export = EXPORT, Id_false = PRIMARY | (FALSE << 8), Id_for = FOR, Id_function = FUNCTION, Id_if = IF, Id_in = RELOP | (IN << 8), Id_new = NEW, Id_null = PRIMARY | (NULL << 8), Id_return = RETURN, Id_switch = SWITCH, Id_this = PRIMARY | (THIS << 8), Id_true = PRIMARY | (TRUE << 8), Id_typeof = UNARYOP | (TYPEOF << 8), Id_var = VAR, Id_void = UNARYOP | (VOID << 8), Id_while = WHILE, Id_with = WITH, // the following are #ifdef RESERVE_JAVA_KEYWORDS in jsscan.c Id_abstract = RESERVED, Id_boolean = RESERVED, Id_byte = RESERVED, Id_catch = CATCH, Id_char = RESERVED, Id_class = RESERVED, Id_const = RESERVED, Id_debugger = RESERVED, Id_double = RESERVED, Id_enum = RESERVED, Id_extends = RESERVED, Id_final = RESERVED, Id_finally = FINALLY, Id_float = RESERVED, Id_goto = RESERVED, Id_implements = RESERVED, Id_import = IMPORT, Id_instanceof = RELOP | (INSTANCEOF << 8), Id_int = RESERVED, Id_interface = RESERVED, Id_long = RESERVED, Id_native = RESERVED, Id_package = RESERVED, Id_private = RESERVED, Id_protected = RESERVED, Id_public = RESERVED, Id_short = RESERVED, Id_static = RESERVED, Id_super = RESERVED, Id_synchronized = RESERVED, Id_throw = THROW, Id_throws = RESERVED, Id_transient = RESERVED, Id_try = TRY, Id_volatile = RESERVED; int id; String s = name; // #generated# Last update: 2001-06-01 17:45:01 CEST L0: { id = 0; String X = null; int c; L: switch (s.length()) { case 2: c=s.charAt(1); if (c=='f') { if (s.charAt(0)=='i') {id=Id_if; break L0;} } else if (c=='n') { if (s.charAt(0)=='i') {id=Id_in; break L0;} } else if (c=='o') { if (s.charAt(0)=='d') {id=Id_do; break L0;} } break L; case 3: switch (s.charAt(0)) { case 'f': if (s.charAt(2)=='r' && s.charAt(1)=='o') {id=Id_for; break L0;} break L; case 'i': if (s.charAt(2)=='t' && s.charAt(1)=='n') {id=Id_int; break L0;} break L; case 'n': if (s.charAt(2)=='w' && s.charAt(1)=='e') {id=Id_new; break L0;} break L; case 't': if (s.charAt(2)=='y' && s.charAt(1)=='r') {id=Id_try; break L0;} break L; case 'v': if (s.charAt(2)=='r' && s.charAt(1)=='a') {id=Id_var; break L0;} break L; } break L; case 4: switch (s.charAt(0)) { case 'b': X="byte";id=Id_byte; break L; case 'c': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='a') {id=Id_case; break L0;} } else if (c=='r') { if (s.charAt(2)=='a' && s.charAt(1)=='h') {id=Id_char; break L0;} } break L; case 'e': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='s' && s.charAt(1)=='l') {id=Id_else; break L0;} } else if (c=='m') { if (s.charAt(2)=='u' && s.charAt(1)=='n') {id=Id_enum; break L0;} } break L; case 'g': X="goto";id=Id_goto; break L; case 'l': X="long";id=Id_long; break L; case 'n': X="null";id=Id_null; break L; case 't': c=s.charAt(3); if (c=='e') { if (s.charAt(2)=='u' && s.charAt(1)=='r') {id=Id_true; break L0;} } else if (c=='s') { if (s.charAt(2)=='i' && s.charAt(1)=='h') {id=Id_this; break L0;} } break L; case 'v': X="void";id=Id_void; break L; case 'w': X="with";id=Id_with; break L; } break L; case 5: switch (s.charAt(2)) { case 'a': X="class";id=Id_class; break L; case 'e': X="break";id=Id_break; break L; case 'i': X="while";id=Id_while; break L; case 'l': X="false";id=Id_false; break L; case 'n': c=s.charAt(0); if (c=='c') { X="const";id=Id_const; } else if (c=='f') { X="final";id=Id_final; } break L; case 'o': c=s.charAt(0); if (c=='f') { X="float";id=Id_float; } else if (c=='s') { X="short";id=Id_short; } break L; case 'p': X="super";id=Id_super; break L; case 'r': X="throw";id=Id_throw; break L; case 't': X="catch";id=Id_catch; break L; } break L; case 6: switch (s.charAt(1)) { case 'a': X="native";id=Id_native; break L; case 'e': c=s.charAt(0); if (c=='d') { X="delete";id=Id_delete; } else if (c=='r') { X="return";id=Id_return; } break L; case 'h': X="throws";id=Id_throws; break L; case 'm': X="import";id=Id_import; break L; case 'o': X="double";id=Id_double; break L; case 't': X="static";id=Id_static; break L; case 'u': X="public";id=Id_public; break L; case 'w': X="switch";id=Id_switch; break L; case 'x': X="export";id=Id_export; break L; case 'y': X="typeof";id=Id_typeof; break L; } break L; case 7: switch (s.charAt(1)) { case 'a': X="package";id=Id_package; break L; case 'e': X="default";id=Id_default; break L; case 'i': X="finally";id=Id_finally; break L; case 'o': X="boolean";id=Id_boolean; break L; case 'r': X="private";id=Id_private; break L; case 'x': X="extends";id=Id_extends; break L; } break L; case 8: switch (s.charAt(0)) { case 'a': X="abstract";id=Id_abstract; break L; case 'c': X="continue";id=Id_continue; break L; case 'd': X="debugger";id=Id_debugger; break L; case 'f': X="function";id=Id_function; break L; case 'v': X="volatile";id=Id_volatile; break L; } break L; case 9: c=s.charAt(0); if (c=='i') { X="interface";id=Id_interface; } else if (c=='p') { X="protected";id=Id_protected; } else if (c=='t') { X="transient";id=Id_transient; } break L; case 10: c=s.charAt(1); if (c=='m') { X="implements";id=Id_implements; } else if (c=='n') { X="instanceof";id=Id_instanceof; } break L; case 12: X="synchronized";id=Id_synchronized; break L; } if (X!=null && X!=s && !X.equals(s)) id = 0; } // #/generated# // #/string_id_map# if (id == 0) { return EOF; } this.op = id >> 8; return id & 0xff; } public TokenStream(Reader in, Scriptable scope, String sourceName, int lineno) { this.in = new LineBuffer(in, lineno); this.scope = scope; this.pushbackToken = EOF; this.sourceName = sourceName; flags = 0; } public Scriptable getScope() { return scope; } /* return and pop the token from the stream if it matches... * otherwise return null */ public boolean matchToken(int toMatch) throws IOException { int token = getToken(); if (token == toMatch) return true; // didn't match, push back token tokenno--; this.pushbackToken = token; return false; } public void clearPushback() { this.pushbackToken = EOF; } public void ungetToken(int tt) { if (this.pushbackToken != EOF && tt != ERROR) { String message = Context.getMessage2("msg.token.replaces.pushback", tokenToString(tt), tokenToString(this.pushbackToken)); throw new RuntimeException(message); } this.pushbackToken = tt; tokenno--; } public int peekToken() throws IOException { int result = getToken(); this.pushbackToken = result; tokenno--; return result; } public int peekTokenSameLine() throws IOException { int result; flags |= TSF_NEWLINES; // SCAN_NEWLINES from jsscan.h result = peekToken(); flags &= ~TSF_NEWLINES; // HIDE_NEWLINES from jsscan.h if (this.pushbackToken == EOL) this.pushbackToken = EOF; return result; } protected static boolean isJSIdentifier(String s) { int length = s.length(); if (length == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i=1; i<length; i++) { char c = s.charAt(i); if (!Character.isJavaIdentifierPart(c)) if (c == '\\') if (! ((i + 5) < length) && (s.charAt(i + 1) == 'u') && 0 <= xDigitToInt(s.charAt(i + 2)) && 0 <= xDigitToInt(s.charAt(i + 3)) && 0 <= xDigitToInt(s.charAt(i + 4)) && 0 <= xDigitToInt(s.charAt(i + 5))) return false; } return true; } private static boolean isAlpha(int c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); } static boolean isDigit(int c) { return (c >= '0' && c <= '9'); } static int xDigitToInt(int c) { if ('0' <= c && c <= '9') { return c - '0'; } if ('a' <= c && c <= 'f') { return c - ('a' - 10); } if ('A' <= c && c <= 'F') { return c - ('A' - 10); } return -1; } /* As defined in ECMA. jsscan.c uses C isspace() (which allows * \v, I think.) note that code in in.read() implicitly accepts * '\r' == \u000D as well. */ public static boolean isJSSpace(int c) { return (c == '\u0020' || c == '\u0009' || c == '\u000C' || c == '\u000B' || c == '\u00A0' || Character.getType((char)c) == Character.SPACE_SEPARATOR); } public static boolean isJSLineTerminator(int c) { return (c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029); } public int getToken() throws IOException { int c; tokenno++; // Check for pushed-back token if (this.pushbackToken != EOF) { int result = this.pushbackToken; this.pushbackToken = EOF; return result; } // Eat whitespace, possibly sensitive to newlines. do { c = in.read(); if (c == '\n') if ((flags & TSF_NEWLINES) != 0) break; } while (isJSSpace(c) || c == '\n'); if (c == EOF_CHAR) return EOF; // identifier/keyword/instanceof? // watch out for starting with a <backslash> boolean isUnicodeEscapeStart = false; if (c == '\\') { c = in.read(); if (c == 'u') isUnicodeEscapeStart = true; else c = '\\'; // always unread the 'u' or whatever, we need // to start the string below at the <backslash>. in.unread(); } if (isUnicodeEscapeStart || Character.isJavaIdentifierStart((char)c)) { in.startString(); boolean containsEscape = isUnicodeEscapeStart; do { c = in.read(); if (c == '\\') { c = in.read(); containsEscape = (c == 'u'); } } while (Character.isJavaIdentifierPart((char)c)); in.unread(); int result; String str = in.getString(); // OPT we shouldn't have to make a string (object!) to // check if it's a keyword. // strictly speaking we should probably push-back // all the bad characters if the <backslash>uXXXX // sequence is malformed. But since there isn't a // correct context(is there?) for a bad Unicode // escape sequence after an identifier, we can report // an error here. if (containsEscape) { char ca[] = str.toCharArray(); int L = str.length(); int destination = 0; for (int i = 0; i != L;) { c = ca[i]; ++i; if (c == '\\' && i != L && ca[i] == 'u') { boolean goodEscape = false; if (i + 4 < L) { int val = xDigitToInt(ca[i + 1]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 2]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 3]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 4]); if (val >= 0) { c = (char)val; i += 5; goodEscape = true; } } } } } if (!goodEscape) { reportSyntaxError("msg.invalid.escape", null); return ERROR; } } ca[destination] = (char)c; ++destination; } str = new String(ca, 0, destination); } else // Return the corresponding token if it's a keyword if ((result = stringToKeyword(str)) != EOF) { return result; } this.string = str; return NAME; } // is it a number? if (isDigit(c) || (c == '.' && isDigit(in.peek()))) { int base = 10; in.startString(); if (c == '0') { c = in.read(); if (c == 'x' || c == 'X') { c = in.read(); base = 16; // restart the string, losing leading 0x in.startString(); } else if (isDigit(c)) { base = 8; } } while (0 <= xDigitToInt(c)) { if (base < 16) { if (isAlpha(c)) break; /* * We permit 08 and 09 as decimal numbers, which * makes our behavior a superset of the ECMA * numeric grammar. We might not always be so * permissive, so we warn about it. */ if (base == 8 && c >= '8') { Object[] errArgs = { c == '8' ? "8" : "9" }; Context.reportWarning( Context.getMessage("msg.bad.octal.literal", errArgs), getSourceName(), in.getLineno(), getLine(), getOffset()); base = 10; } } c = in.read(); } boolean isInteger = true; if (base == 10 && (c == '.' || c == 'e' || c == 'E')) { isInteger = false; if (c == '.') { do { c = in.read(); } while (isDigit(c)); } if (c == 'e' || c == 'E') { c = in.read(); if (c == '+' || c == '-') { c = in.read(); } if (!isDigit(c)) { in.getString(); // throw away string in progress reportSyntaxError("msg.missing.exponent", null); return ERROR; } do { c = in.read(); } while (isDigit(c)); } } in.unread(); String numString = in.getString(); double dval; if (base == 10 && !isInteger) { try { // Use Java conversion to number from string... dval = (Double.valueOf(numString)).doubleValue(); } catch (NumberFormatException ex) { Object[] errArgs = { ex.getMessage() }; reportSyntaxError("msg.caught.nfe", errArgs); return ERROR; } } else { dval = ScriptRuntime.stringToNumber(numString, 0, base); } this.number = dval; return NUMBER; } // is it a string? if (c == '"' || c == '\'') { // We attempt to accumulate a string the fast way, by // building it directly out of the reader. But if there // are any escaped characters in the string, we revert to // building it out of a StringBuffer. StringBuffer stringBuf = null; int quoteChar = c; int val = 0; c = in.read(); in.startString(); // start after the first " while(c != quoteChar) { if (c == '\n' || c == EOF_CHAR) { in.unread(); in.getString(); // throw away the string in progress reportSyntaxError("msg.unterminated.string.lit", null); return ERROR; } if (c == '\\') { // We've hit an escaped character; revert to the // slow method of building a string. if (stringBuf == null) { // Don't include the backslash in.unread(); stringBuf = new StringBuffer(in.getString()); in.read(); } switch (c = in.read()) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\u000B'; break; // \v a late addition to the ECMA spec. // '\v' doesn't seem to be valid Java. default: if (isDigit(c) && c < '8') { val = c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); } } in.unread(); if (val > 0377) { reportSyntaxError("msg.oct.esc.too.large", null); return ERROR; } c = val; } else if (c == 'u') { /* * Get 4 hex digits; if the u escape is not * followed by 4 hex digits, use 'u' + the literal * character sequence that follows. Do some manual * match (OK because we're in a string) to avoid * multi-char match on the underlying stream. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'u'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('u'); c = c1; } else { int c3 = in.read(); c = (c << 4) | xDigitToInt(c3); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); c = c2; } else { int c4 = in.read(); c = (c << 4) | xDigitToInt(c4); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); stringBuf.append((char)c2); c = c3; } else { // got 4 hex digits! Woo Hoo! } } } } } else if (c == 'x') { /* Get 2 hex digits, defaulting to 'x' + literal * sequence, as above. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'x'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('x'); c = c1; } else { // got 2 hex digits } } } } } if (stringBuf != null) stringBuf.append((char) c); c = in.read(); } if (stringBuf != null) this.string = stringBuf.toString(); else { in.unread(); // miss the trailing " this.string = in.getString(); in.read(); } return STRING; } switch (c) { case '\n': return EOL; case ';': return SEMI; case '[': return LB; case ']': return RB; case '{': return LC; case '}': return RC; case '(': return LP; case ')': return RP; case ',': return COMMA; case '?': return HOOK; case ':': return COLON; case '.': return DOT; case '|': if (in.match('|')) { return OR; } else if (in.match('=')) { this.op = BITOR; return ASSIGN; } else { return BITOR; } case '^': if (in.match('=')) { this.op = BITXOR; return ASSIGN; } else { return BITXOR; } case '&': if (in.match('&')) { return AND; } else if (in.match('=')) { this.op = BITAND; return ASSIGN; } else { return BITAND; } case '=': if (in.match('=')) { if (in.match('=')) this.op = SHEQ; else this.op = EQ; return EQOP; } else { this.op = NOP; return ASSIGN; } case '!': if (in.match('=')) { if (in.match('=')) this.op = SHNE; else this.op = NE; return EQOP; } else { this.op = NOT; return UNARYOP; } case '<': /* NB:treat HTML begin-comment as comment-till-eol */ if (in.match('!')) { if (in.match('-')) { if (in.match('-')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); // in place of 'goto retry' } in.unread(); } in.unread(); } if (in.match('<')) { if (in.match('=')) { this.op = LSH; return ASSIGN; } else { this.op = LSH; return SHOP; } } else { if (in.match('=')) { this.op = LE; return RELOP; } else { this.op = LT; return RELOP; } } case '>': if (in.match('>')) { if (in.match('>')) { if (in.match('=')) { this.op = URSH; return ASSIGN; } else { this.op = URSH; return SHOP; } } else { if (in.match('=')) { this.op = RSH; return ASSIGN; } else { this.op = RSH; return SHOP; } } } else { if (in.match('=')) { this.op = GE; return RELOP; } else { this.op = GT; return RELOP; } } case '*': if (in.match('=')) { this.op = MUL; return ASSIGN; } else { return MUL; } case '/': // is it a // comment? if (in.match('/')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); } if (in.match('*')) { - while ((c = in.read()) != -1 - && !(c == '*' && in.match('/'))) { - if (c == '\n') { - } else if (c == '/' && in.match('*')) { - if (in.match('/')) - return getToken(); - reportSyntaxError("msg.nested.comment", null); - return ERROR; - } + while ((c = in.read()) != -1 && + !(c == '*' && in.match('/'))) { + ; // empty loop body } if (c == EOF_CHAR) { reportSyntaxError("msg.unterminated.comment", null); return ERROR; } return getToken(); // `goto retry' } // is it a regexp? if ((flags & TSF_REGEXP) != 0) { // We don't try to use the in.startString/in.getString // approach, because escaped characters (which break it) // seem likely to be common. StringBuffer re = new StringBuffer(); while ((c = in.read()) != '/') { if (c == '\n' || c == EOF_CHAR) { in.unread(); reportSyntaxError("msg.unterminated.re.lit", null); return ERROR; } if (c == '\\') { re.append((char) c); c = in.read(); } re.append((char) c); } StringBuffer flagsBuf = new StringBuffer(); while (true) { if (in.match('g')) flagsBuf.append('g'); else if (in.match('i')) flagsBuf.append('i'); else if (in.match('m')) flagsBuf.append('m'); else break; } if (isAlpha(in.peek())) { reportSyntaxError("msg.invalid.re.flag", null); return ERROR; } this.string = re.toString(); this.regExpFlags = flagsBuf.toString(); return OBJECT; } if (in.match('=')) { this.op = DIV; return ASSIGN; } else { return DIV; } case '%': this.op = MOD; if (in.match('=')) { return ASSIGN; } else { return MOD; } case '~': this.op = BITNOT; return UNARYOP; case '+': case '-': if (in.match('=')) { if (c == '+') { this.op = ADD; return ASSIGN; } else { this.op = SUB; return ASSIGN; } } else if (in.match((char) c)) { if (c == '+') { return INC; } else { return DEC; } } else if (c == '-') { return SUB; } else { return ADD; } default: reportSyntaxError("msg.illegal.character", null); return ERROR; } } public void reportSyntaxError(String messageProperty, Object[] args) { String message = Context.getMessage(messageProperty, args); if (scope != null) { // We're probably in an eval. Need to throw an exception. throw NativeGlobal.constructError( Context.getContext(), "SyntaxError", message, scope, getSourceName(), getLineno(), getOffset(), getLine()); } else { Context.reportError(message, getSourceName(), getLineno(), getLine(), getOffset()); } } public String getSourceName() { return sourceName; } public int getLineno() { return in.getLineno(); } public int getOp() { return op; } public String getString() { return string; } public double getNumber() { return number; } public String getLine() { return in.getLine(); } public int getOffset() { return in.getOffset(); } public int getTokenno() { return tokenno; } public boolean eof() { return in.eof(); } // instance variables private LineBuffer in; /* for TSF_REGEXP, etc. * should this be manipulated by gettor/settor functions? * should it be passed to getToken(); */ public int flags; public String regExpFlags; private String sourceName; private String line; private Scriptable scope; private int pushbackToken; private int tokenno; private int op; // Set this to an inital non-null value so that the Parser has // something to retrieve even if an error has occured and no // string is found. Fosters one class of error, but saves lots of // code. private String string = ""; private double number; }
true
true
public int getToken() throws IOException { int c; tokenno++; // Check for pushed-back token if (this.pushbackToken != EOF) { int result = this.pushbackToken; this.pushbackToken = EOF; return result; } // Eat whitespace, possibly sensitive to newlines. do { c = in.read(); if (c == '\n') if ((flags & TSF_NEWLINES) != 0) break; } while (isJSSpace(c) || c == '\n'); if (c == EOF_CHAR) return EOF; // identifier/keyword/instanceof? // watch out for starting with a <backslash> boolean isUnicodeEscapeStart = false; if (c == '\\') { c = in.read(); if (c == 'u') isUnicodeEscapeStart = true; else c = '\\'; // always unread the 'u' or whatever, we need // to start the string below at the <backslash>. in.unread(); } if (isUnicodeEscapeStart || Character.isJavaIdentifierStart((char)c)) { in.startString(); boolean containsEscape = isUnicodeEscapeStart; do { c = in.read(); if (c == '\\') { c = in.read(); containsEscape = (c == 'u'); } } while (Character.isJavaIdentifierPart((char)c)); in.unread(); int result; String str = in.getString(); // OPT we shouldn't have to make a string (object!) to // check if it's a keyword. // strictly speaking we should probably push-back // all the bad characters if the <backslash>uXXXX // sequence is malformed. But since there isn't a // correct context(is there?) for a bad Unicode // escape sequence after an identifier, we can report // an error here. if (containsEscape) { char ca[] = str.toCharArray(); int L = str.length(); int destination = 0; for (int i = 0; i != L;) { c = ca[i]; ++i; if (c == '\\' && i != L && ca[i] == 'u') { boolean goodEscape = false; if (i + 4 < L) { int val = xDigitToInt(ca[i + 1]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 2]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 3]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 4]); if (val >= 0) { c = (char)val; i += 5; goodEscape = true; } } } } } if (!goodEscape) { reportSyntaxError("msg.invalid.escape", null); return ERROR; } } ca[destination] = (char)c; ++destination; } str = new String(ca, 0, destination); } else // Return the corresponding token if it's a keyword if ((result = stringToKeyword(str)) != EOF) { return result; } this.string = str; return NAME; } // is it a number? if (isDigit(c) || (c == '.' && isDigit(in.peek()))) { int base = 10; in.startString(); if (c == '0') { c = in.read(); if (c == 'x' || c == 'X') { c = in.read(); base = 16; // restart the string, losing leading 0x in.startString(); } else if (isDigit(c)) { base = 8; } } while (0 <= xDigitToInt(c)) { if (base < 16) { if (isAlpha(c)) break; /* * We permit 08 and 09 as decimal numbers, which * makes our behavior a superset of the ECMA * numeric grammar. We might not always be so * permissive, so we warn about it. */ if (base == 8 && c >= '8') { Object[] errArgs = { c == '8' ? "8" : "9" }; Context.reportWarning( Context.getMessage("msg.bad.octal.literal", errArgs), getSourceName(), in.getLineno(), getLine(), getOffset()); base = 10; } } c = in.read(); } boolean isInteger = true; if (base == 10 && (c == '.' || c == 'e' || c == 'E')) { isInteger = false; if (c == '.') { do { c = in.read(); } while (isDigit(c)); } if (c == 'e' || c == 'E') { c = in.read(); if (c == '+' || c == '-') { c = in.read(); } if (!isDigit(c)) { in.getString(); // throw away string in progress reportSyntaxError("msg.missing.exponent", null); return ERROR; } do { c = in.read(); } while (isDigit(c)); } } in.unread(); String numString = in.getString(); double dval; if (base == 10 && !isInteger) { try { // Use Java conversion to number from string... dval = (Double.valueOf(numString)).doubleValue(); } catch (NumberFormatException ex) { Object[] errArgs = { ex.getMessage() }; reportSyntaxError("msg.caught.nfe", errArgs); return ERROR; } } else { dval = ScriptRuntime.stringToNumber(numString, 0, base); } this.number = dval; return NUMBER; } // is it a string? if (c == '"' || c == '\'') { // We attempt to accumulate a string the fast way, by // building it directly out of the reader. But if there // are any escaped characters in the string, we revert to // building it out of a StringBuffer. StringBuffer stringBuf = null; int quoteChar = c; int val = 0; c = in.read(); in.startString(); // start after the first " while(c != quoteChar) { if (c == '\n' || c == EOF_CHAR) { in.unread(); in.getString(); // throw away the string in progress reportSyntaxError("msg.unterminated.string.lit", null); return ERROR; } if (c == '\\') { // We've hit an escaped character; revert to the // slow method of building a string. if (stringBuf == null) { // Don't include the backslash in.unread(); stringBuf = new StringBuffer(in.getString()); in.read(); } switch (c = in.read()) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\u000B'; break; // \v a late addition to the ECMA spec. // '\v' doesn't seem to be valid Java. default: if (isDigit(c) && c < '8') { val = c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); } } in.unread(); if (val > 0377) { reportSyntaxError("msg.oct.esc.too.large", null); return ERROR; } c = val; } else if (c == 'u') { /* * Get 4 hex digits; if the u escape is not * followed by 4 hex digits, use 'u' + the literal * character sequence that follows. Do some manual * match (OK because we're in a string) to avoid * multi-char match on the underlying stream. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'u'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('u'); c = c1; } else { int c3 = in.read(); c = (c << 4) | xDigitToInt(c3); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); c = c2; } else { int c4 = in.read(); c = (c << 4) | xDigitToInt(c4); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); stringBuf.append((char)c2); c = c3; } else { // got 4 hex digits! Woo Hoo! } } } } } else if (c == 'x') { /* Get 2 hex digits, defaulting to 'x' + literal * sequence, as above. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'x'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('x'); c = c1; } else { // got 2 hex digits } } } } } if (stringBuf != null) stringBuf.append((char) c); c = in.read(); } if (stringBuf != null) this.string = stringBuf.toString(); else { in.unread(); // miss the trailing " this.string = in.getString(); in.read(); } return STRING; } switch (c) { case '\n': return EOL; case ';': return SEMI; case '[': return LB; case ']': return RB; case '{': return LC; case '}': return RC; case '(': return LP; case ')': return RP; case ',': return COMMA; case '?': return HOOK; case ':': return COLON; case '.': return DOT; case '|': if (in.match('|')) { return OR; } else if (in.match('=')) { this.op = BITOR; return ASSIGN; } else { return BITOR; } case '^': if (in.match('=')) { this.op = BITXOR; return ASSIGN; } else { return BITXOR; } case '&': if (in.match('&')) { return AND; } else if (in.match('=')) { this.op = BITAND; return ASSIGN; } else { return BITAND; } case '=': if (in.match('=')) { if (in.match('=')) this.op = SHEQ; else this.op = EQ; return EQOP; } else { this.op = NOP; return ASSIGN; } case '!': if (in.match('=')) { if (in.match('=')) this.op = SHNE; else this.op = NE; return EQOP; } else { this.op = NOT; return UNARYOP; } case '<': /* NB:treat HTML begin-comment as comment-till-eol */ if (in.match('!')) { if (in.match('-')) { if (in.match('-')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); // in place of 'goto retry' } in.unread(); } in.unread(); } if (in.match('<')) { if (in.match('=')) { this.op = LSH; return ASSIGN; } else { this.op = LSH; return SHOP; } } else { if (in.match('=')) { this.op = LE; return RELOP; } else { this.op = LT; return RELOP; } } case '>': if (in.match('>')) { if (in.match('>')) { if (in.match('=')) { this.op = URSH; return ASSIGN; } else { this.op = URSH; return SHOP; } } else { if (in.match('=')) { this.op = RSH; return ASSIGN; } else { this.op = RSH; return SHOP; } } } else { if (in.match('=')) { this.op = GE; return RELOP; } else { this.op = GT; return RELOP; } } case '*': if (in.match('=')) { this.op = MUL; return ASSIGN; } else { return MUL; } case '/': // is it a // comment? if (in.match('/')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); } if (in.match('*')) { while ((c = in.read()) != -1 && !(c == '*' && in.match('/'))) { if (c == '\n') { } else if (c == '/' && in.match('*')) { if (in.match('/')) return getToken(); reportSyntaxError("msg.nested.comment", null); return ERROR; } } if (c == EOF_CHAR) { reportSyntaxError("msg.unterminated.comment", null); return ERROR; } return getToken(); // `goto retry' } // is it a regexp? if ((flags & TSF_REGEXP) != 0) { // We don't try to use the in.startString/in.getString // approach, because escaped characters (which break it) // seem likely to be common. StringBuffer re = new StringBuffer(); while ((c = in.read()) != '/') { if (c == '\n' || c == EOF_CHAR) { in.unread(); reportSyntaxError("msg.unterminated.re.lit", null); return ERROR; } if (c == '\\') { re.append((char) c); c = in.read(); } re.append((char) c); } StringBuffer flagsBuf = new StringBuffer(); while (true) { if (in.match('g')) flagsBuf.append('g'); else if (in.match('i')) flagsBuf.append('i'); else if (in.match('m')) flagsBuf.append('m'); else break; } if (isAlpha(in.peek())) { reportSyntaxError("msg.invalid.re.flag", null); return ERROR; } this.string = re.toString(); this.regExpFlags = flagsBuf.toString(); return OBJECT; } if (in.match('=')) { this.op = DIV; return ASSIGN; } else { return DIV; } case '%': this.op = MOD; if (in.match('=')) { return ASSIGN; } else { return MOD; } case '~': this.op = BITNOT; return UNARYOP; case '+': case '-': if (in.match('=')) { if (c == '+') { this.op = ADD; return ASSIGN; } else { this.op = SUB; return ASSIGN; } } else if (in.match((char) c)) { if (c == '+') { return INC; } else { return DEC; } } else if (c == '-') { return SUB; } else { return ADD; } default: reportSyntaxError("msg.illegal.character", null); return ERROR; } }
public int getToken() throws IOException { int c; tokenno++; // Check for pushed-back token if (this.pushbackToken != EOF) { int result = this.pushbackToken; this.pushbackToken = EOF; return result; } // Eat whitespace, possibly sensitive to newlines. do { c = in.read(); if (c == '\n') if ((flags & TSF_NEWLINES) != 0) break; } while (isJSSpace(c) || c == '\n'); if (c == EOF_CHAR) return EOF; // identifier/keyword/instanceof? // watch out for starting with a <backslash> boolean isUnicodeEscapeStart = false; if (c == '\\') { c = in.read(); if (c == 'u') isUnicodeEscapeStart = true; else c = '\\'; // always unread the 'u' or whatever, we need // to start the string below at the <backslash>. in.unread(); } if (isUnicodeEscapeStart || Character.isJavaIdentifierStart((char)c)) { in.startString(); boolean containsEscape = isUnicodeEscapeStart; do { c = in.read(); if (c == '\\') { c = in.read(); containsEscape = (c == 'u'); } } while (Character.isJavaIdentifierPart((char)c)); in.unread(); int result; String str = in.getString(); // OPT we shouldn't have to make a string (object!) to // check if it's a keyword. // strictly speaking we should probably push-back // all the bad characters if the <backslash>uXXXX // sequence is malformed. But since there isn't a // correct context(is there?) for a bad Unicode // escape sequence after an identifier, we can report // an error here. if (containsEscape) { char ca[] = str.toCharArray(); int L = str.length(); int destination = 0; for (int i = 0; i != L;) { c = ca[i]; ++i; if (c == '\\' && i != L && ca[i] == 'u') { boolean goodEscape = false; if (i + 4 < L) { int val = xDigitToInt(ca[i + 1]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 2]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 3]); if (val >= 0) { val = (val << 4) | xDigitToInt(ca[i + 4]); if (val >= 0) { c = (char)val; i += 5; goodEscape = true; } } } } } if (!goodEscape) { reportSyntaxError("msg.invalid.escape", null); return ERROR; } } ca[destination] = (char)c; ++destination; } str = new String(ca, 0, destination); } else // Return the corresponding token if it's a keyword if ((result = stringToKeyword(str)) != EOF) { return result; } this.string = str; return NAME; } // is it a number? if (isDigit(c) || (c == '.' && isDigit(in.peek()))) { int base = 10; in.startString(); if (c == '0') { c = in.read(); if (c == 'x' || c == 'X') { c = in.read(); base = 16; // restart the string, losing leading 0x in.startString(); } else if (isDigit(c)) { base = 8; } } while (0 <= xDigitToInt(c)) { if (base < 16) { if (isAlpha(c)) break; /* * We permit 08 and 09 as decimal numbers, which * makes our behavior a superset of the ECMA * numeric grammar. We might not always be so * permissive, so we warn about it. */ if (base == 8 && c >= '8') { Object[] errArgs = { c == '8' ? "8" : "9" }; Context.reportWarning( Context.getMessage("msg.bad.octal.literal", errArgs), getSourceName(), in.getLineno(), getLine(), getOffset()); base = 10; } } c = in.read(); } boolean isInteger = true; if (base == 10 && (c == '.' || c == 'e' || c == 'E')) { isInteger = false; if (c == '.') { do { c = in.read(); } while (isDigit(c)); } if (c == 'e' || c == 'E') { c = in.read(); if (c == '+' || c == '-') { c = in.read(); } if (!isDigit(c)) { in.getString(); // throw away string in progress reportSyntaxError("msg.missing.exponent", null); return ERROR; } do { c = in.read(); } while (isDigit(c)); } } in.unread(); String numString = in.getString(); double dval; if (base == 10 && !isInteger) { try { // Use Java conversion to number from string... dval = (Double.valueOf(numString)).doubleValue(); } catch (NumberFormatException ex) { Object[] errArgs = { ex.getMessage() }; reportSyntaxError("msg.caught.nfe", errArgs); return ERROR; } } else { dval = ScriptRuntime.stringToNumber(numString, 0, base); } this.number = dval; return NUMBER; } // is it a string? if (c == '"' || c == '\'') { // We attempt to accumulate a string the fast way, by // building it directly out of the reader. But if there // are any escaped characters in the string, we revert to // building it out of a StringBuffer. StringBuffer stringBuf = null; int quoteChar = c; int val = 0; c = in.read(); in.startString(); // start after the first " while(c != quoteChar) { if (c == '\n' || c == EOF_CHAR) { in.unread(); in.getString(); // throw away the string in progress reportSyntaxError("msg.unterminated.string.lit", null); return ERROR; } if (c == '\\') { // We've hit an escaped character; revert to the // slow method of building a string. if (stringBuf == null) { // Don't include the backslash in.unread(); stringBuf = new StringBuffer(in.getString()); in.read(); } switch (c = in.read()) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\u000B'; break; // \v a late addition to the ECMA spec. // '\v' doesn't seem to be valid Java. default: if (isDigit(c) && c < '8') { val = c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); if (isDigit(c) && c < '8') { val = 8 * val + c - '0'; c = in.read(); } } in.unread(); if (val > 0377) { reportSyntaxError("msg.oct.esc.too.large", null); return ERROR; } c = val; } else if (c == 'u') { /* * Get 4 hex digits; if the u escape is not * followed by 4 hex digits, use 'u' + the literal * character sequence that follows. Do some manual * match (OK because we're in a string) to avoid * multi-char match on the underlying stream. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'u'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('u'); c = c1; } else { int c3 = in.read(); c = (c << 4) | xDigitToInt(c3); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); c = c2; } else { int c4 = in.read(); c = (c << 4) | xDigitToInt(c4); if (c < 0) { in.unread(); stringBuf.append('u'); stringBuf.append((char)c1); stringBuf.append((char)c2); c = c3; } else { // got 4 hex digits! Woo Hoo! } } } } } else if (c == 'x') { /* Get 2 hex digits, defaulting to 'x' + literal * sequence, as above. */ int c1 = in.read(); c = xDigitToInt(c1); if (c < 0) { in.unread(); c = 'x'; } else { int c2 = in.read(); c = (c << 4) | xDigitToInt(c2); if (c < 0) { in.unread(); stringBuf.append('x'); c = c1; } else { // got 2 hex digits } } } } } if (stringBuf != null) stringBuf.append((char) c); c = in.read(); } if (stringBuf != null) this.string = stringBuf.toString(); else { in.unread(); // miss the trailing " this.string = in.getString(); in.read(); } return STRING; } switch (c) { case '\n': return EOL; case ';': return SEMI; case '[': return LB; case ']': return RB; case '{': return LC; case '}': return RC; case '(': return LP; case ')': return RP; case ',': return COMMA; case '?': return HOOK; case ':': return COLON; case '.': return DOT; case '|': if (in.match('|')) { return OR; } else if (in.match('=')) { this.op = BITOR; return ASSIGN; } else { return BITOR; } case '^': if (in.match('=')) { this.op = BITXOR; return ASSIGN; } else { return BITXOR; } case '&': if (in.match('&')) { return AND; } else if (in.match('=')) { this.op = BITAND; return ASSIGN; } else { return BITAND; } case '=': if (in.match('=')) { if (in.match('=')) this.op = SHEQ; else this.op = EQ; return EQOP; } else { this.op = NOP; return ASSIGN; } case '!': if (in.match('=')) { if (in.match('=')) this.op = SHNE; else this.op = NE; return EQOP; } else { this.op = NOT; return UNARYOP; } case '<': /* NB:treat HTML begin-comment as comment-till-eol */ if (in.match('!')) { if (in.match('-')) { if (in.match('-')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); // in place of 'goto retry' } in.unread(); } in.unread(); } if (in.match('<')) { if (in.match('=')) { this.op = LSH; return ASSIGN; } else { this.op = LSH; return SHOP; } } else { if (in.match('=')) { this.op = LE; return RELOP; } else { this.op = LT; return RELOP; } } case '>': if (in.match('>')) { if (in.match('>')) { if (in.match('=')) { this.op = URSH; return ASSIGN; } else { this.op = URSH; return SHOP; } } else { if (in.match('=')) { this.op = RSH; return ASSIGN; } else { this.op = RSH; return SHOP; } } } else { if (in.match('=')) { this.op = GE; return RELOP; } else { this.op = GT; return RELOP; } } case '*': if (in.match('=')) { this.op = MUL; return ASSIGN; } else { return MUL; } case '/': // is it a // comment? if (in.match('/')) { while ((c = in.read()) != EOF_CHAR && c != '\n') /* skip to end of line */; in.unread(); return getToken(); } if (in.match('*')) { while ((c = in.read()) != -1 && !(c == '*' && in.match('/'))) { ; // empty loop body } if (c == EOF_CHAR) { reportSyntaxError("msg.unterminated.comment", null); return ERROR; } return getToken(); // `goto retry' } // is it a regexp? if ((flags & TSF_REGEXP) != 0) { // We don't try to use the in.startString/in.getString // approach, because escaped characters (which break it) // seem likely to be common. StringBuffer re = new StringBuffer(); while ((c = in.read()) != '/') { if (c == '\n' || c == EOF_CHAR) { in.unread(); reportSyntaxError("msg.unterminated.re.lit", null); return ERROR; } if (c == '\\') { re.append((char) c); c = in.read(); } re.append((char) c); } StringBuffer flagsBuf = new StringBuffer(); while (true) { if (in.match('g')) flagsBuf.append('g'); else if (in.match('i')) flagsBuf.append('i'); else if (in.match('m')) flagsBuf.append('m'); else break; } if (isAlpha(in.peek())) { reportSyntaxError("msg.invalid.re.flag", null); return ERROR; } this.string = re.toString(); this.regExpFlags = flagsBuf.toString(); return OBJECT; } if (in.match('=')) { this.op = DIV; return ASSIGN; } else { return DIV; } case '%': this.op = MOD; if (in.match('=')) { return ASSIGN; } else { return MOD; } case '~': this.op = BITNOT; return UNARYOP; case '+': case '-': if (in.match('=')) { if (c == '+') { this.op = ADD; return ASSIGN; } else { this.op = SUB; return ASSIGN; } } else if (in.match((char) c)) { if (c == '+') { return INC; } else { return DEC; } } else if (c == '-') { return SUB; } else { return ADD; } default: reportSyntaxError("msg.illegal.character", null); return ERROR; } }
diff --git a/crypto/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java b/crypto/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java index abafe4bd..910081e8 100644 --- a/crypto/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java +++ b/crypto/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java @@ -1,25 +1,25 @@ package org.bouncycastle.crypto.params; import java.security.SecureRandom; import org.bouncycastle.crypto.KeyGenerationParameters; public class DHKeyGenerationParameters extends KeyGenerationParameters { private DHParameters params; public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { - super(random, (params.getJ() != 0) ? params.getJ() : params.getP().bitLength() - 1); + super(random, params.getP().bitLength()); this.params = params; } public DHParameters getParameters() { return params; } }
true
true
public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { super(random, (params.getJ() != 0) ? params.getJ() : params.getP().bitLength() - 1); this.params = params; }
public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { super(random, params.getP().bitLength()); this.params = params; }
diff --git a/src/sai_cas/servlet/CrossMatchServlet.java b/src/sai_cas/servlet/CrossMatchServlet.java index ec11895..a9cbc54 100644 --- a/src/sai_cas/servlet/CrossMatchServlet.java +++ b/src/sai_cas/servlet/CrossMatchServlet.java @@ -1,287 +1,288 @@ package sai_cas.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.File; import java.util.List; import java.util.Calendar; import java.util.logging.Logger; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.*; import sai_cas.VOTABLEFile.VOTABLE; import sai_cas.VOTABLEFile.Votable; import sai_cas.VOTABLEFile.VotableException; import sai_cas.db.*; import sai_cas.output.CSVQueryResultsOutputter; import sai_cas.output.QueryResultsOutputter; import sai_cas.output.VOTableQueryResultsOutputter; import sai_cas.vo.*; public class CrossMatchServlet extends HttpServlet { static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("sai_cas.CrossMatchServlet"); public enum formats {VOTABLE, CSV}; public class CrossMatchServletException extends Exception { CrossMatchServletException() { super(); } CrossMatchServletException(String s) { super(s); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { + logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { } } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new ServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { uploadedFile.delete(); } catch (Exception e) { logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } }
diff --git a/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java b/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java index 50f0d43..530fac3 100644 --- a/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java +++ b/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java @@ -1,638 +1,643 @@ package org.jvnet.sorcerer; import antlr.Token; import antlr.TokenStreamException; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LineMap; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.PrimitiveTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.JavacTask; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.source.util.TreeScanner; import com.sun.source.util.Trees; import org.jvnet.sorcerer.Tag.DeclName; import org.jvnet.sorcerer.impl.JavaLexer; import org.jvnet.sorcerer.impl.JavaTokenTypes; import org.jvnet.sorcerer.util.CharSequenceReader; import org.jvnet.sorcerer.util.TreeUtil; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.DiagnosticListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; /** * Represents set of analyzed source code. * * <p> * This object retains the entire parse trees of the source files * and type information, as well as enough indexes among them * to make page generation fast enough. There's always a tricky trade-off * between how much index you retain in memory vs how much you compute * dynamically. * * <p> * Instances of this class can be safely accessed from multiple threads * concurrently. * * <p> * Normally, {@link Analyzer} is used to create this object, but * advanced clients may invoke the constructor with a properly * configured {@link JavacTask}. * * @see Analyzer#analyze * @author Kohsuke Kawaguchi */ public class ParsedSourceSet { // javac related objects private final Trees trees; private final SourcePositions srcPos; private final Elements elements; private final Types types; private final List<CompilationUnitTree> compilationUnits = new ArrayList<CompilationUnitTree>(); /** * path to {@link ClassTree} keyed by its full-qualified class name. */ private final Map<String,TreePath> classes = new TreeMap<String,TreePath>(); private final Set<PackageElement> packages = new TreeSet<PackageElement>(PACKAGENAME_COMPARATOR); private final List<Dependency> dependencies = new ArrayList<Dependency>(); private final int tabWidth; /** * {@link ParsedType}s keyed by its {@link ParsedType#element}. */ /*package*/ final Map<TypeElement,ParsedType> parsedTypes = new HashMap<TypeElement,ParsedType>(); /** * {@link ClassTree}s in the compilation unit to their {@link TreePath}. */ /*package*/ final Map<ClassTree,TreePath> treePathByClass = new HashMap<ClassTree,TreePath>(); /** * Runs <tt>javac</tt> and analyzes the result. * * <p> * Any error found during the analysis will be reported to * {@link DiagnosticListener} installed on {@link JavacTask}. */ public ParsedSourceSet(JavacTask javac, int tabWidth) throws IOException { trees = Trees.instance(javac); elements = javac.getElements(); types = javac.getTypes(); srcPos = new SourcePositionsWrapper(trees.getSourcePositions()); this.tabWidth = tabWidth; Iterable<? extends CompilationUnitTree> parsed = javac.parse(); javac.analyze(); // used to list up all analyzed classes TreePathScanner<?,?> classScanner = new TreePathScanner<Void,Void>() { public Void visitClass(ClassTree ct, Void _) { TreePath path = getCurrentPath(); treePathByClass.put(ct,path); TypeElement e = (TypeElement) trees.getElement(path); if(e!=null) { classes.put(e.getQualifiedName().toString(), path); // make sure we have descendants tree built for all compilation units getParsedType(e); // remember packages that have compilation units in it Element p = e.getEnclosingElement(); if(p.getKind()==ElementKind.PACKAGE) packages.add((PackageElement) p); } return super.visitClass(ct, _); } }; for( CompilationUnitTree u : parsed ) { compilationUnits.add(u); classScanner.scan(u,null); } // build up index for find usage. for( Map.Entry<TypeElement,Set<CompilationUnitTree>> e : ClassReferenceBuilder.build(compilationUnits).entrySet() ) getParsedType(e.getKey()).referers = e.getValue().toArray(new CompilationUnitTree[e.getValue().size()]); } /** * Gets all the {@link CompilationUnitTree}s that are analyzed. * * @return * can be empty but never null. */ public List<CompilationUnitTree> getCompilationUnits() { return Collections.unmodifiableList(compilationUnits); } /** * Gets all the {@link TreePath}s to {@link ClassTree}s included * in the analyzed source files. * * @return * can be empty but never null. */ public Collection<TreePath> getClasses() { return Collections.unmodifiableCollection(classes.values()); } /** * All the {@link ClassTree}s to their {@link TreePath}s. */ public Map<ClassTree,TreePath> getTreePathByClass() { return treePathByClass; } /** * Gets the javadoc/sorcerer locations of dependencies. */ public List<Dependency> getDependencies() { return dependencies; } public void addDependency(Dependency d) { dependencies.add(d); } /** * Gets all the classes included in the analyzed source files. * * <p> * This includes interfaces, enums, and annotation types. * It also includes types that are defined elsewhere (that are referenced by * compiled source code.) * * @return * can be empty but never null. */ public Collection<TypeElement> getClassElements() { return Collections.unmodifiableCollection(parsedTypes.keySet()); } /** * Gets all the classes in the given package. */ public Collection<TypeElement> getClassElements(PackageElement pkg) { Set<TypeElement> r = new TreeSet<TypeElement>(TYPE_COMPARATOR); for (TypeElement e : parsedTypes.keySet()) { Element p = e.getEnclosingElement(); if(p.equals(pkg)) r.add(e); } return r; } /** * Gets all the packages of the analyzed source files. * * <p> * This does not include those packages that are just referenced. * * @return * can be empty but never null. */ public Collection<PackageElement> getPackageElement() { return Collections.unmodifiableCollection(packages); } /** * Gets the list of all fully-qualified class names in the analyzed source files. * * @return * can be empty but never null. */ public Set<String> getClassNames() { return Collections.unmodifiableSet(classes.keySet()); } /** * Gets the {@link TreePath} by its fully qualified class name. */ public TreePath getClassTreePath(String fullyQualifiedClassName) { return classes.get(fullyQualifiedClassName); } /** * Gets the {@link Trees} object that lets you navigate around the tree model. * * @return * always non-null, same object. */ public Trees getTrees() { return trees; } /** * Gets the {@link SourcePositions} object that lets you find the location of objects. * * @return * always non-null, same object. */ public SourcePositions getSourcePositions() { return srcPos; } /** * Gets the {@link Elements} object that lets you navigate around {@link Element}s. * * @return * always non-null, same object. */ public Elements getElements() { return elements; } /** * Gets the {@link Types} object that lets you navigate around {@link TypeMirror}s. * * @return * always non-null, same object. */ public Types getTypes() { return types; } /** * Gets the current TAB width. */ public int getTabWidth() { return tabWidth; } /** * Gets or creates a {@link ParsedType} for the given {@link TypeElement}. */ public ParsedType getParsedType(TypeElement e) { ParsedType v = parsedTypes.get(e); if(v==null) return new ParsedType(this,e); // the constructor will register itself to the map else return v; } /** * Gets all the {@link ParsedType}s. */ public Collection<ParsedType> getParsedTypes() { return parsedTypes.values(); } /** * Invoked by {@link HtmlGenerator}'s constructor to complete the initialization. * <p> * This is where the actual annotation of the source code happens. */ protected void configure(final CompilationUnitTree cu, final HtmlGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Tag.Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new Tag.FieldDecl(cu,srcPos,vt,e)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new Tag.LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } gen.add(new Tag.DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new Tag.DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new Tag.MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. Token token; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); else token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new Tag.ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new Tag.FieldRef(cu,srcPos,id,(VariableElement)e)); break; + case PARAMETER: + case EXCEPTION_PARAMETER: + case LOCAL_VARIABLE: + gen.add(new Tag.LocalVarRef(cu,srcPos,id,(VariableElement)e)); + break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new Tag.FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e!=null) { gen.add(new Tag.MethodRef(sp,ep,(ExecutableElement)e)); } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mi); if(e!=null) { Name methodName = e.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new Tag.MethodRef(ep-methodName.length(),ep,e)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } } private long getPosition(LineMap lineMap, Token token) { return lineMap.getPosition(token.getLine(),token.getColumn()); } public static final Comparator<PackageElement> PACKAGENAME_COMPARATOR = new Comparator<PackageElement>() { public int compare(PackageElement lhs, PackageElement rhs) { return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString()); } }; public static final Comparator<Element> SIMPLENAME_COMPARATOR = new Comparator<Element>() { public int compare(Element lhs, Element rhs) { return lhs.getSimpleName().toString().compareTo(rhs.getSimpleName().toString()); } }; private static final Comparator<TypeElement> TYPE_COMPARATOR = new Comparator<TypeElement>() { public int compare(TypeElement lhs, TypeElement rhs) { return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString()); } }; }
true
true
protected void configure(final CompilationUnitTree cu, final HtmlGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Tag.Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new Tag.FieldDecl(cu,srcPos,vt,e)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new Tag.LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } gen.add(new Tag.DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new Tag.DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new Tag.MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. Token token; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); else token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new Tag.ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new Tag.FieldRef(cu,srcPos,id,(VariableElement)e)); break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new Tag.FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e!=null) { gen.add(new Tag.MethodRef(sp,ep,(ExecutableElement)e)); } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mi); if(e!=null) { Name methodName = e.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new Tag.MethodRef(ep-methodName.length(),ep,e)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } }
protected void configure(final CompilationUnitTree cu, final HtmlGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Tag.Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new Tag.FieldDecl(cu,srcPos,vt,e)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new Tag.LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } gen.add(new Tag.DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new Tag.DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new Tag.MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. Token token; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); else token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new Tag.ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new Tag.FieldRef(cu,srcPos,id,(VariableElement)e)); break; case PARAMETER: case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: gen.add(new Tag.LocalVarRef(cu,srcPos,id,(VariableElement)e)); break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new Tag.FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new Tag.TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e!=null) { gen.add(new Tag.MethodRef(sp,ep,(ExecutableElement)e)); } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mi); if(e!=null) { Name methodName = e.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new Tag.MethodRef(ep-methodName.length(),ep,e)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } }
diff --git a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java index cde23984..71d9978d 100644 --- a/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java +++ b/sahi/src/main/java/com/redhat/qe/jon/sahi/base/inventory/Operations.java @@ -1,190 +1,194 @@ package com.redhat.qe.jon.sahi.base.inventory; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import net.sf.sahi.client.ElementStub; import org.testng.Assert; import com.redhat.qe.jon.sahi.tasks.SahiTasks; import com.redhat.qe.jon.sahi.tasks.Timing; /** * represents <b>Operations</b> Tab of given resource. * Creating instance of this class will navigate to resource and select <b>Operations</b> Tab * * @author lzoubek */ public class Operations extends ResourceTab { public Operations(SahiTasks tasks, Resource resource) { super(tasks, resource); } @Override protected void navigate() { navigateUnderResource("Operations/Schedules"); raiseErrorIfCellDoesNotExist("Operations"); } /** * Creates new Operation of given name, also selects it in <b>Operation:</b> combo * * @param name of new Operation * @return new operation */ public Operation newOperation(String name) { tasks.cell("New").click(); return new Operation(tasks, name); } /** * asserts operation result, waits until operation is either success or failure. * * @param op operation * @param success if true, success is expected, otherwise failure is expected * @return result map returned by this operation if operation succeeded, otherwise null. * In this map, keys are result properties and values are result values */ public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().summary(); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); getResource().summary(); } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).doubleClick(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest(el.fetch()); } if (headerCells.size() > 1) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 3) + " result rows"); log.finest("The rows are: " + rows.toString()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); - log.fine("Found result property [" + key.getText() + "]"); - result.put(key.getText(), value.getText()); + if (key.exists() && value.exists()) { + log.fine("Found result property [" + key.getText() + "]"); + result.put(key.getText(), value.getText()); + } else { + log.warning("Missing key or value column in the results table - probably caused by nonstandard result output"); + } } return result; } log.fine("Result table not found"); return null; } public static class Operation { private final SahiTasks tasks; private final String name; private final Editor editor; private final Logger log = Logger.getLogger(this.getClass().getName()); public Operation(SahiTasks tasks, String name) { this.tasks = tasks; this.name = name; this.editor = new Editor(tasks); tasks.waitFor(Timing.WAIT_TIME); selectOperation(this.name); } public void selectOperation(String op) { List<ElementStub> pickers = tasks.image("comboBoxPicker.png").collectSimilar(); log.fine("Found " + pickers.size() + " comboboxes"); for (ElementStub picker : pickers) { if (picker.isVisible()) { log.fine("Clicking on " + picker.parentNode().fetch("innerHTML")); tasks.xy(picker.parentNode(), 3, 3).click(); ElementStub operation = tasks.row(op); if (operation.exists()) { tasks.xy(operation, 3, 3).click(); log.fine("Selected operation [" + op + "]."); return; } else { log.fine("Trying workaround with focused picker"); ElementStub focused = tasks.image("comboBoxPicker_Over.png"); if (focused.isVisible()) { log.fine("Focused picker was visible, clicking..."); tasks.xy(focused, 3, 3).click(); operation = tasks.row(op); if (operation.exists()) { tasks.xy(operation, 3, 3).click(); log.fine("Selected operation [" + op + "]."); return; } } } } } throw new RuntimeException("Unable to select operation [" + op + "] clicked on each visible combo, but operation did NOT pop up"); } /** * asserts all required input fields have been filled */ public void assertRequiredInputs() { getEditor().assertRequiredInputs(); } public Editor getEditor() { return editor; } /** * clicks <b>Schedule</b> button to start operation */ public void schedule() { tasks.cell("Schedule").click(); tasks.waitFor(Timing.WAIT_TIME); } } }
true
true
public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().summary(); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); getResource().summary(); } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).doubleClick(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest(el.fetch()); } if (headerCells.size() > 1) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 3) + " result rows"); log.finest("The rows are: " + rows.toString()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); log.fine("Found result property [" + key.getText() + "]"); result.put(key.getText(), value.getText()); } return result; } log.fine("Result table not found"); return null; }
public Map<String, String> assertOperationResult(Operation op, boolean success) { String opName = op.name; String resultImage = "Operation_failed_16.png"; String succ = "Failed"; if (success) { resultImage = "Operation_ok_16.png"; succ = "Success"; } log.fine("Asserting operation [" + opName + "] result, expecting " + succ); getResource().summary(); int timeout = 20 * Timing.TIME_1M; int time = 0; while (time < timeout && tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { time += Timing.TIME_10S; log.fine("Operation [" + opName + "] in progress, waiting " + Timing.toString(Timing.TIME_10S)); tasks.waitFor(Timing.TIME_10S); getResource().summary(); } if (tasks.image("Operation_inprogress_16.png").in(tasks.div(opName + "[0]").parentNode("tr")).exists()) { log.info("Operation [" + opName + "] did NOT finish after " + Timing.toString(time) + "!!!"); Assert.assertEquals(!success, success, "Operation [" + opName + "] result: " + succ); } else { log.info("Operation [" + opName + "] finished after " + Timing.toString(time)); } boolean existsImage = tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).exists(); // when operation failed and success was expected, let's get operation error message if (!existsImage && success) { String message = null; tasks.xy(tasks.image("Operation_failed_16.png").in(tasks.div(opName + "[0]").parentNode("tr")), 3, 3).click(); if (tasks.preformatted("").exists()) { message = tasks.preformatted("").getText(); } tasks.waitFor(Timing.WAIT_TIME); int buttons = tasks.image("close.png").countSimilar(); tasks.xy(tasks.image("close.png[" + (buttons - 1) + "]"), 3, 3).click(); if (message != null) { Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ + " errorMessage:\n" + message); return null; } } Assert.assertTrue(existsImage, "Operation [" + opName + "] result: " + succ); log.fine("Getting operation result"); tasks.image(resultImage).in(tasks.div(opName + "[0]").parentNode("tr")).doubleClick(); log.finest("The property element: " + tasks.cell("Property").fetch()); List<ElementStub> headerCells = tasks.cell("Property").collectSimilar(); for (ElementStub el : headerCells) { log.finest(el.fetch()); } if (headerCells.size() > 1) { Map<String, String> result = new HashMap<String, String>(); ElementStub table = headerCells.get(headerCells.size() - 1).parentNode("table"); log.finer("Table element is " + table.toString()); List<ElementStub> rows = tasks.row("").in(table).collectSimilar(); // starting with 3rd row, because 1st some shit and 2nd is table header // we also ignore last because sahi was failing log.fine("Have " + (rows.size() - 3) + " result rows"); log.finest("The rows are: " + rows.toString()); for (int i = 2; i < rows.size(); i++) { ElementStub row = rows.get(i); ElementStub key = tasks.cell(0).in(row); ElementStub value = tasks.cell(2).in(row); if (key.exists() && value.exists()) { log.fine("Found result property [" + key.getText() + "]"); result.put(key.getText(), value.getText()); } else { log.warning("Missing key or value column in the results table - probably caused by nonstandard result output"); } } return result; } log.fine("Result table not found"); return null; }
diff --git a/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageConsumer.java b/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageConsumer.java index c1ce5cb30..492985fb4 100755 --- a/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageConsumer.java +++ b/activemq-core/src/main/java/org/apache/activemq/ActiveMQMessageConsumer.java @@ -1,1429 +1,1429 @@ /** * 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; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.jms.IllegalStateException; import javax.jms.InvalidDestinationException; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.TransactionRolledBackException; import org.apache.activemq.blob.BlobDownloader; import org.apache.activemq.command.ActiveMQBlobMessage; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQTempDestination; import org.apache.activemq.command.CommandTypes; import org.apache.activemq.command.ConsumerId; import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.MessagePull; import org.apache.activemq.command.RemoveInfo; import org.apache.activemq.command.TransactionId; import org.apache.activemq.management.JMSConsumerStatsImpl; import org.apache.activemq.management.StatsCapable; import org.apache.activemq.management.StatsImpl; import org.apache.activemq.selector.SelectorParser; import org.apache.activemq.thread.Scheduler; import org.apache.activemq.transaction.Synchronization; import org.apache.activemq.util.Callback; import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.JMSExceptionSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A client uses a <CODE>MessageConsumer</CODE> object to receive messages * from a destination. A <CODE> MessageConsumer</CODE> object is created by * passing a <CODE>Destination</CODE> object to a message-consumer creation * method supplied by a session. * <P> * <CODE>MessageConsumer</CODE> is the parent interface for all message * consumers. * <P> * A message consumer can be created with a message selector. A message selector * allows the client to restrict the messages delivered to the message consumer * to those that match the selector. * <P> * A client may either synchronously receive a message consumer's messages or * have the consumer asynchronously deliver them as they arrive. * <P> * For synchronous receipt, a client can request the next message from a message * consumer using one of its <CODE> receive</CODE> methods. There are several * variations of <CODE>receive</CODE> that allow a client to poll or wait for * the next message. * <P> * For asynchronous delivery, a client can register a * <CODE>MessageListener</CODE> object with a message consumer. As messages * arrive at the message consumer, it delivers them by calling the * <CODE>MessageListener</CODE>'s<CODE> * onMessage</CODE> method. * <P> * It is a client programming error for a <CODE>MessageListener</CODE> to * throw an exception. * * * @see javax.jms.MessageConsumer * @see javax.jms.QueueReceiver * @see javax.jms.TopicSubscriber * @see javax.jms.Session */ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsCapable, ActiveMQDispatcher { @SuppressWarnings("serial") class PreviouslyDeliveredMap<K, V> extends HashMap<K, V> { final TransactionId transactionId; public PreviouslyDeliveredMap(TransactionId transactionId) { this.transactionId = transactionId; } } private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageConsumer.class); protected final Scheduler scheduler; protected final ActiveMQSession session; protected final ConsumerInfo info; // These are the messages waiting to be delivered to the client protected final MessageDispatchChannel unconsumedMessages; // The are the messages that were delivered to the consumer but that have // not been acknowledged. It's kept in reverse order since we // Always walk list in reverse order. private final LinkedList<MessageDispatch> deliveredMessages = new LinkedList<MessageDispatch>(); // track duplicate deliveries in a transaction such that the tx integrity can be validated private PreviouslyDeliveredMap<MessageId, Boolean> previouslyDeliveredMessages; private int deliveredCounter; private int additionalWindowSize; private long redeliveryDelay; private int ackCounter; private int dispatchedCount; private final AtomicReference<MessageListener> messageListener = new AtomicReference<MessageListener>(); private final JMSConsumerStatsImpl stats; private final String selector; private boolean synchronizationRegistered; private final AtomicBoolean started = new AtomicBoolean(false); private MessageAvailableListener availableListener; private RedeliveryPolicy redeliveryPolicy; private boolean optimizeAcknowledge; private final AtomicBoolean deliveryingAcknowledgements = new AtomicBoolean(); private ExecutorService executorService; private MessageTransformer transformer; private boolean clearDispatchList; boolean inProgressClearRequiredFlag; private MessageAck pendingAck; private long lastDeliveredSequenceId; private IOException failureError; private long optimizeAckTimestamp = System.currentTimeMillis(); private long optimizeAcknowledgeTimeOut = 0; private long failoverRedeliveryWaitPeriod = 0; private boolean transactedIndividualAck = false; /** * Create a MessageConsumer * * @param session * @param dest * @param name * @param selector * @param prefetch * @param maximumPendingMessageCount * @param noLocal * @param browser * @param dispatchAsync * @param messageListener * @throws JMSException */ public ActiveMQMessageConsumer(ActiveMQSession session, ConsumerId consumerId, ActiveMQDestination dest, String name, String selector, int prefetch, int maximumPendingMessageCount, boolean noLocal, boolean browser, boolean dispatchAsync, MessageListener messageListener) throws JMSException { if (dest == null) { throw new InvalidDestinationException("Don't understand null destinations"); } else if (dest.getPhysicalName() == null) { throw new InvalidDestinationException("The destination object was not given a physical name."); } else if (dest.isTemporary()) { String physicalName = dest.getPhysicalName(); if (physicalName == null) { throw new IllegalArgumentException("Physical name of Destination should be valid: " + dest); } String connectionID = session.connection.getConnectionInfo().getConnectionId().getValue(); if (physicalName.indexOf(connectionID) < 0) { throw new InvalidDestinationException( "Cannot use a Temporary destination from another Connection"); } if (session.connection.isDeleted(dest)) { throw new InvalidDestinationException( "Cannot use a Temporary destination that has been deleted"); } if (prefetch < 0) { throw new JMSException("Cannot have a prefetch size less than zero"); } } if (session.connection.isMessagePrioritySupported()) { this.unconsumedMessages = new SimplePriorityMessageDispatchChannel(); }else { this.unconsumedMessages = new FifoMessageDispatchChannel(); } this.session = session; this.scheduler = session.getScheduler(); this.redeliveryPolicy = session.connection.getRedeliveryPolicy(); setTransformer(session.getTransformer()); this.info = new ConsumerInfo(consumerId); this.info.setExclusive(this.session.connection.isExclusiveConsumer()); this.info.setSubscriptionName(name); this.info.setPrefetchSize(prefetch); this.info.setCurrentPrefetchSize(prefetch); this.info.setMaximumPendingMessageLimit(maximumPendingMessageCount); this.info.setNoLocal(noLocal); this.info.setDispatchAsync(dispatchAsync); this.info.setRetroactive(this.session.connection.isUseRetroactiveConsumer()); this.info.setSelector(null); // Allows the options on the destination to configure the consumerInfo if (dest.getOptions() != null) { - Map<String, Object> options = IntrospectionSupport.extractProperties(dest.getOptions(), "producer."); + Map<String, Object> options = IntrospectionSupport.extractProperties(dest.getOptions(), "consumer."); IntrospectionSupport.setProperties(this.info, options); if (options.size() > 0) { String msg = "There are " + options.size() + " consumer options that couldn't be set on the consumer." + " Check the options are spelled correctly." + " Unknown parameters=[" + options + "]." + " This consumer cannot be started."; LOG.warn(msg); throw new ConfigurationException(msg); } } this.info.setDestination(dest); this.info.setBrowser(browser); if (selector != null && selector.trim().length() != 0) { // Validate the selector SelectorParser.parse(selector); this.info.setSelector(selector); this.selector = selector; } else if (info.getSelector() != null) { // Validate the selector SelectorParser.parse(this.info.getSelector()); this.selector = this.info.getSelector(); } else { this.selector = null; } this.stats = new JMSConsumerStatsImpl(session.getSessionStats(), dest); this.optimizeAcknowledge = session.connection.isOptimizeAcknowledge() && session.isAutoAcknowledge() && !info.isBrowser(); if (this.optimizeAcknowledge) { this.optimizeAcknowledgeTimeOut = session.connection.getOptimizeAcknowledgeTimeOut(); } this.info.setOptimizedAcknowledge(this.optimizeAcknowledge); this.failoverRedeliveryWaitPeriod = session.connection.getConsumerFailoverRedeliveryWaitPeriod(); this.transactedIndividualAck = session.connection.isTransactedIndividualAck(); if (messageListener != null) { setMessageListener(messageListener); } try { this.session.addConsumer(this); this.session.syncSendPacket(info); } catch (JMSException e) { this.session.removeConsumer(this); throw e; } if (session.connection.isStarted()) { start(); } } private boolean isAutoAcknowledgeEach() { return session.isAutoAcknowledge() || ( session.isDupsOkAcknowledge() && getDestination().isQueue() ); } private boolean isAutoAcknowledgeBatch() { return session.isDupsOkAcknowledge() && !getDestination().isQueue() ; } public StatsImpl getStats() { return stats; } public JMSConsumerStatsImpl getConsumerStats() { return stats; } public RedeliveryPolicy getRedeliveryPolicy() { return redeliveryPolicy; } /** * Sets the redelivery policy used when messages are redelivered */ public void setRedeliveryPolicy(RedeliveryPolicy redeliveryPolicy) { this.redeliveryPolicy = redeliveryPolicy; } public MessageTransformer getTransformer() { return transformer; } /** * Sets the transformer used to transform messages before they are sent on * to the JMS bus */ public void setTransformer(MessageTransformer transformer) { this.transformer = transformer; } /** * @return Returns the value. */ public ConsumerId getConsumerId() { return info.getConsumerId(); } /** * @return the consumer name - used for durable consumers */ public String getConsumerName() { return this.info.getSubscriptionName(); } /** * @return true if this consumer does not accept locally produced messages */ protected boolean isNoLocal() { return info.isNoLocal(); } /** * Retrieve is a browser * * @return true if a browser */ protected boolean isBrowser() { return info.isBrowser(); } /** * @return ActiveMQDestination */ protected ActiveMQDestination getDestination() { return info.getDestination(); } /** * @return Returns the prefetchNumber. */ public int getPrefetchNumber() { return info.getPrefetchSize(); } /** * @return true if this is a durable topic subscriber */ public boolean isDurableSubscriber() { return info.getSubscriptionName() != null && info.getDestination().isTopic(); } /** * Gets this message consumer's message selector expression. * * @return this message consumer's message selector, or null if no message * selector exists for the message consumer (that is, if the message * selector was not set or was set to null or the empty string) * @throws JMSException if the JMS provider fails to receive the next * message due to some internal error. */ public String getMessageSelector() throws JMSException { checkClosed(); return selector; } /** * Gets the message consumer's <CODE>MessageListener</CODE>. * * @return the listener for the message consumer, or null if no listener is * set * @throws JMSException if the JMS provider fails to get the message * listener due to some internal error. * @see javax.jms.MessageConsumer#setMessageListener(javax.jms.MessageListener) */ public MessageListener getMessageListener() throws JMSException { checkClosed(); return this.messageListener.get(); } /** * Sets the message consumer's <CODE>MessageListener</CODE>. * <P> * Setting the message listener to null is the equivalent of unsetting the * message listener for the message consumer. * <P> * The effect of calling <CODE>MessageConsumer.setMessageListener</CODE> * while messages are being consumed by an existing listener or the consumer * is being used to consume messages synchronously is undefined. * * @param listener the listener to which the messages are to be delivered * @throws JMSException if the JMS provider fails to receive the next * message due to some internal error. * @see javax.jms.MessageConsumer#getMessageListener */ public void setMessageListener(MessageListener listener) throws JMSException { checkClosed(); if (info.getPrefetchSize() == 0) { throw new JMSException( "Illegal prefetch size of zero. This setting is not supported for asynchronous consumers please set a value of at least 1"); } if (listener != null) { boolean wasRunning = session.isRunning(); if (wasRunning) { session.stop(); } this.messageListener.set(listener); session.redispatch(this, unconsumedMessages); if (wasRunning) { session.start(); } } else { this.messageListener.set(null); } } public MessageAvailableListener getAvailableListener() { return availableListener; } /** * Sets the listener used to notify synchronous consumers that there is a * message available so that the {@link MessageConsumer#receiveNoWait()} can * be called. */ public void setAvailableListener(MessageAvailableListener availableListener) { this.availableListener = availableListener; } /** * Used to get an enqueued message from the unconsumedMessages list. The * amount of time this method blocks is based on the timeout value. - if * timeout==-1 then it blocks until a message is received. - if timeout==0 * then it it tries to not block at all, it returns a message if it is * available - if timeout>0 then it blocks up to timeout amount of time. * Expired messages will consumed by this method. * * @throws JMSException * @return null if we timeout or if the consumer is closed. */ private MessageDispatch dequeue(long timeout) throws JMSException { try { long deadline = 0; if (timeout > 0) { deadline = System.currentTimeMillis() + timeout; } while (true) { MessageDispatch md = unconsumedMessages.dequeue(timeout); if (md == null) { if (timeout > 0 && !unconsumedMessages.isClosed()) { timeout = Math.max(deadline - System.currentTimeMillis(), 0); } else { if (failureError != null) { throw JMSExceptionSupport.create(failureError); } else { return null; } } } else if (md.getMessage() == null) { return null; } else if (md.getMessage().isExpired()) { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " received expired message: " + md); } beforeMessageIsConsumed(md); afterMessageIsConsumed(md, true); if (timeout > 0) { timeout = Math.max(deadline - System.currentTimeMillis(), 0); } } else { if (LOG.isTraceEnabled()) { LOG.trace(getConsumerId() + " received message: " + md); } return md; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw JMSExceptionSupport.create(e); } } /** * Receives the next message produced for this message consumer. * <P> * This call blocks indefinitely until a message is produced or until this * message consumer is closed. * <P> * If this <CODE>receive</CODE> is done within a transaction, the consumer * retains the message until the transaction commits. * * @return the next message produced for this message consumer, or null if * this message consumer is concurrently closed */ public Message receive() throws JMSException { checkClosed(); checkMessageListener(); sendPullCommand(0); MessageDispatch md = dequeue(-1); if (md == null) { return null; } beforeMessageIsConsumed(md); afterMessageIsConsumed(md, false); return createActiveMQMessage(md); } /** * @param md * @return */ private ActiveMQMessage createActiveMQMessage(final MessageDispatch md) throws JMSException { ActiveMQMessage m = (ActiveMQMessage)md.getMessage().copy(); if (m.getDataStructureType()==CommandTypes.ACTIVEMQ_BLOB_MESSAGE) { ((ActiveMQBlobMessage)m).setBlobDownloader(new BlobDownloader(session.getBlobTransferPolicy())); } if (transformer != null) { Message transformedMessage = transformer.consumerTransform(session, this, m); if (transformedMessage != null) { m = ActiveMQMessageTransformation.transformMessage(transformedMessage, session.connection); } } if (session.isClientAcknowledge()) { m.setAcknowledgeCallback(new Callback() { public void execute() throws Exception { session.checkClosed(); session.acknowledge(); } }); }else if (session.isIndividualAcknowledge()) { m.setAcknowledgeCallback(new Callback() { public void execute() throws Exception { session.checkClosed(); acknowledge(md); } }); } return m; } /** * Receives the next message that arrives within the specified timeout * interval. * <P> * This call blocks until a message arrives, the timeout expires, or this * message consumer is closed. A <CODE>timeout</CODE> of zero never * expires, and the call blocks indefinitely. * * @param timeout the timeout value (in milliseconds), a time out of zero * never expires. * @return the next message produced for this message consumer, or null if * the timeout expires or this message consumer is concurrently * closed */ public Message receive(long timeout) throws JMSException { checkClosed(); checkMessageListener(); if (timeout == 0) { return this.receive(); } sendPullCommand(timeout); while (timeout > 0) { MessageDispatch md; if (info.getPrefetchSize() == 0) { md = dequeue(-1); // We let the broker let us know when we timeout. } else { md = dequeue(timeout); } if (md == null) { return null; } beforeMessageIsConsumed(md); afterMessageIsConsumed(md, false); return createActiveMQMessage(md); } return null; } /** * Receives the next message if one is immediately available. * * @return the next message produced for this message consumer, or null if * one is not available * @throws JMSException if the JMS provider fails to receive the next * message due to some internal error. */ public Message receiveNoWait() throws JMSException { checkClosed(); checkMessageListener(); sendPullCommand(-1); MessageDispatch md; if (info.getPrefetchSize() == 0) { md = dequeue(-1); // We let the broker let us know when we // timeout. } else { md = dequeue(0); } if (md == null) { return null; } beforeMessageIsConsumed(md); afterMessageIsConsumed(md, false); return createActiveMQMessage(md); } /** * Closes the message consumer. * <P> * Since a provider may allocate some resources on behalf of a <CODE> * MessageConsumer</CODE> * outside the Java virtual machine, clients should close them when they are * not needed. Relying on garbage collection to eventually reclaim these * resources may not be timely enough. * <P> * This call blocks until a <CODE>receive</CODE> or message listener in * progress has completed. A blocked message consumer <CODE>receive </CODE> * call returns null when this message consumer is closed. * * @throws JMSException if the JMS provider fails to close the consumer due * to some internal error. */ public void close() throws JMSException { if (!unconsumedMessages.isClosed()) { if (session.getTransactionContext().isInTransaction()) { session.getTransactionContext().addSynchronization(new Synchronization() { @Override public void afterCommit() throws Exception { doClose(); } @Override public void afterRollback() throws Exception { doClose(); } }); } else { doClose(); } } } void doClose() throws JMSException { dispose(); RemoveInfo removeCommand = info.createRemoveCommand(); if (LOG.isDebugEnabled()) { LOG.debug("remove: " + this.getConsumerId() + ", lastDeliveredSequenceId:" + lastDeliveredSequenceId); } removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId); this.session.asyncSendPacket(removeCommand); } void inProgressClearRequired() { inProgressClearRequiredFlag = true; // deal with delivered messages async to avoid lock contention with in progress acks clearDispatchList = true; } void clearMessagesInProgress() { if (inProgressClearRequiredFlag) { synchronized (unconsumedMessages.getMutex()) { if (inProgressClearRequiredFlag) { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " clearing unconsumed list (" + unconsumedMessages.size() + ") on transport interrupt"); } // ensure unconsumed are rolledback up front as they may get redelivered to another consumer List<MessageDispatch> list = unconsumedMessages.removeAll(); if (!this.info.isBrowser()) { for (MessageDispatch old : list) { session.connection.rollbackDuplicate(this, old.getMessage()); } } // allow dispatch on this connection to resume session.connection.transportInterruptionProcessingComplete(); inProgressClearRequiredFlag = false; } } } } void deliverAcks() { MessageAck ack = null; if (deliveryingAcknowledgements.compareAndSet(false, true)) { if (isAutoAcknowledgeEach()) { synchronized(deliveredMessages) { ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); if (ack != null) { deliveredMessages.clear(); ackCounter = 0; } else { ack = pendingAck; pendingAck = null; } } } else if (pendingAck != null && pendingAck.isStandardAck()) { ack = pendingAck; pendingAck = null; } if (ack != null) { final MessageAck ackToSend = ack; if (executorService == null) { executorService = Executors.newSingleThreadExecutor(); } executorService.submit(new Runnable() { public void run() { try { session.sendAck(ackToSend,true); } catch (JMSException e) { LOG.error(getConsumerId() + " failed to delivered acknowledgements", e); } finally { deliveryingAcknowledgements.set(false); } } }); } else { deliveryingAcknowledgements.set(false); } } } public void dispose() throws JMSException { if (!unconsumedMessages.isClosed()) { // Do we have any acks we need to send out before closing? // Ack any delivered messages now. if (!session.getTransacted()) { deliverAcks(); if (isAutoAcknowledgeBatch()) { acknowledge(); } } if (executorService != null) { executorService.shutdown(); try { executorService.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (session.isClientAcknowledge()) { if (!this.info.isBrowser()) { // rollback duplicates that aren't acknowledged List<MessageDispatch> tmp = null; synchronized (this.deliveredMessages) { tmp = new ArrayList<MessageDispatch>(this.deliveredMessages); } for (MessageDispatch old : tmp) { this.session.connection.rollbackDuplicate(this, old.getMessage()); } tmp.clear(); } } if (!session.isTransacted()) { synchronized(deliveredMessages) { deliveredMessages.clear(); } } unconsumedMessages.close(); this.session.removeConsumer(this); List<MessageDispatch> list = unconsumedMessages.removeAll(); if (!this.info.isBrowser()) { for (MessageDispatch old : list) { // ensure we don't filter this as a duplicate session.connection.rollbackDuplicate(this, old.getMessage()); } } } } /** * @throws IllegalStateException */ protected void checkClosed() throws IllegalStateException { if (unconsumedMessages.isClosed()) { throw new IllegalStateException("The Consumer is closed"); } } /** * If we have a zero prefetch specified then send a pull command to the * broker to pull a message we are about to receive */ protected void sendPullCommand(long timeout) throws JMSException { clearDispatchList(); if (info.getPrefetchSize() == 0 && unconsumedMessages.isEmpty()) { MessagePull messagePull = new MessagePull(); messagePull.configure(info); messagePull.setTimeout(timeout); session.asyncSendPacket(messagePull); } } protected void checkMessageListener() throws JMSException { session.checkMessageListener(); } protected void setOptimizeAcknowledge(boolean value) { if (optimizeAcknowledge && !value) { deliverAcks(); } optimizeAcknowledge = value; } protected void setPrefetchSize(int prefetch) { deliverAcks(); this.info.setCurrentPrefetchSize(prefetch); } private void beforeMessageIsConsumed(MessageDispatch md) throws JMSException { md.setDeliverySequenceId(session.getNextDeliveryId()); lastDeliveredSequenceId = md.getMessage().getMessageId().getBrokerSequenceId(); if (!isAutoAcknowledgeBatch()) { synchronized(deliveredMessages) { deliveredMessages.addFirst(md); } if (session.getTransacted()) { if (transactedIndividualAck) { immediateIndividualTransactedAck(md); } else { ackLater(md, MessageAck.DELIVERED_ACK_TYPE); } } } } private void immediateIndividualTransactedAck(MessageDispatch md) throws JMSException { // acks accumulate on the broker pending transaction completion to indicate // delivery status registerSync(); MessageAck ack = new MessageAck(md, MessageAck.INDIVIDUAL_ACK_TYPE, 1); ack.setTransactionId(session.getTransactionContext().getTransactionId()); session.sendAck(ack); } private void afterMessageIsConsumed(MessageDispatch md, boolean messageExpired) throws JMSException { if (unconsumedMessages.isClosed()) { return; } if (messageExpired) { synchronized (deliveredMessages) { deliveredMessages.remove(md); } stats.getExpiredMessageCount().increment(); ackLater(md, MessageAck.DELIVERED_ACK_TYPE); } else { stats.onMessage(); if (session.getTransacted()) { // Do nothing. } else if (isAutoAcknowledgeEach()) { if (deliveryingAcknowledgements.compareAndSet(false, true)) { synchronized (deliveredMessages) { if (!deliveredMessages.isEmpty()) { if (optimizeAcknowledge) { ackCounter++; if (ackCounter >= (info.getPrefetchSize() * .65) || (optimizeAcknowledgeTimeOut > 0 && System.currentTimeMillis() >= (optimizeAckTimestamp + optimizeAcknowledgeTimeOut))) { MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); if (ack != null) { deliveredMessages.clear(); ackCounter = 0; session.sendAck(ack); optimizeAckTimestamp = System.currentTimeMillis(); } } } else { MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); if (ack!=null) { deliveredMessages.clear(); session.sendAck(ack); } } } } deliveryingAcknowledgements.set(false); } } else if (isAutoAcknowledgeBatch()) { ackLater(md, MessageAck.STANDARD_ACK_TYPE); } else if (session.isClientAcknowledge()||session.isIndividualAcknowledge()) { boolean messageUnackedByConsumer = false; synchronized (deliveredMessages) { messageUnackedByConsumer = deliveredMessages.contains(md); } if (messageUnackedByConsumer) { ackLater(md, MessageAck.DELIVERED_ACK_TYPE); } } else { throw new IllegalStateException("Invalid session state."); } } } /** * Creates a MessageAck for all messages contained in deliveredMessages. * Caller should hold the lock for deliveredMessages. * * @param type Ack-Type (i.e. MessageAck.STANDARD_ACK_TYPE) * @return <code>null</code> if nothing to ack. */ private MessageAck makeAckForAllDeliveredMessages(byte type) { synchronized (deliveredMessages) { if (deliveredMessages.isEmpty()) return null; MessageDispatch md = deliveredMessages.getFirst(); MessageAck ack = new MessageAck(md, type, deliveredMessages.size()); ack.setFirstMessageId(deliveredMessages.getLast().getMessage().getMessageId()); return ack; } } private void ackLater(MessageDispatch md, byte ackType) throws JMSException { // Don't acknowledge now, but we may need to let the broker know the // consumer got the message to expand the pre-fetch window if (session.getTransacted()) { registerSync(); } deliveredCounter++; MessageAck oldPendingAck = pendingAck; pendingAck = new MessageAck(md, ackType, deliveredCounter); pendingAck.setTransactionId(session.getTransactionContext().getTransactionId()); if( oldPendingAck==null ) { pendingAck.setFirstMessageId(pendingAck.getLastMessageId()); } else if ( oldPendingAck.getAckType() == pendingAck.getAckType() ) { pendingAck.setFirstMessageId(oldPendingAck.getFirstMessageId()); } else { // old pending ack being superseded by ack of another type, if is is not a delivered // ack and hence important, send it now so it is not lost. if ( !oldPendingAck.isDeliveredAck()) { if (LOG.isDebugEnabled()) { LOG.debug("Sending old pending ack " + oldPendingAck + ", new pending: " + pendingAck); } session.sendAck(oldPendingAck); } else { if (LOG.isDebugEnabled()) { LOG.debug("dropping old pending ack " + oldPendingAck + ", new pending: " + pendingAck); } } } if ((0.5 * info.getPrefetchSize()) <= (deliveredCounter - additionalWindowSize)) { session.sendAck(pendingAck); pendingAck=null; deliveredCounter = 0; additionalWindowSize = 0; } } private void registerSync() throws JMSException { session.doStartTransaction(); if (!synchronizationRegistered) { synchronizationRegistered = true; session.getTransactionContext().addSynchronization(new Synchronization() { @Override public void beforeEnd() throws Exception { if (transactedIndividualAck) { clearDispatchList(); waitForRedeliveries(); synchronized(deliveredMessages) { rollbackOnFailedRecoveryRedelivery(); } } else { acknowledge(); } synchronizationRegistered = false; } @Override public void afterCommit() throws Exception { commit(); synchronizationRegistered = false; } @Override public void afterRollback() throws Exception { rollback(); synchronizationRegistered = false; } }); } } /** * Acknowledge all the messages that have been delivered to the client up to * this point. * * @throws JMSException */ public void acknowledge() throws JMSException { clearDispatchList(); waitForRedeliveries(); synchronized(deliveredMessages) { // Acknowledge all messages so far. MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); if (ack == null) return; // no msgs if (session.getTransacted()) { rollbackOnFailedRecoveryRedelivery(); session.doStartTransaction(); ack.setTransactionId(session.getTransactionContext().getTransactionId()); } session.sendAck(ack); pendingAck = null; // Adjust the counters deliveredCounter = Math.max(0, deliveredCounter - deliveredMessages.size()); additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size()); if (!session.getTransacted()) { deliveredMessages.clear(); } } } private void waitForRedeliveries() { if (failoverRedeliveryWaitPeriod > 0 && previouslyDeliveredMessages != null) { long expiry = System.currentTimeMillis() + failoverRedeliveryWaitPeriod; int numberNotReplayed; do { numberNotReplayed = 0; synchronized(deliveredMessages) { if (previouslyDeliveredMessages != null) { for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) { if (!entry.getValue()) { numberNotReplayed++; } } } } if (numberNotReplayed > 0) { LOG.info("waiting for redelivery of " + numberNotReplayed + " in transaction: " + previouslyDeliveredMessages.transactionId + ", to consumer :" + this.getConsumerId()); try { Thread.sleep(Math.max(500, failoverRedeliveryWaitPeriod/4)); } catch (InterruptedException outOfhere) { break; } } } while (numberNotReplayed > 0 && expiry < System.currentTimeMillis()); } } /* * called with deliveredMessages locked */ private void rollbackOnFailedRecoveryRedelivery() throws JMSException { if (previouslyDeliveredMessages != null) { // if any previously delivered messages was not re-delivered, transaction is invalid and must rollback // as messages have been dispatched else where. int numberNotReplayed = 0; for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) { if (!entry.getValue()) { numberNotReplayed++; if (LOG.isDebugEnabled()) { LOG.debug("previously delivered message has not been replayed in transaction: " + previouslyDeliveredMessages.transactionId + " , messageId: " + entry.getKey()); } } } if (numberNotReplayed > 0) { String message = "rolling back transaction (" + previouslyDeliveredMessages.transactionId + ") post failover recovery. " + numberNotReplayed + " previously delivered message(s) not replayed to consumer: " + this.getConsumerId(); LOG.warn(message); throw new TransactionRolledBackException(message); } } } void acknowledge(MessageDispatch md) throws JMSException { MessageAck ack = new MessageAck(md,MessageAck.INDIVIDUAL_ACK_TYPE,1); session.sendAck(ack); synchronized(deliveredMessages){ deliveredMessages.remove(md); } } public void commit() throws JMSException { synchronized (deliveredMessages) { deliveredMessages.clear(); clearPreviouslyDelivered(); } redeliveryDelay = 0; } public void rollback() throws JMSException { synchronized (unconsumedMessages.getMutex()) { if (optimizeAcknowledge) { // remove messages read but not acked at the broker yet through // optimizeAcknowledge if (!this.info.isBrowser()) { synchronized(deliveredMessages) { for (int i = 0; (i < deliveredMessages.size()) && (i < ackCounter); i++) { // ensure we don't filter this as a duplicate MessageDispatch md = deliveredMessages.removeLast(); session.connection.rollbackDuplicate(this, md.getMessage()); } } } } synchronized(deliveredMessages) { rollbackPreviouslyDeliveredAndNotRedelivered(); if (deliveredMessages.isEmpty()) { return; } // use initial delay for first redelivery MessageDispatch lastMd = deliveredMessages.getFirst(); final int currentRedeliveryCount = lastMd.getMessage().getRedeliveryCounter(); if (currentRedeliveryCount > 0) { redeliveryDelay = redeliveryPolicy.getNextRedeliveryDelay(redeliveryDelay); } else { redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay(); } MessageId firstMsgId = deliveredMessages.getLast().getMessage().getMessageId(); for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) { MessageDispatch md = iter.next(); md.getMessage().onMessageRolledBack(); // ensure we don't filter this as a duplicate session.connection.rollbackDuplicate(this, md.getMessage()); } if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES && lastMd.getMessage().getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()) { // We need to NACK the messages so that they get sent to the // DLQ. // Acknowledge the last message. MessageAck ack = new MessageAck(lastMd, MessageAck.POSION_ACK_TYPE, deliveredMessages.size()); ack.setPoisonCause(lastMd.getRollbackCause()); ack.setFirstMessageId(firstMsgId); session.sendAck(ack,true); // Adjust the window size. additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size()); redeliveryDelay = 0; } else { // only redelivery_ack after first delivery if (currentRedeliveryCount > 0) { MessageAck ack = new MessageAck(lastMd, MessageAck.REDELIVERED_ACK_TYPE, deliveredMessages.size()); ack.setFirstMessageId(firstMsgId); session.sendAck(ack,true); } // stop the delivery of messages. unconsumedMessages.stop(); for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) { MessageDispatch md = iter.next(); unconsumedMessages.enqueueFirst(md); } if (redeliveryDelay > 0 && !unconsumedMessages.isClosed()) { // Start up the delivery again a little later. scheduler.executeAfterDelay(new Runnable() { public void run() { try { if (started.get()) { start(); } } catch (JMSException e) { session.connection.onAsyncException(e); } } }, redeliveryDelay); } else { start(); } } deliveredCounter -= deliveredMessages.size(); deliveredMessages.clear(); } } if (messageListener.get() != null) { session.redispatch(this, unconsumedMessages); } } /* * called with unconsumedMessages && deliveredMessages locked * remove any message not re-delivered as they can't be replayed to this * consumer on rollback */ private void rollbackPreviouslyDeliveredAndNotRedelivered() { if (previouslyDeliveredMessages != null) { for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) { if (!entry.getValue()) { removeFromDeliveredMessages(entry.getKey()); } } clearPreviouslyDelivered(); } } /* * called with deliveredMessages locked */ private void removeFromDeliveredMessages(MessageId key) { Iterator<MessageDispatch> iterator = deliveredMessages.iterator(); while (iterator.hasNext()) { MessageDispatch candidate = iterator.next(); if (key.equals(candidate.getMessage().getMessageId())) { session.connection.rollbackDuplicate(this, candidate.getMessage()); iterator.remove(); break; } } } /* * called with deliveredMessages locked */ private void clearPreviouslyDelivered() { if (previouslyDeliveredMessages != null) { previouslyDeliveredMessages.clear(); previouslyDeliveredMessages = null; } } public void dispatch(MessageDispatch md) { MessageListener listener = this.messageListener.get(); try { clearMessagesInProgress(); clearDispatchList(); synchronized (unconsumedMessages.getMutex()) { if (!unconsumedMessages.isClosed()) { if (this.info.isBrowser() || !session.connection.isDuplicate(this, md.getMessage())) { if (listener != null && unconsumedMessages.isRunning()) { ActiveMQMessage message = createActiveMQMessage(md); beforeMessageIsConsumed(md); try { boolean expired = message.isExpired(); if (!expired) { listener.onMessage(message); } afterMessageIsConsumed(md, expired); } catch (RuntimeException e) { LOG.error(getConsumerId() + " Exception while processing message: " + md.getMessage().getMessageId(), e); if (isAutoAcknowledgeBatch() || isAutoAcknowledgeEach() || session.isIndividualAcknowledge()) { // schedual redelivery and possible dlq processing md.setRollbackCause(e); rollback(); } else { // Transacted or Client ack: Deliver the // next message. afterMessageIsConsumed(md, false); } } } else { if (!unconsumedMessages.isRunning()) { // delayed redelivery, ensure it can be re delivered session.connection.rollbackDuplicate(this, md.getMessage()); } unconsumedMessages.enqueue(md); if (availableListener != null) { availableListener.onMessageAvailable(this); } } } else { if (!session.isTransacted()) { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " ignoring (auto acking) duplicate: " + md.getMessage()); } MessageAck ack = new MessageAck(md, MessageAck.STANDARD_ACK_TYPE, 1); session.sendAck(ack); } else { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " tracking transacted redelivery of duplicate: " + md.getMessage()); } boolean needsPoisonAck = false; synchronized (deliveredMessages) { if (previouslyDeliveredMessages != null) { previouslyDeliveredMessages.put(md.getMessage().getMessageId(), true); } else { // delivery while pending redelivery to another consumer on the same connection // not waiting for redelivery will help here needsPoisonAck = true; } } if (needsPoisonAck) { LOG.warn("acking duplicate delivery as poison, redelivery must be pending to another" + " consumer on this connection, failoverRedeliveryWaitPeriod=" + failoverRedeliveryWaitPeriod + ". Message: " + md); MessageAck poisonAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1); poisonAck.setFirstMessageId(md.getMessage().getMessageId()); session.sendAck(poisonAck); } else { if (transactedIndividualAck) { immediateIndividualTransactedAck(md); } else { ackLater(md, MessageAck.DELIVERED_ACK_TYPE); } } } } } } if (++dispatchedCount % 1000 == 0) { dispatchedCount = 0; Thread.yield(); } } catch (Exception e) { session.connection.onClientInternalException(e); } } // async (on next call) clear or track delivered as they may be flagged as duplicates if they arrive again private void clearDispatchList() { if (clearDispatchList) { synchronized (deliveredMessages) { if (clearDispatchList) { if (!deliveredMessages.isEmpty()) { if (session.isTransacted()) { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " tracking existing transacted delivered list (" + deliveredMessages.size() + ") on transport interrupt"); } if (previouslyDeliveredMessages == null) { previouslyDeliveredMessages = new PreviouslyDeliveredMap<MessageId, Boolean>(session.getTransactionContext().getTransactionId()); } for (MessageDispatch delivered : deliveredMessages) { previouslyDeliveredMessages.put(delivered.getMessage().getMessageId(), false); } } else { if (LOG.isDebugEnabled()) { LOG.debug(getConsumerId() + " clearing delivered list (" + deliveredMessages.size() + ") on transport interrupt"); } deliveredMessages.clear(); pendingAck = null; } } clearDispatchList = false; } } } } public int getMessageSize() { return unconsumedMessages.size(); } public void start() throws JMSException { if (unconsumedMessages.isClosed()) { return; } started.set(true); unconsumedMessages.start(); session.executor.wakeup(); } public void stop() { started.set(false); unconsumedMessages.stop(); } @Override public String toString() { return "ActiveMQMessageConsumer { value=" + info.getConsumerId() + ", started=" + started.get() + " }"; } /** * Delivers a message to the message listener. * * @return * @throws JMSException */ public boolean iterate() { MessageListener listener = this.messageListener.get(); if (listener != null) { MessageDispatch md = unconsumedMessages.dequeueNoWait(); if (md != null) { dispatch(md); return true; } } return false; } public boolean isInUse(ActiveMQTempDestination destination) { return info.getDestination().equals(destination); } public long getLastDeliveredSequenceId() { return lastDeliveredSequenceId; } public IOException getFailureError() { return failureError; } public void setFailureError(IOException failureError) { this.failureError = failureError; } }
true
true
public ActiveMQMessageConsumer(ActiveMQSession session, ConsumerId consumerId, ActiveMQDestination dest, String name, String selector, int prefetch, int maximumPendingMessageCount, boolean noLocal, boolean browser, boolean dispatchAsync, MessageListener messageListener) throws JMSException { if (dest == null) { throw new InvalidDestinationException("Don't understand null destinations"); } else if (dest.getPhysicalName() == null) { throw new InvalidDestinationException("The destination object was not given a physical name."); } else if (dest.isTemporary()) { String physicalName = dest.getPhysicalName(); if (physicalName == null) { throw new IllegalArgumentException("Physical name of Destination should be valid: " + dest); } String connectionID = session.connection.getConnectionInfo().getConnectionId().getValue(); if (physicalName.indexOf(connectionID) < 0) { throw new InvalidDestinationException( "Cannot use a Temporary destination from another Connection"); } if (session.connection.isDeleted(dest)) { throw new InvalidDestinationException( "Cannot use a Temporary destination that has been deleted"); } if (prefetch < 0) { throw new JMSException("Cannot have a prefetch size less than zero"); } } if (session.connection.isMessagePrioritySupported()) { this.unconsumedMessages = new SimplePriorityMessageDispatchChannel(); }else { this.unconsumedMessages = new FifoMessageDispatchChannel(); } this.session = session; this.scheduler = session.getScheduler(); this.redeliveryPolicy = session.connection.getRedeliveryPolicy(); setTransformer(session.getTransformer()); this.info = new ConsumerInfo(consumerId); this.info.setExclusive(this.session.connection.isExclusiveConsumer()); this.info.setSubscriptionName(name); this.info.setPrefetchSize(prefetch); this.info.setCurrentPrefetchSize(prefetch); this.info.setMaximumPendingMessageLimit(maximumPendingMessageCount); this.info.setNoLocal(noLocal); this.info.setDispatchAsync(dispatchAsync); this.info.setRetroactive(this.session.connection.isUseRetroactiveConsumer()); this.info.setSelector(null); // Allows the options on the destination to configure the consumerInfo if (dest.getOptions() != null) { Map<String, Object> options = IntrospectionSupport.extractProperties(dest.getOptions(), "producer."); IntrospectionSupport.setProperties(this.info, options); if (options.size() > 0) { String msg = "There are " + options.size() + " consumer options that couldn't be set on the consumer." + " Check the options are spelled correctly." + " Unknown parameters=[" + options + "]." + " This consumer cannot be started."; LOG.warn(msg); throw new ConfigurationException(msg); } } this.info.setDestination(dest); this.info.setBrowser(browser); if (selector != null && selector.trim().length() != 0) { // Validate the selector SelectorParser.parse(selector); this.info.setSelector(selector); this.selector = selector; } else if (info.getSelector() != null) { // Validate the selector SelectorParser.parse(this.info.getSelector()); this.selector = this.info.getSelector(); } else { this.selector = null; } this.stats = new JMSConsumerStatsImpl(session.getSessionStats(), dest); this.optimizeAcknowledge = session.connection.isOptimizeAcknowledge() && session.isAutoAcknowledge() && !info.isBrowser(); if (this.optimizeAcknowledge) { this.optimizeAcknowledgeTimeOut = session.connection.getOptimizeAcknowledgeTimeOut(); } this.info.setOptimizedAcknowledge(this.optimizeAcknowledge); this.failoverRedeliveryWaitPeriod = session.connection.getConsumerFailoverRedeliveryWaitPeriod(); this.transactedIndividualAck = session.connection.isTransactedIndividualAck(); if (messageListener != null) { setMessageListener(messageListener); } try { this.session.addConsumer(this); this.session.syncSendPacket(info); } catch (JMSException e) { this.session.removeConsumer(this); throw e; } if (session.connection.isStarted()) { start(); } }
public ActiveMQMessageConsumer(ActiveMQSession session, ConsumerId consumerId, ActiveMQDestination dest, String name, String selector, int prefetch, int maximumPendingMessageCount, boolean noLocal, boolean browser, boolean dispatchAsync, MessageListener messageListener) throws JMSException { if (dest == null) { throw new InvalidDestinationException("Don't understand null destinations"); } else if (dest.getPhysicalName() == null) { throw new InvalidDestinationException("The destination object was not given a physical name."); } else if (dest.isTemporary()) { String physicalName = dest.getPhysicalName(); if (physicalName == null) { throw new IllegalArgumentException("Physical name of Destination should be valid: " + dest); } String connectionID = session.connection.getConnectionInfo().getConnectionId().getValue(); if (physicalName.indexOf(connectionID) < 0) { throw new InvalidDestinationException( "Cannot use a Temporary destination from another Connection"); } if (session.connection.isDeleted(dest)) { throw new InvalidDestinationException( "Cannot use a Temporary destination that has been deleted"); } if (prefetch < 0) { throw new JMSException("Cannot have a prefetch size less than zero"); } } if (session.connection.isMessagePrioritySupported()) { this.unconsumedMessages = new SimplePriorityMessageDispatchChannel(); }else { this.unconsumedMessages = new FifoMessageDispatchChannel(); } this.session = session; this.scheduler = session.getScheduler(); this.redeliveryPolicy = session.connection.getRedeliveryPolicy(); setTransformer(session.getTransformer()); this.info = new ConsumerInfo(consumerId); this.info.setExclusive(this.session.connection.isExclusiveConsumer()); this.info.setSubscriptionName(name); this.info.setPrefetchSize(prefetch); this.info.setCurrentPrefetchSize(prefetch); this.info.setMaximumPendingMessageLimit(maximumPendingMessageCount); this.info.setNoLocal(noLocal); this.info.setDispatchAsync(dispatchAsync); this.info.setRetroactive(this.session.connection.isUseRetroactiveConsumer()); this.info.setSelector(null); // Allows the options on the destination to configure the consumerInfo if (dest.getOptions() != null) { Map<String, Object> options = IntrospectionSupport.extractProperties(dest.getOptions(), "consumer."); IntrospectionSupport.setProperties(this.info, options); if (options.size() > 0) { String msg = "There are " + options.size() + " consumer options that couldn't be set on the consumer." + " Check the options are spelled correctly." + " Unknown parameters=[" + options + "]." + " This consumer cannot be started."; LOG.warn(msg); throw new ConfigurationException(msg); } } this.info.setDestination(dest); this.info.setBrowser(browser); if (selector != null && selector.trim().length() != 0) { // Validate the selector SelectorParser.parse(selector); this.info.setSelector(selector); this.selector = selector; } else if (info.getSelector() != null) { // Validate the selector SelectorParser.parse(this.info.getSelector()); this.selector = this.info.getSelector(); } else { this.selector = null; } this.stats = new JMSConsumerStatsImpl(session.getSessionStats(), dest); this.optimizeAcknowledge = session.connection.isOptimizeAcknowledge() && session.isAutoAcknowledge() && !info.isBrowser(); if (this.optimizeAcknowledge) { this.optimizeAcknowledgeTimeOut = session.connection.getOptimizeAcknowledgeTimeOut(); } this.info.setOptimizedAcknowledge(this.optimizeAcknowledge); this.failoverRedeliveryWaitPeriod = session.connection.getConsumerFailoverRedeliveryWaitPeriod(); this.transactedIndividualAck = session.connection.isTransactedIndividualAck(); if (messageListener != null) { setMessageListener(messageListener); } try { this.session.addConsumer(this); this.session.syncSendPacket(info); } catch (JMSException e) { this.session.removeConsumer(this); throw e; } if (session.connection.isStarted()) { start(); } }
diff --git a/src/main/java/hudson/plugins/phing/PhingBuilder.java b/src/main/java/hudson/plugins/phing/PhingBuilder.java index d7b16b2..47ebee0 100644 --- a/src/main/java/hudson/plugins/phing/PhingBuilder.java +++ b/src/main/java/hudson/plugins/phing/PhingBuilder.java @@ -1,267 +1,267 @@ /* * The MIT License * * Copyright (c) 2008-2011, Jenkins project, Seiji Sogabe * * 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.plugins.phing; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.plugins.phing.console.PhingConsoleAnnotator; import hudson.tasks.Builder; import hudson.util.ArgumentListBuilder; import hudson.util.VariableResolver; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Properties; import java.util.Set; import org.kohsuke.stapler.DataBoundConstructor; /** * Phing Builder Plugin. * * @author Seiji Sogabe */ public final class PhingBuilder extends Builder { @Extension public static final PhingDescriptor DESCRIPTOR = new PhingDescriptor(); /** * Optional build script. */ private final String buildFile; /** * Identifies {@link PhingInstallation} to be used. */ private final String name; /** * List of Phing targets to be invoked. * If not specified, use "build.xml". */ private final String targets; /** * Optional properties to be passed to Phing. * Follow {@link Properties} syntax. */ private final String properties; /** * Whether uses ModuleRoot as working directory or not. * @since 0.9 */ private final boolean useModuleRoot; /** * Additional options to be passed to Phing. * @since 0.12 */ private final String options; public String getBuildFile() { return buildFile; } public String getName() { return name; } public String getTargets() { return targets; } public String getProperties() { return properties; } public boolean isUseModuleRoot() { return useModuleRoot; } public String getOptions() { return options; } @DataBoundConstructor public PhingBuilder(String name, String buildFile, String targets, String properties, boolean useModuleRoot, String options) { super(); this.name = Util.fixEmptyAndTrim(name); this.buildFile = Util.fixEmptyAndTrim(buildFile); this.targets = Util.fixEmptyAndTrim(targets); this.properties = Util.fixEmptyAndTrim(properties); this.useModuleRoot = useModuleRoot; this.options = Util.fixEmptyAndTrim(options); } public PhingInstallation getPhing() { for (final PhingInstallation inst : DESCRIPTOR.getInstallations()) { if (name != null && name.equals(inst.getName())) { return inst; } } return null; } @Override public Descriptor<Builder> getDescriptor() { return DESCRIPTOR; } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ArgumentListBuilder args = new ArgumentListBuilder(); final EnvVars env = build.getEnvironment(listener); final PhingInstallation pi = getPhing(); // PHP Command if (pi != null) { final String phpCommand = pi.getPhpCommand(); if (phpCommand != null) { env.put("PHP_COMMAND", phpCommand); } } // Phing Command if (pi == null) { args.add(PhingInstallation.getExecName(launcher)); } else { args.add(pi.getExecutable(launcher)); } VariableResolver<String> vr = build.getBuildVariableResolver(); String script = (buildFile == null) ? "build.xml" : buildFile; FilePath buildScript = lookingForBuildScript(build, env.expand(script), listener); if (buildScript == null) { listener.getLogger().println(Messages.Phing_NotFoundABuildScript(script)); return false; } args.add("-buildfile", buildScript.getRemote()); // Targets String expandedTargets = Util.replaceMacro(env.expand(targets), vr); if (expandedTargets != null) { args.addTokenized(expandedTargets.replaceAll("[\t\r\n]+", " ")); } Set<String> sensitiveVars = build.getSensitiveBuildVariables(); args.addKeyValuePairs("-D", build.getBuildVariables(), sensitiveVars); - args.addKeyValuePairsFromPropertyString("-D", properties, vr, sensitiveVars); + args.addKeyValuePairsFromPropertyString("-D", env.expand(properties), vr, sensitiveVars); String expandedOptions = Util.replaceMacro(env.expand(options), vr); if (expandedOptions == null || !expandedOptions.contains("-logger ")) { // avoid printing esc sequence args.add("-logger", "phing.listener.DefaultLogger"); } if (expandedOptions != null) { args.addTokenized(expandedOptions.replaceAll("[\t\r\n]", " ")); } // Environment variables if (pi != null && pi.getPhingHome() != null) { env.put("PHING_HOME", pi.getPhingHome()); env.put("PHING_CLASSPATH", pi.getPhingHome() + File.separator + "classes"); } if (!launcher.isUnix()) { args = args.toWindowsCommand(); } // Working Directory // since 0.9 FilePath working = useModuleRoot ? build.getModuleRoot() : buildScript.getParent(); listener.getLogger().println(Messages.Phing_WorkingDirectory(working)); final long startTime = System.currentTimeMillis(); try { PhingConsoleAnnotator pca = new PhingConsoleAnnotator(listener.getLogger(), build.getCharset()); int result; try { result = launcher.launch().cmds(args).envs(env).stdout(pca).pwd(working).join(); } finally { pca.forceEol(); } return result == 0; } catch (final IOException e) { Util.displayIOException(e, listener); final long processingTime = System.currentTimeMillis() - startTime; final String errorMessage = buildErrorMessage(pi, processingTime); e.printStackTrace(listener.fatalError(errorMessage)); return false; } } private FilePath lookingForBuildScript(AbstractBuild<?, ?> build, String script, BuildListener listener) throws IOException, InterruptedException { PrintStream logger = listener.getLogger(); FilePath buildScriptPath = build.getModuleRoot().child(script); logger.println("looking for '" + buildScriptPath.getRemote() + "' ... "); if (buildScriptPath.exists()) { return buildScriptPath; } buildScriptPath = build.getWorkspace().child(script); logger.println("looking for '" + buildScriptPath.getRemote() + "' ... "); if (buildScriptPath.exists()) { return buildScriptPath; } buildScriptPath = new FilePath(new File(script)); logger.println("looking for '" + buildScriptPath.getRemote() + "' ... "); if (buildScriptPath.exists()) { return buildScriptPath; } // build script not Found return null; } private String buildErrorMessage(final PhingInstallation pi, final long processingTime) { final StringBuffer msg = new StringBuffer(); msg.append(Messages.Phing_ExecFailed()); if (pi == null && processingTime < 1000) { if (DESCRIPTOR.getInstallations() == null) { msg.append(Messages.Phing_GlocalConfigNeeded()); } else { msg.append(Messages.Phing_ProjectConfigNeeded()); } } return msg.toString(); } }
true
true
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ArgumentListBuilder args = new ArgumentListBuilder(); final EnvVars env = build.getEnvironment(listener); final PhingInstallation pi = getPhing(); // PHP Command if (pi != null) { final String phpCommand = pi.getPhpCommand(); if (phpCommand != null) { env.put("PHP_COMMAND", phpCommand); } } // Phing Command if (pi == null) { args.add(PhingInstallation.getExecName(launcher)); } else { args.add(pi.getExecutable(launcher)); } VariableResolver<String> vr = build.getBuildVariableResolver(); String script = (buildFile == null) ? "build.xml" : buildFile; FilePath buildScript = lookingForBuildScript(build, env.expand(script), listener); if (buildScript == null) { listener.getLogger().println(Messages.Phing_NotFoundABuildScript(script)); return false; } args.add("-buildfile", buildScript.getRemote()); // Targets String expandedTargets = Util.replaceMacro(env.expand(targets), vr); if (expandedTargets != null) { args.addTokenized(expandedTargets.replaceAll("[\t\r\n]+", " ")); } Set<String> sensitiveVars = build.getSensitiveBuildVariables(); args.addKeyValuePairs("-D", build.getBuildVariables(), sensitiveVars); args.addKeyValuePairsFromPropertyString("-D", properties, vr, sensitiveVars); String expandedOptions = Util.replaceMacro(env.expand(options), vr); if (expandedOptions == null || !expandedOptions.contains("-logger ")) { // avoid printing esc sequence args.add("-logger", "phing.listener.DefaultLogger"); } if (expandedOptions != null) { args.addTokenized(expandedOptions.replaceAll("[\t\r\n]", " ")); } // Environment variables if (pi != null && pi.getPhingHome() != null) { env.put("PHING_HOME", pi.getPhingHome()); env.put("PHING_CLASSPATH", pi.getPhingHome() + File.separator + "classes"); } if (!launcher.isUnix()) { args = args.toWindowsCommand(); } // Working Directory // since 0.9 FilePath working = useModuleRoot ? build.getModuleRoot() : buildScript.getParent(); listener.getLogger().println(Messages.Phing_WorkingDirectory(working)); final long startTime = System.currentTimeMillis(); try { PhingConsoleAnnotator pca = new PhingConsoleAnnotator(listener.getLogger(), build.getCharset()); int result; try { result = launcher.launch().cmds(args).envs(env).stdout(pca).pwd(working).join(); } finally { pca.forceEol(); } return result == 0; } catch (final IOException e) { Util.displayIOException(e, listener); final long processingTime = System.currentTimeMillis() - startTime; final String errorMessage = buildErrorMessage(pi, processingTime); e.printStackTrace(listener.fatalError(errorMessage)); return false; } }
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { ArgumentListBuilder args = new ArgumentListBuilder(); final EnvVars env = build.getEnvironment(listener); final PhingInstallation pi = getPhing(); // PHP Command if (pi != null) { final String phpCommand = pi.getPhpCommand(); if (phpCommand != null) { env.put("PHP_COMMAND", phpCommand); } } // Phing Command if (pi == null) { args.add(PhingInstallation.getExecName(launcher)); } else { args.add(pi.getExecutable(launcher)); } VariableResolver<String> vr = build.getBuildVariableResolver(); String script = (buildFile == null) ? "build.xml" : buildFile; FilePath buildScript = lookingForBuildScript(build, env.expand(script), listener); if (buildScript == null) { listener.getLogger().println(Messages.Phing_NotFoundABuildScript(script)); return false; } args.add("-buildfile", buildScript.getRemote()); // Targets String expandedTargets = Util.replaceMacro(env.expand(targets), vr); if (expandedTargets != null) { args.addTokenized(expandedTargets.replaceAll("[\t\r\n]+", " ")); } Set<String> sensitiveVars = build.getSensitiveBuildVariables(); args.addKeyValuePairs("-D", build.getBuildVariables(), sensitiveVars); args.addKeyValuePairsFromPropertyString("-D", env.expand(properties), vr, sensitiveVars); String expandedOptions = Util.replaceMacro(env.expand(options), vr); if (expandedOptions == null || !expandedOptions.contains("-logger ")) { // avoid printing esc sequence args.add("-logger", "phing.listener.DefaultLogger"); } if (expandedOptions != null) { args.addTokenized(expandedOptions.replaceAll("[\t\r\n]", " ")); } // Environment variables if (pi != null && pi.getPhingHome() != null) { env.put("PHING_HOME", pi.getPhingHome()); env.put("PHING_CLASSPATH", pi.getPhingHome() + File.separator + "classes"); } if (!launcher.isUnix()) { args = args.toWindowsCommand(); } // Working Directory // since 0.9 FilePath working = useModuleRoot ? build.getModuleRoot() : buildScript.getParent(); listener.getLogger().println(Messages.Phing_WorkingDirectory(working)); final long startTime = System.currentTimeMillis(); try { PhingConsoleAnnotator pca = new PhingConsoleAnnotator(listener.getLogger(), build.getCharset()); int result; try { result = launcher.launch().cmds(args).envs(env).stdout(pca).pwd(working).join(); } finally { pca.forceEol(); } return result == 0; } catch (final IOException e) { Util.displayIOException(e, listener); final long processingTime = System.currentTimeMillis() - startTime; final String errorMessage = buildErrorMessage(pi, processingTime); e.printStackTrace(listener.fatalError(errorMessage)); return false; } }
diff --git a/VASSAL/counters/BasicPiece.java b/VASSAL/counters/BasicPiece.java index d75b5d95..e142216f 100644 --- a/VASSAL/counters/BasicPiece.java +++ b/VASSAL/counters/BasicPiece.java @@ -1,709 +1,709 @@ /* * $Id$ * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.counters; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.InputEvent; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.KeyStroke; import VASSAL.build.GameModule; import VASSAL.build.module.Chatter; import VASSAL.build.module.GlobalOptions; import VASSAL.build.module.Map; import VASSAL.build.module.documentation.HelpFile; import VASSAL.build.module.map.boardPicker.Board; import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone; import VASSAL.command.AddPiece; import VASSAL.command.ChangePiece; import VASSAL.command.Command; import VASSAL.command.RemovePiece; import VASSAL.i18n.Localization; import VASSAL.i18n.PieceI18nData; import VASSAL.i18n.TranslatablePiece; import VASSAL.tools.DataArchive; import VASSAL.tools.SequenceEncoder; /** * Basic class for representing a physical component of the game * Can be a counter, a card, or an overlay */ public class BasicPiece implements TranslatablePiece, StateMergeable { public static final String ID = "piece;"; private static Highlighter highlighter; /** * Return information about the current location of the piece through getProperty(): * * LocationName - Current Location Name of piece as displayed in Chat Window * CurrentX - Current X position * CurrentY - Current Y position * CurrentMap - Current Map name or "" if not on a map * CurrentBoard - Current Board name or "" if not on a map * CurrentZone - If the current map has a multi-zoned grid, then * return the name of the Zone the piece is in, or "" * if the piece is not in any zone, or not on a map */ public static final String LOCATION_NAME = "LocationName"; public static final String CURRENT_MAP = "CurrentMap"; public static final String CURRENT_BOARD = "CurrentBoard"; public static final String CURRENT_ZONE = "CurrentZone"; public static final String CURRENT_X = "CurrentX"; public static final String CURRENT_Y = "CurrentY"; public static final String OLD_LOCATION_NAME = "OldLocationName"; public static final String OLD_MAP = "OldMap"; public static final String OLD_BOARD = "OldBoard"; public static final String OLD_ZONE = "OldZone"; public static final String OLD_X = "OldX"; public static final String OLD_Y = "OldY"; public static final String BASIC_NAME = "BasicName"; public static final String PIECE_NAME = "PieceName"; public static final String DECK_NAME = "DeckName"; public static Font POPUP_MENU_FONT = new Font("Dialog", 0, 11); protected Image image; protected Rectangle imageBounds; protected JPopupMenu popup; private Map map; private KeyCommand[] commands; private Stack parent; private Point pos = new Point(0, 0); private String id; private java.util.Map<Object,Object> props; private char cloneKey, deleteKey; // Moved into independent traits, but retained for backward compatibility protected String imageName; private String commonName; public BasicPiece() { this(ID + ";;;;"); } public BasicPiece(String type) { mySetType(type); } public void mySetType(String type) { SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(type, ';'); st.nextToken(); cloneKey = st.nextChar('\0'); deleteKey = st.nextChar('\0'); imageName = st.nextToken(); commonName = st.nextToken(); initImage(); commands = null; } public String getType() { SequenceEncoder se = new SequenceEncoder(cloneKey > 0 ? "" + cloneKey : "", ';'); return ID + se.append(deleteKey > 0 ? "" + deleteKey : "") .append(imageName).append(commonName).getValue(); } public void setMap(Map map) { if (map != this.map) { commands = null; this.map = map; } } public Map getMap() { return getParent() == null ? map : getParent().getMap(); } public Object getProperty(Object key) { if (Properties.KEY_COMMANDS.equals(key)) { return getKeyCommands(); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().locationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (BASIC_NAME.equals(key)) { return getName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getConfigureName(); } else if (DECK_NAME.equals(key)) { return getParent() instanceof Deck ? ((Deck)getParent()).getDeckName() : ""; } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getName(); } } return ""; } else if (CURRENT_X.equals(key)) { return String.valueOf(getPosition().x); } else if (CURRENT_Y.equals(key)) { return String.valueOf(getPosition().y); } else if (Properties.VISIBLE_STATE.equals(key)) { return ""; } Object prop = props == null ? null : props.get(key); if (prop == null) { Map map = getMap(); Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getProperty(key); } else if (map != null) { prop = map.getProperty(key); } else { prop = GameModule.getGameModule().getProperty(key); } } return prop; } public Object getLocalizedProperty(Object key) { if (Properties.KEY_COMMANDS.equals(key)) { return getProperty(key); } else if (LOCATION_NAME.equals(key)) { return getMap() == null ? "" : getMap().localizedLocationName(getPosition()); } else if (PIECE_NAME.equals(key)) { return Decorator.getOutermost(this).getName(); } else if (BASIC_NAME.equals(key)) { return getLocalizedName(); } else if (CURRENT_MAP.equals(key)) { return getMap() == null ? "" : getMap().getLocalizedConfigureName(); } else if (DECK_NAME.equals(key)) { return getParent() instanceof Deck ? ((Deck)getParent()).getLocalizedDeckName() : ""; } else if (CURRENT_BOARD.equals(key)) { if (getMap() != null) { Board b = getMap().findBoard(getPosition()); if (b != null) { return b.getLocalizedName(); } } return ""; } else if (CURRENT_ZONE.equals(key)) { if (getMap() != null) { Zone z = getMap().findZone(getPosition()); if (z != null) { return z.getLocalizedName(); } } return ""; } else if (CURRENT_X.equals(key)) { return getProperty(key); } else if (CURRENT_Y.equals(key)) { return getProperty(key); } else if (Properties.VISIBLE_STATE.equals(key)) { return getProperty(key); } Object prop = props == null ? null : props.get(key); if (prop == null) { Map map = getMap(); Zone zone = (map == null ? null : map.findZone(getPosition())); if (zone != null) { prop = zone.getLocalizedProperty(key); } else if (map != null) { prop = map.getLocalizedProperty(key); } else { prop = GameModule.getGameModule().getLocalizedProperty(key); } } return prop; } public void setProperty(Object key, Object val) { if (props == null) { props = new HashMap<Object,Object>(); } if (val == null) { props.remove(key); } else { props.put(key, val); } } protected Object prefsValue(String s) { return GameModule.getGameModule().getPrefs().getValue(s); } public void draw(Graphics g, int x, int y, Component obs, double zoom) { initImage(); if (image != null) { if (zoom == 1.0) { g.drawImage(image, x + imageBounds.x, y + imageBounds.y, obs); } else { Image scaledImage = GameModule.getGameModule().getDataArchive().getScaledImage(image, zoom); g.drawImage(scaledImage, x + (int) (zoom * imageBounds.x), y + (int) (zoom * imageBounds.y), obs); } } } private void initImage() { if (imageName.trim().length() > 0) { try { image = GameModule.getGameModule().getDataArchive().getCachedImage(imageName); imageBounds = DataArchive.getImageBounds(image); } catch (IOException e) { imageBounds = new Rectangle(); } } else { image = null; imageBounds = new Rectangle(); } } protected KeyCommand[] getKeyCommands() { if (commands == null) { ArrayList<KeyCommand> l = new ArrayList<KeyCommand>(); GamePiece target = Decorator.getOutermost(this); if (cloneKey > 0) { l.add(new KeyCommand("Clone", KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_MASK), target)); } if (deleteKey > 0) { l.add(new KeyCommand("Delete", KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_MASK), target)); } commands = l.toArray(new KeyCommand[l.size()]); } GamePiece outer = Decorator.getOutermost(this); boolean canAdjustPosition = outer.getMap() != null && outer.getParent() != null && outer.getParent().topPiece() != getParent().bottomPiece(); enableCommand("Move up", canAdjustPosition); enableCommand("Move down", canAdjustPosition); enableCommand("Move to top", canAdjustPosition); enableCommand("Move to bottom", canAdjustPosition); enableCommand("Clone", outer.getMap() != null); enableCommand("Delete", outer.getMap() != null); return commands; } private void enableCommand(String name, boolean enable) { for (int i = 0; i < commands.length; ++i) { if (name.equals(commands[i].getName())) { commands[i].setEnabled(enable); } } } private boolean isEnabled(KeyStroke stroke) { if (stroke == null) { return false; } for (int i = 0; i < commands.length; ++i) { if (stroke.equals(commands[i].getKeyStroke())) { return commands[i].isEnabled(); } } return true; } public Point getPosition() { return getParent() == null ? new Point(pos) : getParent().getPosition(); } public void setPosition(Point p) { if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } pos = p; if (getMap() != null && getParent() == null) { getMap().repaint(getMap().boundingBoxOf(Decorator.getOutermost(this))); } } public Stack getParent() { return parent; } public void setParent(Stack s) { parent = s; } public Rectangle boundingBox() { return new Rectangle(imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height); } public Shape getShape() { return new Rectangle(imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height); } public boolean equals(GamePiece c) { return c == this; } public String getName() { return commonName; } public String getLocalizedName() { String key = TranslatablePiece.PREFIX + getName(); return Localization.getInstance().translate(key, getName()); } public Command keyEvent(KeyStroke stroke) { getKeyCommands(); if (!isEnabled(stroke)) { return null; } Command comm = null; GamePiece outer = Decorator.getOutermost(this); if (KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_MASK).equals(stroke)) { GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode (GameModule.getGameModule().encode (new AddPiece(outer)))).getTarget(); newPiece.setId(null); GameModule.getGameModule().getGameState().addPiece(newPiece); newPiece.setState(outer.getState()); comm = new AddPiece(newPiece); if (getMap() != null) { comm.append(getMap().placeOrMerge(newPiece,getPosition())); KeyBuffer.getBuffer().remove(outer); KeyBuffer.getBuffer().add(newPiece); if (GlobalOptions.getInstance().autoReportEnabled()) { - String s = "* " + outer.getName(); + String s = "* " + outer.getLocalizedName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " cloned in " + loc + " * "; } else { s += "cloned *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); report.execute(); comm = comm.append(report); } } } else if (KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_MASK).equals(stroke)) { comm = new RemovePiece(outer); if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled()) { - String s = "* " + outer.getName(); + String s = "* " + outer.getLocalizedName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " deleted from " + loc + " * "; } else { s += " deleted *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); comm = comm.append(report); } comm.execute(); } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index < parent.getPieceCount() - 1) { parent.insert(outer, index + 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index > 0) { parent.insert(outer, index - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) { parent = outer.getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) < parent.getPieceCount() - 1) { parent.insert(outer, parent.getPieceCount() - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) { parent = getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) > 0) { parent.insert(outer, 0); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } return comm; } public String getState() { SequenceEncoder se = new SequenceEncoder(';'); String mapName = map == null ? "null" : map.getIdentifier(); se.append(mapName); Point p = getPosition(); se.append(p.x).append(p.y); return se.getValue(); } public void setState(String s) { GamePiece outer = Decorator.getOutermost(this); Map oldMap = getMap(); SequenceEncoder.Decoder st = new SequenceEncoder.Decoder(s, ';'); String mapId = st.nextToken(); Map newMap = null; if (!"null".equals(mapId)) { newMap = Map.getMapById(mapId); if (newMap == null) { System.err.println("Could not find map " + mapId); return; } } Point newPos = new Point(st.nextInt(0), st.nextInt(0)); setPosition(newPos); if (newMap != oldMap) { if (newMap != null) { // This will remove from oldMap // and set the map to newMap newMap.addPiece(outer); } else if (oldMap != null) { oldMap.removePiece(outer); setMap(null); } else { setMap(null); } } } public void mergeState(String newState, String oldState) { if (!newState.equals(oldState)) { setState(newState); } } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * Get the Highlighter instance for drawing selected pieces. Note that * since this is a static method, all pieces in a module will * always use the same Highlighter */ public static Highlighter getHighlighter() { if (highlighter == null) { highlighter = new ColoredBorder(); } return highlighter; } /** * Set the Highlighter for all pieces */ public static void setHighlighter(Highlighter h) { highlighter = h; } public String getDescription() { return "Basic Piece"; } public HelpFile getHelpFile() { return HelpFile.getReferenceManualPage("BasicPiece.htm"); } public PieceEditor getEditor() { return new Ed(this); } private static class Ed implements PieceEditor { private JPanel panel; private KeySpecifier cloneKeyInput; private KeySpecifier deleteKeyInput; private JTextField pieceName; private ImagePicker picker; private String state; private Ed(BasicPiece p) { state = p.getState(); initComponents(p); } private void initComponents(BasicPiece p) { panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); picker = new ImagePicker(); picker.setImageName(p.imageName); panel.add(picker); cloneKeyInput = new KeySpecifier(p.cloneKey); deleteKeyInput = new KeySpecifier(p.deleteKey); pieceName = new JTextField(12); pieceName.setText(p.commonName); pieceName.setMaximumSize(pieceName.getPreferredSize()); Box col = Box.createVerticalBox(); Box row = Box.createHorizontalBox(); row.add(new JLabel("Name: ")); row.add(pieceName); col.add(row); if (p.cloneKey != 0) { row = Box.createHorizontalBox(); row.add(new JLabel("To Clone: ")); row.add(cloneKeyInput); col.add(row); } if (p.deleteKey != 0) { row = Box.createHorizontalBox(); row.add(new JLabel("To Delete: ")); row.add(deleteKeyInput); col.add(row); } panel.add(col); } public void reset(BasicPiece p) { } public Component getControls() { return panel; } public String getState() { return state; } public String getType() { SequenceEncoder se = new SequenceEncoder(cloneKeyInput.getKey(), ';'); String type = se.append(deleteKeyInput.getKey()) .append(picker.getImageName()) .append(pieceName.getText()).getValue(); return BasicPiece.ID + type; } } public String toString() { return super.toString()+"[name="+getName()+",type="+getType()+",state="+getState()+"]"; } public PieceI18nData getI18nData() { PieceI18nData data = new PieceI18nData(this); data.add(commonName, "Basic piece name"); return data; } }
false
true
public Command keyEvent(KeyStroke stroke) { getKeyCommands(); if (!isEnabled(stroke)) { return null; } Command comm = null; GamePiece outer = Decorator.getOutermost(this); if (KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_MASK).equals(stroke)) { GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode (GameModule.getGameModule().encode (new AddPiece(outer)))).getTarget(); newPiece.setId(null); GameModule.getGameModule().getGameState().addPiece(newPiece); newPiece.setState(outer.getState()); comm = new AddPiece(newPiece); if (getMap() != null) { comm.append(getMap().placeOrMerge(newPiece,getPosition())); KeyBuffer.getBuffer().remove(outer); KeyBuffer.getBuffer().add(newPiece); if (GlobalOptions.getInstance().autoReportEnabled()) { String s = "* " + outer.getName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " cloned in " + loc + " * "; } else { s += "cloned *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); report.execute(); comm = comm.append(report); } } } else if (KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_MASK).equals(stroke)) { comm = new RemovePiece(outer); if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled()) { String s = "* " + outer.getName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " deleted from " + loc + " * "; } else { s += " deleted *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); comm = comm.append(report); } comm.execute(); } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index < parent.getPieceCount() - 1) { parent.insert(outer, index + 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index > 0) { parent.insert(outer, index - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) { parent = outer.getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) < parent.getPieceCount() - 1) { parent.insert(outer, parent.getPieceCount() - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) { parent = getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) > 0) { parent.insert(outer, 0); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } return comm; }
public Command keyEvent(KeyStroke stroke) { getKeyCommands(); if (!isEnabled(stroke)) { return null; } Command comm = null; GamePiece outer = Decorator.getOutermost(this); if (KeyStroke.getKeyStroke(cloneKey, InputEvent.CTRL_MASK).equals(stroke)) { GamePiece newPiece = ((AddPiece) GameModule.getGameModule().decode (GameModule.getGameModule().encode (new AddPiece(outer)))).getTarget(); newPiece.setId(null); GameModule.getGameModule().getGameState().addPiece(newPiece); newPiece.setState(outer.getState()); comm = new AddPiece(newPiece); if (getMap() != null) { comm.append(getMap().placeOrMerge(newPiece,getPosition())); KeyBuffer.getBuffer().remove(outer); KeyBuffer.getBuffer().add(newPiece); if (GlobalOptions.getInstance().autoReportEnabled()) { String s = "* " + outer.getLocalizedName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " cloned in " + loc + " * "; } else { s += "cloned *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); report.execute(); comm = comm.append(report); } } } else if (KeyStroke.getKeyStroke(deleteKey, InputEvent.CTRL_MASK).equals(stroke)) { comm = new RemovePiece(outer); if (getMap() != null && GlobalOptions.getInstance().autoReportEnabled()) { String s = "* " + outer.getLocalizedName(); String loc = getMap().locationName(outer.getPosition()); if (loc != null) { s += " deleted from " + loc + " * "; } else { s += " deleted *"; } Command report = new Chatter.DisplayText(GameModule.getGameModule().getChatter(), s); comm = comm.append(report); } comm.execute(); } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveUpKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index < parent.getPieceCount() - 1) { parent.insert(outer, index + 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveDownKey())) { if (parent != null) { String oldState = parent.getState(); int index = parent.indexOf(outer); if (index > 0) { parent.insert(outer, index - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveTopKey())) { parent = outer.getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) < parent.getPieceCount() - 1) { parent.insert(outer, parent.getPieceCount() - 1); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToFront(parent); } } else { getMap().getPieceCollection().moveToFront(outer); } } else if (getMap() != null && stroke.equals(getMap().getStackMetrics().getMoveBottomKey())) { parent = getParent(); if (parent != null) { String oldState = parent.getState(); if (parent.indexOf(outer) > 0) { parent.insert(outer, 0); comm = new ChangePiece(parent.getId(), oldState, parent.getState()); } else { getMap().getPieceCollection().moveToBack(parent); } } else { getMap().getPieceCollection().moveToBack(outer); } } return comm; }
diff --git a/core/java/src/net/i2p/client/BWLimitsMessageHandler.java b/core/java/src/net/i2p/client/BWLimitsMessageHandler.java index be00d3fff..34fa81ec8 100644 --- a/core/java/src/net/i2p/client/BWLimitsMessageHandler.java +++ b/core/java/src/net/i2p/client/BWLimitsMessageHandler.java @@ -1,27 +1,27 @@ package net.i2p.client; /* * Released into the public domain * with no warranty of any kind, either expressed or implied. */ import net.i2p.I2PAppContext; import net.i2p.data.i2cp.I2CPMessage; import net.i2p.data.i2cp.BandwidthLimitsMessage; import net.i2p.util.Log; /** * Handle I2CP BW replies from the router */ class BWLimitsMessageHandler extends HandlerImpl { public BWLimitsMessageHandler(I2PAppContext ctx) { super(ctx, BandwidthLimitsMessage.MESSAGE_TYPE); } public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); BandwidthLimitsMessage msg = (BandwidthLimitsMessage) message; - ((I2PSimpleSession)session).bwReceived(msg.getLimits()); + session.bwReceived(msg.getLimits()); } }
true
true
public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); BandwidthLimitsMessage msg = (BandwidthLimitsMessage) message; ((I2PSimpleSession)session).bwReceived(msg.getLimits()); }
public void handleMessage(I2CPMessage message, I2PSessionImpl session) { if (_log.shouldLog(Log.DEBUG)) _log.debug("Handle message " + message); BandwidthLimitsMessage msg = (BandwidthLimitsMessage) message; session.bwReceived(msg.getLimits()); }
diff --git a/src/java/org/apache/fop/apps/FOUserAgent.java b/src/java/org/apache/fop/apps/FOUserAgent.java index 0bd803ec8..a6ec87916 100644 --- a/src/java/org/apache/fop/apps/FOUserAgent.java +++ b/src/java/org/apache/fop/apps/FOUserAgent.java @@ -1,655 +1,655 @@ /* * Copyright 1999-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. */ /* $Id$ */ package org.apache.fop.apps; // Java import java.io.File; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.Date; import java.util.List; import java.util.Map; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; // avalon configuration import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; // commons logging import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // FOP import org.apache.fop.Version; import org.apache.fop.fo.ElementMapping; import org.apache.fop.fo.FOEventHandler; import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.pdf.PDFEncryptionParams; import org.apache.fop.render.Renderer; import org.apache.fop.render.RendererFactory; import org.apache.fop.render.XMLHandlerRegistry; /** * The User Agent for fo. * This user agent is used by the processing to obtain user configurable * options. * <p> * Renderer specific extensions (that do not produce normal areas on * the output) will be done like so: * <br> * The extension will create an area, custom if necessary * <br> * this area will be added to the user agent with a key * <br> * the renderer will know keys for particular extensions * <br> * eg. bookmarks will be held in a special hierarchical area representing * the title and bookmark structure * <br> * These areas may contain resolvable areas that will be processed * with other resolvable areas */ public class FOUserAgent { /** Defines the default resolution (72dpi) for FOP */ public static final float DEFAULT_RESOLUTION = 72.0f; //dpi /** Defines the default resolution (72dpi) for FOP */ public static final float DEFAULT_PX2MM = (25.4f / DEFAULT_RESOLUTION); //dpi (=25.4/dpi) /** Defines the default page-height */ public static final String DEFAULT_PAGE_HEIGHT = "11in"; /** Defines the default page-width */ public static final String DEFAULT_PAGE_WIDTH = "8.26in"; /** Factory for Renderers and FOEventHandlers */ private RendererFactory rendererFactory = new RendererFactory(); /** Registry for XML handlers */ private XMLHandlerRegistry xmlHandlers = new XMLHandlerRegistry(); private String baseURL; /** A user settable URI Resolver */ private URIResolver uriResolver = null; /** Our default resolver if none is set */ private URIResolver foURIResolver = new FOURIResolver(); private PDFEncryptionParams pdfEncryptionParams; private float resolution = DEFAULT_RESOLUTION; private String pageHeight = DEFAULT_PAGE_HEIGHT; private String pageWidth = DEFAULT_PAGE_WIDTH; private Map rendererOptions = new java.util.HashMap(); private File outputFile = null; private Renderer rendererOverride = null; private FOEventHandler foEventHandlerOverride = null; private LayoutManagerMaker lmMakerOverride = null; /* user configuration */ private Configuration userConfig = null; private Log log = LogFactory.getLog("FOP"); /* FOP has the ability, for some FO's, to continue processing even if the * input XSL violates that FO's content model. This is the default * behavior for FOP. However, this flag, if set, provides the user the * ability for FOP to halt on all content model violations if desired. */ private boolean strictValidation = true; /** @see #setBreakIndentInheritanceOnReferenceAreaBoundary(boolean) */ private boolean breakIndentInheritanceOnReferenceAreaBoundary = false; /* Additional fo.ElementMapping subclasses set by user */ private List additionalElementMappings = null; /** Producer: Metadata element for the system/software that produces * the document. (Some renderers can store this in the document.) */ protected String producer = "Apache FOP Version " + Version.getVersion(); /** Creator: Metadata element for the user that created the * document. (Some renderers can store this in the document.) */ protected String creator = null; /** Creation Date: Override of the date the document was created. * (Some renderers can store this in the document.) */ protected Date creationDate = null; /** Author of the content of the document. */ protected String author = null; /** Title of the document. */ protected String title = null; /** Set of keywords applicable to this document. */ protected String keywords = null; /** * Add the element mapping with the given class name. * @param elementMapping the class name representing the element mapping. */ public void addElementMapping(ElementMapping elementMapping) { if (additionalElementMappings == null) { additionalElementMappings = new java.util.ArrayList(); } additionalElementMappings.add(elementMapping); } /** * Returns the List of user-added ElementMapping class names * @return List of Strings holding ElementMapping names. */ public List getAdditionalElementMappings() { return additionalElementMappings; } /** * Sets an explicit renderer to use which overrides the one defined by the * render type setting. * @param renderer the Renderer instance to use */ public void setRendererOverride(Renderer renderer) { this.rendererOverride = renderer; } /** * Returns the overriding Renderer instance, if any. * @return the overriding Renderer or null */ public Renderer getRendererOverride() { return rendererOverride; } /** * Sets an explicit FOEventHandler instance which overrides the one * defined by the render type setting. * @param handler the FOEventHandler instance */ public void setFOEventHandlerOverride(FOEventHandler handler) { this.foEventHandlerOverride = handler; } /** * Returns the overriding FOEventHandler instance, if any. * @return the overriding FOEventHandler or null */ public FOEventHandler getFOEventHandlerOverride() { return this.foEventHandlerOverride; } /** * Activates strict XSL content model validation for FOP * Default is false (FOP will continue processing where it can) * @param validateStrictly true to turn on strict validation */ public void setStrictValidation(boolean validateStrictly) { this.strictValidation = validateStrictly; } /** * Returns whether FOP is strictly validating input XSL * @return true of strict validation turned on, false otherwise */ public boolean validateStrictly() { return strictValidation; } /** * @return true if the indent inheritance should be broken when crossing reference area * boundaries (for more info, see the javadoc for the relative member variable) */ public boolean isBreakIndentInheritanceOnReferenceAreaBoundary() { return breakIndentInheritanceOnReferenceAreaBoundary; } /** * Controls whether to enable a feature that breaks indent inheritance when crossing * reference area boundaries. * <p> * This flag controls whether FOP will enable special code that breaks property * inheritance for start-indent and end-indent when the evaluation of the inherited * value would cross a reference area. This is described under * http://wiki.apache.org/xmlgraphics-fop/IndentInheritance as is intended to * improve interoperability with commercial FO implementations and to produce * results that are more in line with the expectation of unexperienced FO users. * Note: Enabling this features violates the XSL specification! * @param value true to enable the feature */ public void setBreakIndentInheritanceOnReferenceAreaBoundary(boolean value) { this.breakIndentInheritanceOnReferenceAreaBoundary = value; } /** * Sets an explicit LayoutManagerMaker instance which overrides the one * defined by the AreaTreeHandler. * @param lmMaker the LayoutManagerMaker instance */ public void setLayoutManagerMakerOverride(LayoutManagerMaker lmMaker) { this.lmMakerOverride = lmMaker; } /** * Returns the overriding LayoutManagerMaker instance, if any. * @return the overriding LayoutManagerMaker or null */ public LayoutManagerMaker getLayoutManagerMakerOverride() { return this.lmMakerOverride; } /** * Sets the producer of the document. * @param producer source of document */ public void setProducer(String producer) { this.producer = producer; } /** * Returns the producer of the document * @return producer name */ public String getProducer() { return producer; } /** * Sets the creator of the document. * @param creator of document */ public void setCreator(String creator) { this.creator = creator; } /** * Returns the creator of the document * @return creator name */ public String getCreator() { return creator; } /** * Sets the creation date of the document. * @param creationDate date of document */ public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } /** * Returns the creation date of the document * @return creation date of document */ public Date getCreationDate() { return creationDate; } /** * Sets the author of the document. * @param author of document */ public void setAuthor(String author) { this.author = author; } /** * Returns the author of the document * @return author name */ public String getAuthor() { return author; } /** * Sets the title of the document. This will override any title coming from * an fo:title element. * @param title of document */ public void setTitle(String title) { this.title = title; } /** * Returns the title of the document * @return title name */ public String getTitle() { return title; } /** * Sets the keywords for the document. * @param keywords for the document */ public void setKeywords(String keywords) { this.keywords = keywords; } /** * Returns the keywords for the document * @return the keywords */ public String getKeywords() { return keywords; } /** * Returns the renderer options * @return renderer options */ public Map getRendererOptions() { return rendererOptions; } /** * Set the user configuration. * @param userConfig configuration */ public void setUserConfig(Configuration userConfig) { this.userConfig = userConfig; try { initUserConfig(); } catch (ConfigurationException cfge) { log.error("Error initializing User Agent configuration: " + cfge.getMessage()); } } /** * Get the user configuration. * @return the user configuration */ public Configuration getUserConfig() { return userConfig; } /** * Initializes user agent settings from the user configuration * file, if present: baseURL, resolution, default page size,... * * @throws ConfigurationException when there is an entry that * misses the required attribute */ public void initUserConfig() throws ConfigurationException { log.debug("Initializing User Agent Configuration"); if (userConfig.getChild("base", false) != null) { try { String cfgBaseDir = userConfig.getChild("base").getValue(null); if (cfgBaseDir != null) { File dir = new File(cfgBaseDir); if (dir.isDirectory()) { cfgBaseDir = "file://" + dir.getCanonicalPath() + System.getProperty("file.separator"); cfgBaseDir = cfgBaseDir.replace( System.getProperty("file.separator").charAt(0), '/'); } else { //The next statement is for validation only new URL(cfgBaseDir); } } setBaseURL(cfgBaseDir); } catch (MalformedURLException mue) { log.error("Base URL in user config is malformed!"); } catch (IOException ioe) { log.error("Error converting relative base directory to absolute URL."); } log.info("Base URL set to: " + baseURL); } if (userConfig.getChild("pixelToMillimeter", false) != null) { this.resolution = 25.4f / userConfig.getChild("pixelToMillimeter") .getAttributeAsFloat("value", DEFAULT_PX2MM); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } else if (userConfig.getChild("resolution", false) != null) { this.resolution - = 25.4f / userConfig.getChild("resolution").getValueAsFloat(DEFAULT_RESOLUTION); + = userConfig.getChild("resolution").getValueAsFloat(DEFAULT_RESOLUTION); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } if (userConfig.getChild("strict-validation", false) != null) { this.strictValidation = userConfig.getChild("strict-validation").getValueAsBoolean(); } if (userConfig.getChild("break-indent-inheritance", false) != null) { this.breakIndentInheritanceOnReferenceAreaBoundary = userConfig.getChild("break-indent-inheritance").getValueAsBoolean(); } Configuration pageConfig = userConfig.getChild("default-page-settings"); if (pageConfig.getAttribute("height", null) != null) { setPageHeight(pageConfig.getAttribute("height")); log.info("Default page-height set to: " + pageHeight); } if (pageConfig.getAttribute("width", null) != null) { setPageWidth(pageConfig.getAttribute("width")); log.info("Default page-width set to: " + pageWidth); } } /** * Returns the configuration subtree for a specific renderer. * @param mimeType MIME type of the renderer * @return the requested configuration subtree, null if there's no configuration */ public Configuration getUserRendererConfig (String mimeType) { if (userConfig == null || mimeType == null) { return null; } Configuration userRendererConfig = null; Configuration[] cfgs = userConfig.getChild("renderers").getChildren("renderer"); for (int i = 0; i < cfgs.length; ++i) { Configuration cfg = cfgs[i]; try { if (cfg.getAttribute("mime").equals(mimeType)) { userRendererConfig = cfg; break; } } catch (ConfigurationException e) { // silently pass over configurations without mime type } } log.debug((userRendererConfig == null ? "No u" : "U") + "ser configuration found for MIME type " + mimeType); return userRendererConfig; } /** * Sets the base URL. * @param baseURL base URL */ public void setBaseURL(String baseURL) { this.baseURL = baseURL; } /** * Returns the base URL. * @return the base URL */ public String getBaseURL() { return this.baseURL; } /** * Sets the URI Resolver. * @param uriResolver the new URI resolver */ public void setURIResolver(URIResolver uriResolver) { this.uriResolver = uriResolver; } /** * Returns the URI Resolver. * @return the URI Resolver */ public URIResolver getURIResolver() { return this.uriResolver; } /** * Returns the parameters for PDF encryption. * @return the PDF encryption parameters, null if not applicable */ public PDFEncryptionParams getPDFEncryptionParams() { return pdfEncryptionParams; } /** * Sets the parameters for PDF encryption. * @param pdfEncryptionParams the PDF encryption parameters, null to * disable PDF encryption */ public void setPDFEncryptionParams(PDFEncryptionParams pdfEncryptionParams) { this.pdfEncryptionParams = pdfEncryptionParams; } /** * Attempts to resolve the given URI. * Will use the configured resolver and if not successful fall back * to the default resolver. * @param uri URI to access * @return A {@link javax.xml.transform.Source} object, or null if the URI * cannot be resolved. * @see org.apache.fop.apps.FOURIResolver */ public Source resolveURI(String uri) { Source source = null; if (uriResolver != null) { try { source = uriResolver.resolve(uri, getBaseURL()); } catch (TransformerException te) { log.error("Attempt to resolve URI '" + uri + "' failed: ", te); } } if (source == null) { // URI Resolver not configured or returned null, use default resolver try { source = foURIResolver.resolve(uri, getBaseURL()); } catch (TransformerException te) { log.error("Attempt to resolve URI '" + uri + "' failed: ", te); } } return source; } /** * Sets the output File. * @param f the output File */ public void setOutputFile(File f) { this.outputFile = f; } /** * Gets the output File. * @return the output File */ public File getOutputFile() { return outputFile; } /** * Returns the conversion factor from pixel units to millimeters. This * depends on the desired reolution. * @return float conversion factor */ public float getPixelUnitToMillimeter() { return 25.4f / this.resolution; } /** @return the resolution for resolution-dependant output */ public float getResolution() { return this.resolution; } /** * Sets the resolution in dpi. * @param dpi resolution in dpi */ public void setResolution(int dpi) { this.resolution = dpi; } /** * Gets the default page-height to use as fallback, * in case page-height="auto" * * @return the page-height, as a String */ public String getPageHeight() { return this.pageHeight; } /** * Sets the page-height to use as fallback, in case * page-height="auto" * * @param pageHeight page-height as a String */ public void setPageHeight(String pageHeight) { this.pageHeight = pageHeight; } /** * Gets the default page-width to use as fallback, * in case page-width="auto" * * @return the page-width, as a String */ public String getPageWidth() { return this.pageWidth; } /** * Sets the page-width to use as fallback, in case * page-width="auto" * * @param pageWidth page-width as a String */ public void setPageWidth(String pageWidth) { this.pageWidth = pageWidth; } /** * If to create hot links to footnotes and before floats. * @return True if hot links should be created */ /* TODO This method is never referenced! public boolean linkToFootnotes() { return true; }*/ /** * @return the RendererFactory */ public RendererFactory getRendererFactory() { return this.rendererFactory; } /** * @return the XML handler registry */ public XMLHandlerRegistry getXMLHandlerRegistry() { return this.xmlHandlers; } }
true
true
public void initUserConfig() throws ConfigurationException { log.debug("Initializing User Agent Configuration"); if (userConfig.getChild("base", false) != null) { try { String cfgBaseDir = userConfig.getChild("base").getValue(null); if (cfgBaseDir != null) { File dir = new File(cfgBaseDir); if (dir.isDirectory()) { cfgBaseDir = "file://" + dir.getCanonicalPath() + System.getProperty("file.separator"); cfgBaseDir = cfgBaseDir.replace( System.getProperty("file.separator").charAt(0), '/'); } else { //The next statement is for validation only new URL(cfgBaseDir); } } setBaseURL(cfgBaseDir); } catch (MalformedURLException mue) { log.error("Base URL in user config is malformed!"); } catch (IOException ioe) { log.error("Error converting relative base directory to absolute URL."); } log.info("Base URL set to: " + baseURL); } if (userConfig.getChild("pixelToMillimeter", false) != null) { this.resolution = 25.4f / userConfig.getChild("pixelToMillimeter") .getAttributeAsFloat("value", DEFAULT_PX2MM); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } else if (userConfig.getChild("resolution", false) != null) { this.resolution = 25.4f / userConfig.getChild("resolution").getValueAsFloat(DEFAULT_RESOLUTION); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } if (userConfig.getChild("strict-validation", false) != null) { this.strictValidation = userConfig.getChild("strict-validation").getValueAsBoolean(); } if (userConfig.getChild("break-indent-inheritance", false) != null) { this.breakIndentInheritanceOnReferenceAreaBoundary = userConfig.getChild("break-indent-inheritance").getValueAsBoolean(); } Configuration pageConfig = userConfig.getChild("default-page-settings"); if (pageConfig.getAttribute("height", null) != null) { setPageHeight(pageConfig.getAttribute("height")); log.info("Default page-height set to: " + pageHeight); } if (pageConfig.getAttribute("width", null) != null) { setPageWidth(pageConfig.getAttribute("width")); log.info("Default page-width set to: " + pageWidth); } }
public void initUserConfig() throws ConfigurationException { log.debug("Initializing User Agent Configuration"); if (userConfig.getChild("base", false) != null) { try { String cfgBaseDir = userConfig.getChild("base").getValue(null); if (cfgBaseDir != null) { File dir = new File(cfgBaseDir); if (dir.isDirectory()) { cfgBaseDir = "file://" + dir.getCanonicalPath() + System.getProperty("file.separator"); cfgBaseDir = cfgBaseDir.replace( System.getProperty("file.separator").charAt(0), '/'); } else { //The next statement is for validation only new URL(cfgBaseDir); } } setBaseURL(cfgBaseDir); } catch (MalformedURLException mue) { log.error("Base URL in user config is malformed!"); } catch (IOException ioe) { log.error("Error converting relative base directory to absolute URL."); } log.info("Base URL set to: " + baseURL); } if (userConfig.getChild("pixelToMillimeter", false) != null) { this.resolution = 25.4f / userConfig.getChild("pixelToMillimeter") .getAttributeAsFloat("value", DEFAULT_PX2MM); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } else if (userConfig.getChild("resolution", false) != null) { this.resolution = userConfig.getChild("resolution").getValueAsFloat(DEFAULT_RESOLUTION); log.info("resolution set to: " + resolution + "dpi (px2mm=" + getPixelUnitToMillimeter() + ")"); } if (userConfig.getChild("strict-validation", false) != null) { this.strictValidation = userConfig.getChild("strict-validation").getValueAsBoolean(); } if (userConfig.getChild("break-indent-inheritance", false) != null) { this.breakIndentInheritanceOnReferenceAreaBoundary = userConfig.getChild("break-indent-inheritance").getValueAsBoolean(); } Configuration pageConfig = userConfig.getChild("default-page-settings"); if (pageConfig.getAttribute("height", null) != null) { setPageHeight(pageConfig.getAttribute("height")); log.info("Default page-height set to: " + pageHeight); } if (pageConfig.getAttribute("width", null) != null) { setPageWidth(pageConfig.getAttribute("width")); log.info("Default page-width set to: " + pageWidth); } }
diff --git a/src/com/anysoftkeyboard/dictionaries/ExternalDictionaryFactory.java b/src/com/anysoftkeyboard/dictionaries/ExternalDictionaryFactory.java index 96188f17..5662e5c1 100644 --- a/src/com/anysoftkeyboard/dictionaries/ExternalDictionaryFactory.java +++ b/src/com/anysoftkeyboard/dictionaries/ExternalDictionaryFactory.java @@ -1,104 +1,104 @@ package com.anysoftkeyboard.dictionaries; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import com.anysoftkeyboard.addons.AddOn; import com.anysoftkeyboard.addons.AddOnsFactory; import com.menny.android.anysoftkeyboard.R; public class ExternalDictionaryFactory extends AddOnsFactory<DictionaryAddOnAndBuilder> { private static final String TAG = "ASK ExtDictFctry"; private static final String XML_LANGUAGE_ATTRIBUTE = "locale"; private static final String XML_ASSETS_ATTRIBUTE = "dictionaryAssertName"; private static final String XML_RESOURCE_ATTRIBUTE = "dictionaryResourceId"; private static final String XML_AUTO_TEXT_RESOURCE_ATTRIBUTE = "autoTextResourceId"; private static final String XML_INITIAL_SUGGESTIONS_ARRAY_RESOURCE_ATTRIBUTE = "initialSuggestions"; private static final ExternalDictionaryFactory msInstance; static { msInstance = new ExternalDictionaryFactory(); } public static ArrayList<DictionaryAddOnAndBuilder> getAllAvailableExternalDictionaries(Context askContext) { return msInstance.getAllAddOns(askContext); } public static DictionaryAddOnAndBuilder getDictionaryBuilderById(String id, Context askContext) { return msInstance.getAddOnById(id, askContext); } public static DictionaryAddOnAndBuilder getDictionaryBuilderByLocale(String locale, Context askContext) { return msInstance.getAddOnByLocale(locale, askContext); } private final HashMap<String, DictionaryAddOnAndBuilder> mBuildersByLocale = new HashMap<String, DictionaryAddOnAndBuilder>(); private ExternalDictionaryFactory() { super(TAG, "com.menny.android.anysoftkeyboard.DICTIONARY", "com.menny.android.anysoftkeyboard.dictionaries", "Dictionaries", "Dictionary", R.xml.dictionaries, true); } @Override protected synchronized void clearAddOnList() { super.clearAddOnList(); mBuildersByLocale.clear(); } @Override protected void buildOtherDataBasedOnNewAddOns( ArrayList<DictionaryAddOnAndBuilder> newAddOns) { super.buildOtherDataBasedOnNewAddOns(newAddOns); for(DictionaryAddOnAndBuilder addOn : newAddOns) mBuildersByLocale.put(addOn.getLanguage(), addOn); } public synchronized DictionaryAddOnAndBuilder getAddOnByLocale(String locale, Context askContext) { if (mBuildersByLocale.size() == 0) loadAddOns(askContext); return mBuildersByLocale.get(locale); } @Override protected DictionaryAddOnAndBuilder createConcreateAddOn(Context context, String prefId, int nameId, String description, int sortIndex, AttributeSet attrs) { final String language = attrs.getAttributeValue(null, XML_LANGUAGE_ATTRIBUTE); final String assets = attrs.getAttributeValue(null, XML_ASSETS_ATTRIBUTE); final int dictionaryResourceId = attrs.getAttributeResourceValue(null, XML_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int autoTextResId = attrs.getAttributeResourceValue(null, XML_AUTO_TEXT_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int initialSuggestionsId = attrs.getAttributeResourceValue(null, XML_INITIAL_SUGGESTIONS_ARRAY_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); //asserting if (TextUtils.isEmpty(prefId) ||(language == null) || (nameId == AddOn.INVALID_RES_ID) || ((assets == null) && (dictionaryResourceId == AddOn.INVALID_RES_ID))) { Log.e(TAG, "External dictionary does not include all mandatory details! Will not create dictionary."); return null; } else { final DictionaryAddOnAndBuilder creator; - if (dictionaryResourceId == -1) + if (dictionaryResourceId == AddOn.INVALID_RES_ID) creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, assets, initialSuggestionsId); else creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, dictionaryResourceId, autoTextResId, initialSuggestionsId); return creator; } } }
true
true
protected DictionaryAddOnAndBuilder createConcreateAddOn(Context context, String prefId, int nameId, String description, int sortIndex, AttributeSet attrs) { final String language = attrs.getAttributeValue(null, XML_LANGUAGE_ATTRIBUTE); final String assets = attrs.getAttributeValue(null, XML_ASSETS_ATTRIBUTE); final int dictionaryResourceId = attrs.getAttributeResourceValue(null, XML_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int autoTextResId = attrs.getAttributeResourceValue(null, XML_AUTO_TEXT_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int initialSuggestionsId = attrs.getAttributeResourceValue(null, XML_INITIAL_SUGGESTIONS_ARRAY_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); //asserting if (TextUtils.isEmpty(prefId) ||(language == null) || (nameId == AddOn.INVALID_RES_ID) || ((assets == null) && (dictionaryResourceId == AddOn.INVALID_RES_ID))) { Log.e(TAG, "External dictionary does not include all mandatory details! Will not create dictionary."); return null; } else { final DictionaryAddOnAndBuilder creator; if (dictionaryResourceId == -1) creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, assets, initialSuggestionsId); else creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, dictionaryResourceId, autoTextResId, initialSuggestionsId); return creator; } }
protected DictionaryAddOnAndBuilder createConcreateAddOn(Context context, String prefId, int nameId, String description, int sortIndex, AttributeSet attrs) { final String language = attrs.getAttributeValue(null, XML_LANGUAGE_ATTRIBUTE); final String assets = attrs.getAttributeValue(null, XML_ASSETS_ATTRIBUTE); final int dictionaryResourceId = attrs.getAttributeResourceValue(null, XML_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int autoTextResId = attrs.getAttributeResourceValue(null, XML_AUTO_TEXT_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); final int initialSuggestionsId = attrs.getAttributeResourceValue(null, XML_INITIAL_SUGGESTIONS_ARRAY_RESOURCE_ATTRIBUTE, AddOn.INVALID_RES_ID); //asserting if (TextUtils.isEmpty(prefId) ||(language == null) || (nameId == AddOn.INVALID_RES_ID) || ((assets == null) && (dictionaryResourceId == AddOn.INVALID_RES_ID))) { Log.e(TAG, "External dictionary does not include all mandatory details! Will not create dictionary."); return null; } else { final DictionaryAddOnAndBuilder creator; if (dictionaryResourceId == AddOn.INVALID_RES_ID) creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, assets, initialSuggestionsId); else creator = new DictionaryAddOnAndBuilder(context, prefId, nameId, description, sortIndex, language, dictionaryResourceId, autoTextResId, initialSuggestionsId); return creator; } }
diff --git a/src/main/java/org/seforge/monitor/web/MetricController.java b/src/main/java/org/seforge/monitor/web/MetricController.java index 79e835e..4a430a9 100644 --- a/src/main/java/org/seforge/monitor/web/MetricController.java +++ b/src/main/java/org/seforge/monitor/web/MetricController.java @@ -1,99 +1,101 @@ package org.seforge.monitor.web; import java.util.Date; import java.util.List; import org.hyperic.hq.hqapi1.types.LastMetricData; import org.seforge.monitor.domain.Metric; import org.seforge.monitor.domain.ResourceGroup; import org.seforge.monitor.domain.ResourcePrototype; import org.seforge.monitor.extjs.JsonObjectResponse; import org.seforge.monitor.hqapi.HQProxy; import org.seforge.monitor.manager.MetricManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import flexjson.JSONSerializer; import flexjson.transformer.DateTransformer; @RequestMapping("/metrics") @Controller public class MetricController { @Autowired private HQProxy proxy; @Autowired private MetricManager metricManager; //thd PathVariable id is the id of a metric @RequestMapping(value = "/{id}/lastmetricdata", method = RequestMethod.GET) public ResponseEntity<String> listLastMetricData(@PathVariable("id") Integer id) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if( id == null){ returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No Metric Id provided."); response.setSuccess(false); response.setTotal(0L); }else{ try { Metric metric = Metric.findMetric(id); LastMetricData data = proxy.getLastMetricData(metric); returnStatus = HttpStatus.OK; response.setMessage("Last Metric Data found"); response.setSuccess(true); response.setTotal(1); response.setData(data); } catch (Exception e) { returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer().exclude("*.class").transform(new DateTransformer("MM/dd/yy"), Date.class).serialize(response), returnStatus); } //thd PathVariable id is the id of a resourcePrototype @RequestMapping(value = "/all", method = RequestMethod.GET) - public ResponseEntity<String> listAllMetrics(@RequestParam("groupId") Integer groupId, @RequestParam("resourcePrototypeId") Integer resourcePrototypeId) { + public ResponseEntity<String> listAllMetrics(@RequestParam("groupId") Integer groupId, @RequestParam("resourcePrototypeId") Integer resourcePrototypeId, + @RequestParam("start") Integer start, @RequestParam("limit") Integer limit ) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if( groupId == null){ returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No ResourcePrototype Id provided."); response.setSuccess(false); response.setTotal(0L); }else{ try { ResourcePrototype prototype = ResourcePrototype.findResourcePrototype(resourcePrototypeId); ResourceGroup group = ResourceGroup.findResourceGroup(groupId); - List data = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group, 0, 10); + List total = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group); + List data = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group, start, limit); returnStatus = HttpStatus.OK; response.setMessage("All Metric Templates found"); response.setSuccess(true); - response.setTotal(data.size()); + response.setTotal(total.size()); response.setData(data); } catch (Exception e) { returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer().exclude("*.class").transform(new DateTransformer("MM/dd/yy"), Date.class).serialize(response), returnStatus); } }
false
true
public ResponseEntity<String> listAllMetrics(@RequestParam("groupId") Integer groupId, @RequestParam("resourcePrototypeId") Integer resourcePrototypeId) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if( groupId == null){ returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No ResourcePrototype Id provided."); response.setSuccess(false); response.setTotal(0L); }else{ try { ResourcePrototype prototype = ResourcePrototype.findResourcePrototype(resourcePrototypeId); ResourceGroup group = ResourceGroup.findResourceGroup(groupId); List data = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group, 0, 10); returnStatus = HttpStatus.OK; response.setMessage("All Metric Templates found"); response.setSuccess(true); response.setTotal(data.size()); response.setData(data); } catch (Exception e) { returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer().exclude("*.class").transform(new DateTransformer("MM/dd/yy"), Date.class).serialize(response), returnStatus); }
public ResponseEntity<String> listAllMetrics(@RequestParam("groupId") Integer groupId, @RequestParam("resourcePrototypeId") Integer resourcePrototypeId, @RequestParam("start") Integer start, @RequestParam("limit") Integer limit ) { HttpStatus returnStatus; JsonObjectResponse response = new JsonObjectResponse(); if( groupId == null){ returnStatus = HttpStatus.BAD_REQUEST; response.setMessage("No ResourcePrototype Id provided."); response.setSuccess(false); response.setTotal(0L); }else{ try { ResourcePrototype prototype = ResourcePrototype.findResourcePrototype(resourcePrototypeId); ResourceGroup group = ResourceGroup.findResourceGroup(groupId); List total = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group); List data = metricManager.getMetricsByResourcePrototypeAndGroup(prototype, group, start, limit); returnStatus = HttpStatus.OK; response.setMessage("All Metric Templates found"); response.setSuccess(true); response.setTotal(total.size()); response.setData(data); } catch (Exception e) { returnStatus = HttpStatus.INTERNAL_SERVER_ERROR; response.setMessage(e.getMessage()); response.setSuccess(false); response.setTotal(0L); } } return new ResponseEntity<String>(new JSONSerializer().exclude("*.class").transform(new DateTransformer("MM/dd/yy"), Date.class).serialize(response), returnStatus); }
diff --git a/src/test/java/javax/time/calendar/format/TestDateTimeFormatters.java b/src/test/java/javax/time/calendar/format/TestDateTimeFormatters.java index 0b451cfc..fb9ff21b 100644 --- a/src/test/java/javax/time/calendar/format/TestDateTimeFormatters.java +++ b/src/test/java/javax/time/calendar/format/TestDateTimeFormatters.java @@ -1,240 +1,240 @@ /* * Copyright (c) 2008, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.time.calendar.format; import static org.testng.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Iterator; import javax.time.calendar.Calendrical; import javax.time.calendar.CalendricalProvider; import javax.time.calendar.ISOChronology; import javax.time.calendar.LocalDateTime; import javax.time.calendar.TimeZone; import javax.time.calendar.YearMonth; import javax.time.calendar.ZonedDateTime; import javax.time.calendar.field.WeekOfWeekyear; import javax.time.calendar.field.Weekyear; import javax.time.calendar.field.Year; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test DateTimeFormatters. * * @author Michael Nascimento Santos * @author Stephen Colebourne */ @Test public class TestDateTimeFormatters { @BeforeMethod public void setUp() { } @SuppressWarnings("unchecked") public void test_constructor() throws Exception { for (Constructor constructor : DateTimeFormatters.class.getDeclaredConstructors()) { assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); constructor.newInstance(Collections.nCopies(constructor.getParameterTypes().length, null).toArray()); } } //----------------------------------------------------------------------- @Test(expectedExceptions=NullPointerException.class) public void test_print_nullCalendrical() { DateTimeFormatters.isoDate().print((CalendricalProvider) null); } //----------------------------------------------------------------------- public void test_print_isoDate() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC); assertEquals(DateTimeFormatters.isoDate().print(test), "2008-06-03"); } public void test_print_isoDate_missingField() { try { CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical(); DateTimeFormatters.isoDate().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.dayOfMonthRule()); assertEquals(ex.getValue(), null); } } //----------------------------------------------------------------------- public void test_print_isoTime() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC); assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30"); } public void test_print_isoTime_nanos1() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 1), TimeZone.UTC); assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.000000001"); } public void test_print_isoTime_nanos2() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 500000000), TimeZone.UTC); assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.5"); } public void test_print_isoTime_nanos3() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30, 123456000), TimeZone.UTC); assertEquals(DateTimeFormatters.isoTime().print(test), "11:05:30.123456"); } public void test_print_isoTime_missingField() { try { CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical(); DateTimeFormatters.isoTime().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.hourOfDay()); assertEquals(ex.getValue(), null); } } //----------------------------------------------------------------------- public void test_print_isoOrdinalDate() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC); assertEquals(DateTimeFormatters.isoOrdinalDate().print(test), "2008-155"); } public void test_print_isoOrdinalDate_missingField() { try { CalendricalProvider test = Year.isoYear(2008).toCalendrical(); DateTimeFormatters.isoOrdinalDate().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfYear()); assertEquals(ex.getValue(), null); } } //----------------------------------------------------------------------- public void test_print_basicIsoDate() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC); assertEquals(DateTimeFormatters.basicIsoDate().print(test), "20080603"); } public void test_print_basicIsoDate_missingField() { try { CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical(); DateTimeFormatters.basicIsoDate().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfMonth()); assertEquals(ex.getValue(), null); } } //----------------------------------------------------------------------- @DataProvider(name="weekDate") Iterator<Object[]> weekDate() { return new Iterator<Object[]>() { private ZonedDateTime date = ZonedDateTime.dateTime(LocalDateTime.dateTime(2003, 12, 29, 11, 5, 30), TimeZone.UTC); private ZonedDateTime endDate = date.withDate(2005, 1, 2); private int week = 1; private int day = 1; public boolean hasNext() { - return !endDate.isAfter(date); + return !date.isAfter(endDate); } public Object[] next() { StringBuilder sb = new StringBuilder("2004-W"); if (week < 10) { sb.append('0'); } sb.append(week).append('-').append(day); Object[] ret = new Object[] {date, sb.toString()}; date = date.plusDays(1); day += 1; if (day == 8) { day = 1; week++; } return ret; } public void remove() { throw new UnsupportedOperationException(); } }; } @Test(dataProvider="weekDate") public void test_print_weekDate(CalendricalProvider test, String expected) { assertEquals(DateTimeFormatters.isoWeekDate().print(test), expected); } public void test_print_weekDate_missingField() { try { CalendricalProvider test = Calendrical.calendrical(Weekyear.rule(), 2004, WeekOfWeekyear.rule(), 1); DateTimeFormatters.isoWeekDate().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfWeek()); assertEquals(ex.getValue(), null); } } //----------------------------------------------------------------------- public void test_print_rfc1123() { CalendricalProvider test = ZonedDateTime.dateTime(LocalDateTime.dateTime(2008, 6, 3, 11, 5, 30), TimeZone.UTC); assertEquals(DateTimeFormatters.rfc1123().print(test), "Tue, 03 Jun 2008 11:05:30 Z"); } public void test_print_rfc1123_missingField() { try { CalendricalProvider test = YearMonth.yearMonth(2008, 6).toCalendrical(); DateTimeFormatters.rfc1123().print(test); fail(); } catch (CalendricalFormatFieldException ex) { assertEquals(ex.getFieldRule(), ISOChronology.INSTANCE.dayOfWeek()); assertEquals(ex.getValue(), null); } } }
true
true
Iterator<Object[]> weekDate() { return new Iterator<Object[]>() { private ZonedDateTime date = ZonedDateTime.dateTime(LocalDateTime.dateTime(2003, 12, 29, 11, 5, 30), TimeZone.UTC); private ZonedDateTime endDate = date.withDate(2005, 1, 2); private int week = 1; private int day = 1; public boolean hasNext() { return !endDate.isAfter(date); } public Object[] next() { StringBuilder sb = new StringBuilder("2004-W"); if (week < 10) { sb.append('0'); } sb.append(week).append('-').append(day); Object[] ret = new Object[] {date, sb.toString()}; date = date.plusDays(1); day += 1; if (day == 8) { day = 1; week++; } return ret; } public void remove() { throw new UnsupportedOperationException(); } }; }
Iterator<Object[]> weekDate() { return new Iterator<Object[]>() { private ZonedDateTime date = ZonedDateTime.dateTime(LocalDateTime.dateTime(2003, 12, 29, 11, 5, 30), TimeZone.UTC); private ZonedDateTime endDate = date.withDate(2005, 1, 2); private int week = 1; private int day = 1; public boolean hasNext() { return !date.isAfter(endDate); } public Object[] next() { StringBuilder sb = new StringBuilder("2004-W"); if (week < 10) { sb.append('0'); } sb.append(week).append('-').append(day); Object[] ret = new Object[] {date, sb.toString()}; date = date.plusDays(1); day += 1; if (day == 8) { day = 1; week++; } return ret; } public void remove() { throw new UnsupportedOperationException(); } }; }
diff --git a/src/main/org/codehaus/groovy/ast/CompileUnit.java b/src/main/org/codehaus/groovy/ast/CompileUnit.java index 674397a92..eae0c9f16 100644 --- a/src/main/org/codehaus/groovy/ast/CompileUnit.java +++ b/src/main/org/codehaus/groovy/ast/CompileUnit.java @@ -1,175 +1,175 @@ /* * Copyright 2003-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.ast; import groovy.lang.GroovyClassLoader; import java.security.CodeSource; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.SyntaxException; /** * Represents the entire contents of a compilation step which consists of one * or more {@link ModuleNode}instances * * @author <a href="mailto:[email protected]">James Strachan </a> * @version $Revision$ */ public class CompileUnit { private final List modules = new ArrayList(); private Map classes = new HashMap(); private CompilerConfiguration config; private GroovyClassLoader classLoader; private CodeSource codeSource; private Map classesToCompile = new HashMap(); private Map classNameToSource = new HashMap(); public CompileUnit(GroovyClassLoader classLoader, CompilerConfiguration config) { this(classLoader, null, config); } public CompileUnit(GroovyClassLoader classLoader, CodeSource codeSource, CompilerConfiguration config) { this.classLoader = classLoader; this.config = config; this.codeSource = codeSource; } public List getModules() { return modules; } public void addModule(ModuleNode node) { // node==null means a compilation error prevented // groovy from building an ast if (node==null) return; modules.add(node); node.setUnit(this); addClasses(node.getClasses()); } /** * @return the ClassNode for the given qualified name or returns null if * the name does not exist in the current compilation unit * (ignoring the .class files on the classpath) */ public ClassNode getClass(String name) { ClassNode cn = (ClassNode) classes.get(name); if (cn!=null) return cn; return (ClassNode) classesToCompile.get(name); } /** * @return a list of all the classes in each module in the compilation unit */ public List getClasses() { List answer = new ArrayList(); for (Iterator iter = modules.iterator(); iter.hasNext();) { ModuleNode module = (ModuleNode) iter.next(); answer.addAll(module.getClasses()); } return answer; } public CompilerConfiguration getConfig() { return config; } public GroovyClassLoader getClassLoader() { return classLoader; } public CodeSource getCodeSource() { return codeSource; } /** * Appends all of the fully qualified class names in this * module into the given map */ void addClasses(List classList) { for (Iterator iter = classList.iterator(); iter.hasNext();) { addClass((ClassNode) iter.next()); } } /** * Adds a class to the unit. */ public void addClass(ClassNode node) { node = node.redirect(); String name = node.getName(); ClassNode stored = (ClassNode) classes.get(name); if (stored != null && stored != node) { // we have a duplicate class! // One possibility for this is, that we delcared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node.getModule().getContext(); SourceUnit storedSource = stored.getModule().getContext(); String txt = "Invalid duplicate class definition of class "+node.getName()+" : "; if (nodeSource==storedSource) { // same class in same source - txt += "The source "+nodeSource.getName()+" contains at last two defintions of the class "+node.getName()+".\n"; + txt += "The source "+nodeSource.getName()+" contains at least two defintions of the class "+node.getName()+".\n"; if (node.isScriptBody() || stored.isScriptBody()) { txt += "One of the classes is a explicit generated class using the class statement, the other is a class generated from"+ " the script body based on the file name. Solutions are to change the file name or to change the class name.\n"; } } else { txt += "The sources "+nodeSource.getName()+" and "+storedSource.getName()+" are containing both a class of the name "+node.getName()+".\n"; } nodeSource.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber()), nodeSource) ); } classes.put(name, node); if (classesToCompile.containsKey(name)) { ClassNode cn = (ClassNode) classesToCompile.get(name); cn.setRedirect(node); classesToCompile.remove(name); } } /** * this emthod actually does not compile a class. It's only * a marker that this type has to be compiled by the CompilationUnit * at the end of a parse step no node should be be left. */ public void addClassNodeToCompile(ClassNode node, SourceUnit location) { classesToCompile.put(node.getName(),node); classNameToSource.put(node.getName(),location); } public SourceUnit getScriptSourceLocation(String className) { return (SourceUnit) classNameToSource.get(className); } public boolean hasClassNodeToCompile(){ return !classesToCompile.isEmpty(); } public Iterator iterateClassNodeToCompile(){ return classesToCompile.keySet().iterator(); } }
true
true
public void addClass(ClassNode node) { node = node.redirect(); String name = node.getName(); ClassNode stored = (ClassNode) classes.get(name); if (stored != null && stored != node) { // we have a duplicate class! // One possibility for this is, that we delcared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node.getModule().getContext(); SourceUnit storedSource = stored.getModule().getContext(); String txt = "Invalid duplicate class definition of class "+node.getName()+" : "; if (nodeSource==storedSource) { // same class in same source txt += "The source "+nodeSource.getName()+" contains at last two defintions of the class "+node.getName()+".\n"; if (node.isScriptBody() || stored.isScriptBody()) { txt += "One of the classes is a explicit generated class using the class statement, the other is a class generated from"+ " the script body based on the file name. Solutions are to change the file name or to change the class name.\n"; } } else { txt += "The sources "+nodeSource.getName()+" and "+storedSource.getName()+" are containing both a class of the name "+node.getName()+".\n"; } nodeSource.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber()), nodeSource) ); } classes.put(name, node); if (classesToCompile.containsKey(name)) { ClassNode cn = (ClassNode) classesToCompile.get(name); cn.setRedirect(node); classesToCompile.remove(name); } }
public void addClass(ClassNode node) { node = node.redirect(); String name = node.getName(); ClassNode stored = (ClassNode) classes.get(name); if (stored != null && stored != node) { // we have a duplicate class! // One possibility for this is, that we delcared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node.getModule().getContext(); SourceUnit storedSource = stored.getModule().getContext(); String txt = "Invalid duplicate class definition of class "+node.getName()+" : "; if (nodeSource==storedSource) { // same class in same source txt += "The source "+nodeSource.getName()+" contains at least two defintions of the class "+node.getName()+".\n"; if (node.isScriptBody() || stored.isScriptBody()) { txt += "One of the classes is a explicit generated class using the class statement, the other is a class generated from"+ " the script body based on the file name. Solutions are to change the file name or to change the class name.\n"; } } else { txt += "The sources "+nodeSource.getName()+" and "+storedSource.getName()+" are containing both a class of the name "+node.getName()+".\n"; } nodeSource.getErrorCollector().addErrorAndContinue( new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber()), nodeSource) ); } classes.put(name, node); if (classesToCompile.containsKey(name)) { ClassNode cn = (ClassNode) classesToCompile.get(name); cn.setRedirect(node); classesToCompile.remove(name); } }
diff --git a/src/org/coronastreet/gpxconverter/MainWindow.java b/src/org/coronastreet/gpxconverter/MainWindow.java index 0ccf757..915eb99 100644 --- a/src/org/coronastreet/gpxconverter/MainWindow.java +++ b/src/org/coronastreet/gpxconverter/MainWindow.java @@ -1,301 +1,301 @@ package org.coronastreet.gpxconverter; import java.awt.EventQueue; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.SwingConstants; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JFileChooser; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JTextArea; import java.io.File; import javax.swing.JScrollPane; import java.awt.Font; import javax.swing.JRadioButton; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class MainWindow { private JFrame frmStravaGpxConverter; private JTextField txtSourceFile; private JFileChooser fc; private JTextArea statusTextArea; protected String newline = "\n"; private JTextField loginVal; private JPasswordField passwordVal; private JTextField txtActivityName; private String activityType; private String altimeterEval; private String authToken; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.frmStravaGpxConverter.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } protected void statusLog(String actionDescription) { statusTextArea.append(actionDescription + newline); statusTextArea.setCaretPosition(statusTextArea.getDocument().getLength()-1); } protected boolean doLogin() { boolean ret = false; HttpClient httpClient = new DefaultHttpClient(); statusLog("Authenticating athlete..."); try { HttpPost request = new HttpPost("http://www.strava.com/api/v2/authentication/login"); String jsonString = "{\"email\":\"" + loginVal.getText() + "\",\"password\":\"" + new String(passwordVal.getPassword()) + "\"} "; StringEntity params = new StringEntity(jsonString); //statusLog("Sending Entity: " + jsonString); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { statusLog("Failed to Login."); HttpEntity entity = response.getEntity(); if (entity != null) { String output = EntityUtils.toString(entity); statusLog(output); } } HttpEntity entity = response.getEntity(); if (entity != null) { String output = EntityUtils.toString(entity); //statusLog(output); JSONObject userInfo = new JSONObject(output); JSONObject athleteInfo = userInfo.getJSONObject("athlete"); statusLog("Logged in as " + athleteInfo.get("name")); authToken = (String)userInfo.get("token"); if (authToken.length() > 0) { ret = true; } } else { statusLog("What happened?!"); } }catch (Exception ex) { // handle exception here ex.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return ret; } /** * Initialize the contents of the frame. */ private void initialize() { frmStravaGpxConverter = new JFrame(); frmStravaGpxConverter.getContentPane().setFont(new Font("Tahoma", Font.BOLD, 11)); frmStravaGpxConverter.setTitle("Garmin GPX Importer for Strava"); frmStravaGpxConverter.setBounds(100, 100, 441, 426); frmStravaGpxConverter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmStravaGpxConverter.getContentPane().setLayout(null); fc = new JFileChooser(); JLabel lblThisToolConverts = new JLabel("Upload Ride Data from a Garmin GPX file with HR and Cadence data."); lblThisToolConverts.setFont(new Font("Tahoma", Font.BOLD, 11)); lblThisToolConverts.setHorizontalAlignment(SwingConstants.CENTER); lblThisToolConverts.setBounds(10, 11, 405, 14); frmStravaGpxConverter.getContentPane().add(lblThisToolConverts); txtSourceFile = new JTextField(); txtSourceFile.setBounds(24, 36, 286, 20); frmStravaGpxConverter.getContentPane().add(txtSourceFile); txtSourceFile.setColumns(10); statusTextArea = new JTextArea(); statusTextArea.setEditable(false); statusTextArea.setColumns(100); statusTextArea.setRows(100); statusTextArea.setLineWrap(true); JScrollPane statusScroller = new JScrollPane(statusTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); statusScroller.setBounds(10, 254, 405, 112); frmStravaGpxConverter.getContentPane().add(statusScroller); JLabel lblSourceGpxFile = new JLabel("Source GPX File"); lblSourceGpxFile.setBounds(24, 57, 111, 14); frmStravaGpxConverter.getContentPane().add(lblSourceGpxFile); JButton btnNewButton = new JButton("Find Src"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc.setFileFilter(new GPXFilter()); int returnVal = fc.showDialog(frmStravaGpxConverter, "Choose Source"); if (returnVal == JFileChooser.APPROVE_OPTION) { txtSourceFile.setText(fc.getSelectedFile().getPath()); File f = new File(""); fc.setSelectedFile(f); } } }); - btnNewButton.setBounds(320, 34, 78, 23); + btnNewButton.setBounds(320, 34, 95, 23); frmStravaGpxConverter.getContentPane().add(btnNewButton); loginVal = new JTextField(); loginVal.setBounds(100, 80, 210, 20); frmStravaGpxConverter.getContentPane().add(loginVal); loginVal.setColumns(10); passwordVal = new JPasswordField(); passwordVal.setBounds(100, 110, 210, 20); frmStravaGpxConverter.getContentPane().add(passwordVal); passwordVal.setColumns(10); JLabel lblLogin = new JLabel("Login:"); lblLogin.setHorizontalAlignment(SwingConstants.RIGHT); lblLogin.setBounds(45, 82, 51, 14); frmStravaGpxConverter.getContentPane().add(lblLogin); JLabel lblNewLabel = new JLabel("Password:"); lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT); lblNewLabel.setBounds(24, 111, 72, 14); frmStravaGpxConverter.getContentPane().add(lblNewLabel); JRadioButton typeIsRide = new JRadioButton("Ride"); typeIsRide.setBounds(144, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRide); JRadioButton typeIsRun = new JRadioButton("Run"); typeIsRun.setBounds(211, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRun); JRadioButton typeIsHike = new JRadioButton("Hike"); typeIsHike.setBounds(270, 175, 109, 23); frmStravaGpxConverter.getContentPane().add(typeIsHike); ButtonGroup eventType = new ButtonGroup(); eventType.add(typeIsHike); eventType.add(typeIsRun); eventType.add(typeIsRide); typeIsHike.addActionListener(new TypeAction()); typeIsRun.addActionListener(new TypeAction()); typeIsRide.addActionListener(new TypeAction()); JLabel lblAltimeter = new JLabel("Altimeter:"); lblAltimeter.setHorizontalAlignment(SwingConstants.RIGHT); lblAltimeter.setBounds(10, 204, 86, 14); frmStravaGpxConverter.getContentPane().add(lblAltimeter); JRadioButton altYes = new JRadioButton("Yes"); altYes.setBounds(144, 196, 51, 23); frmStravaGpxConverter.getContentPane().add(altYes); JRadioButton altNo = new JRadioButton("No"); altNo.setBounds(211, 196, 57, 23); frmStravaGpxConverter.getContentPane().add(altNo); ButtonGroup altimeterAvail = new ButtonGroup(); altimeterAvail.add(altYes); altimeterAvail.add(altNo); altYes.addActionListener(new DeviceAction()); altNo.addActionListener(new DeviceAction()); JLabel lblActivityType = new JLabel("Activity Type:"); lblActivityType.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityType.setBounds(10, 179, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityType); JLabel lblActivityName = new JLabel("Activity Name:"); lblActivityName.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityName.setBounds(10, 148, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityName); txtActivityName = new JTextField(); txtActivityName.setBounds(100, 147, 315, 20); frmStravaGpxConverter.getContentPane().add(txtActivityName); txtActivityName.setColumns(10); JButton btnConvertIt = new JButton("Upload Data"); btnConvertIt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (doLogin()) { // Check stuff //if (txtSourceFile.getText().equals(txtDestFile.getText())) { // txtStatusArea.append("Can't write to same file you read from!\n"); // return; //} Converter c = new Converter(); c.setInFile(txtSourceFile.getText()); c.setAuthToken(authToken); c.setActivityName(txtActivityName.getText()); c.setActivityType(activityType); if (altimeterEval.startsWith("Yes")) { c.setDeviceType("Garmin Edge 800"); } else { c.setDeviceType("Garmin Edge 200"); } //c.setOutFile(txtDestFile.getText()); statusLog("Starting Conversion and Upload..."); c.convert(statusTextArea); statusLog("Finished!"); } else { statusLog("Problems Authenticating."); } } }); btnConvertIt.setBounds(144, 226, 131, 23); frmStravaGpxConverter.getContentPane().add(btnConvertIt); } public class TypeAction implements ActionListener { public void actionPerformed(ActionEvent e) { activityType = e.getActionCommand(); } } public class DeviceAction implements ActionListener { public void actionPerformed(ActionEvent e) { altimeterEval = e.getActionCommand(); } } }
true
true
private void initialize() { frmStravaGpxConverter = new JFrame(); frmStravaGpxConverter.getContentPane().setFont(new Font("Tahoma", Font.BOLD, 11)); frmStravaGpxConverter.setTitle("Garmin GPX Importer for Strava"); frmStravaGpxConverter.setBounds(100, 100, 441, 426); frmStravaGpxConverter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmStravaGpxConverter.getContentPane().setLayout(null); fc = new JFileChooser(); JLabel lblThisToolConverts = new JLabel("Upload Ride Data from a Garmin GPX file with HR and Cadence data."); lblThisToolConverts.setFont(new Font("Tahoma", Font.BOLD, 11)); lblThisToolConverts.setHorizontalAlignment(SwingConstants.CENTER); lblThisToolConverts.setBounds(10, 11, 405, 14); frmStravaGpxConverter.getContentPane().add(lblThisToolConverts); txtSourceFile = new JTextField(); txtSourceFile.setBounds(24, 36, 286, 20); frmStravaGpxConverter.getContentPane().add(txtSourceFile); txtSourceFile.setColumns(10); statusTextArea = new JTextArea(); statusTextArea.setEditable(false); statusTextArea.setColumns(100); statusTextArea.setRows(100); statusTextArea.setLineWrap(true); JScrollPane statusScroller = new JScrollPane(statusTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); statusScroller.setBounds(10, 254, 405, 112); frmStravaGpxConverter.getContentPane().add(statusScroller); JLabel lblSourceGpxFile = new JLabel("Source GPX File"); lblSourceGpxFile.setBounds(24, 57, 111, 14); frmStravaGpxConverter.getContentPane().add(lblSourceGpxFile); JButton btnNewButton = new JButton("Find Src"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc.setFileFilter(new GPXFilter()); int returnVal = fc.showDialog(frmStravaGpxConverter, "Choose Source"); if (returnVal == JFileChooser.APPROVE_OPTION) { txtSourceFile.setText(fc.getSelectedFile().getPath()); File f = new File(""); fc.setSelectedFile(f); } } }); btnNewButton.setBounds(320, 34, 78, 23); frmStravaGpxConverter.getContentPane().add(btnNewButton); loginVal = new JTextField(); loginVal.setBounds(100, 80, 210, 20); frmStravaGpxConverter.getContentPane().add(loginVal); loginVal.setColumns(10); passwordVal = new JPasswordField(); passwordVal.setBounds(100, 110, 210, 20); frmStravaGpxConverter.getContentPane().add(passwordVal); passwordVal.setColumns(10); JLabel lblLogin = new JLabel("Login:"); lblLogin.setHorizontalAlignment(SwingConstants.RIGHT); lblLogin.setBounds(45, 82, 51, 14); frmStravaGpxConverter.getContentPane().add(lblLogin); JLabel lblNewLabel = new JLabel("Password:"); lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT); lblNewLabel.setBounds(24, 111, 72, 14); frmStravaGpxConverter.getContentPane().add(lblNewLabel); JRadioButton typeIsRide = new JRadioButton("Ride"); typeIsRide.setBounds(144, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRide); JRadioButton typeIsRun = new JRadioButton("Run"); typeIsRun.setBounds(211, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRun); JRadioButton typeIsHike = new JRadioButton("Hike"); typeIsHike.setBounds(270, 175, 109, 23); frmStravaGpxConverter.getContentPane().add(typeIsHike); ButtonGroup eventType = new ButtonGroup(); eventType.add(typeIsHike); eventType.add(typeIsRun); eventType.add(typeIsRide); typeIsHike.addActionListener(new TypeAction()); typeIsRun.addActionListener(new TypeAction()); typeIsRide.addActionListener(new TypeAction()); JLabel lblAltimeter = new JLabel("Altimeter:"); lblAltimeter.setHorizontalAlignment(SwingConstants.RIGHT); lblAltimeter.setBounds(10, 204, 86, 14); frmStravaGpxConverter.getContentPane().add(lblAltimeter); JRadioButton altYes = new JRadioButton("Yes"); altYes.setBounds(144, 196, 51, 23); frmStravaGpxConverter.getContentPane().add(altYes); JRadioButton altNo = new JRadioButton("No"); altNo.setBounds(211, 196, 57, 23); frmStravaGpxConverter.getContentPane().add(altNo); ButtonGroup altimeterAvail = new ButtonGroup(); altimeterAvail.add(altYes); altimeterAvail.add(altNo); altYes.addActionListener(new DeviceAction()); altNo.addActionListener(new DeviceAction()); JLabel lblActivityType = new JLabel("Activity Type:"); lblActivityType.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityType.setBounds(10, 179, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityType); JLabel lblActivityName = new JLabel("Activity Name:"); lblActivityName.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityName.setBounds(10, 148, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityName); txtActivityName = new JTextField(); txtActivityName.setBounds(100, 147, 315, 20); frmStravaGpxConverter.getContentPane().add(txtActivityName); txtActivityName.setColumns(10); JButton btnConvertIt = new JButton("Upload Data"); btnConvertIt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (doLogin()) { // Check stuff //if (txtSourceFile.getText().equals(txtDestFile.getText())) { // txtStatusArea.append("Can't write to same file you read from!\n"); // return; //} Converter c = new Converter(); c.setInFile(txtSourceFile.getText()); c.setAuthToken(authToken); c.setActivityName(txtActivityName.getText()); c.setActivityType(activityType); if (altimeterEval.startsWith("Yes")) { c.setDeviceType("Garmin Edge 800"); } else { c.setDeviceType("Garmin Edge 200"); } //c.setOutFile(txtDestFile.getText()); statusLog("Starting Conversion and Upload..."); c.convert(statusTextArea); statusLog("Finished!"); } else { statusLog("Problems Authenticating."); } } }); btnConvertIt.setBounds(144, 226, 131, 23); frmStravaGpxConverter.getContentPane().add(btnConvertIt); }
private void initialize() { frmStravaGpxConverter = new JFrame(); frmStravaGpxConverter.getContentPane().setFont(new Font("Tahoma", Font.BOLD, 11)); frmStravaGpxConverter.setTitle("Garmin GPX Importer for Strava"); frmStravaGpxConverter.setBounds(100, 100, 441, 426); frmStravaGpxConverter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmStravaGpxConverter.getContentPane().setLayout(null); fc = new JFileChooser(); JLabel lblThisToolConverts = new JLabel("Upload Ride Data from a Garmin GPX file with HR and Cadence data."); lblThisToolConverts.setFont(new Font("Tahoma", Font.BOLD, 11)); lblThisToolConverts.setHorizontalAlignment(SwingConstants.CENTER); lblThisToolConverts.setBounds(10, 11, 405, 14); frmStravaGpxConverter.getContentPane().add(lblThisToolConverts); txtSourceFile = new JTextField(); txtSourceFile.setBounds(24, 36, 286, 20); frmStravaGpxConverter.getContentPane().add(txtSourceFile); txtSourceFile.setColumns(10); statusTextArea = new JTextArea(); statusTextArea.setEditable(false); statusTextArea.setColumns(100); statusTextArea.setRows(100); statusTextArea.setLineWrap(true); JScrollPane statusScroller = new JScrollPane(statusTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); statusScroller.setBounds(10, 254, 405, 112); frmStravaGpxConverter.getContentPane().add(statusScroller); JLabel lblSourceGpxFile = new JLabel("Source GPX File"); lblSourceGpxFile.setBounds(24, 57, 111, 14); frmStravaGpxConverter.getContentPane().add(lblSourceGpxFile); JButton btnNewButton = new JButton("Find Src"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc.setFileFilter(new GPXFilter()); int returnVal = fc.showDialog(frmStravaGpxConverter, "Choose Source"); if (returnVal == JFileChooser.APPROVE_OPTION) { txtSourceFile.setText(fc.getSelectedFile().getPath()); File f = new File(""); fc.setSelectedFile(f); } } }); btnNewButton.setBounds(320, 34, 95, 23); frmStravaGpxConverter.getContentPane().add(btnNewButton); loginVal = new JTextField(); loginVal.setBounds(100, 80, 210, 20); frmStravaGpxConverter.getContentPane().add(loginVal); loginVal.setColumns(10); passwordVal = new JPasswordField(); passwordVal.setBounds(100, 110, 210, 20); frmStravaGpxConverter.getContentPane().add(passwordVal); passwordVal.setColumns(10); JLabel lblLogin = new JLabel("Login:"); lblLogin.setHorizontalAlignment(SwingConstants.RIGHT); lblLogin.setBounds(45, 82, 51, 14); frmStravaGpxConverter.getContentPane().add(lblLogin); JLabel lblNewLabel = new JLabel("Password:"); lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT); lblNewLabel.setBounds(24, 111, 72, 14); frmStravaGpxConverter.getContentPane().add(lblNewLabel); JRadioButton typeIsRide = new JRadioButton("Ride"); typeIsRide.setBounds(144, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRide); JRadioButton typeIsRun = new JRadioButton("Run"); typeIsRun.setBounds(211, 175, 57, 23); frmStravaGpxConverter.getContentPane().add(typeIsRun); JRadioButton typeIsHike = new JRadioButton("Hike"); typeIsHike.setBounds(270, 175, 109, 23); frmStravaGpxConverter.getContentPane().add(typeIsHike); ButtonGroup eventType = new ButtonGroup(); eventType.add(typeIsHike); eventType.add(typeIsRun); eventType.add(typeIsRide); typeIsHike.addActionListener(new TypeAction()); typeIsRun.addActionListener(new TypeAction()); typeIsRide.addActionListener(new TypeAction()); JLabel lblAltimeter = new JLabel("Altimeter:"); lblAltimeter.setHorizontalAlignment(SwingConstants.RIGHT); lblAltimeter.setBounds(10, 204, 86, 14); frmStravaGpxConverter.getContentPane().add(lblAltimeter); JRadioButton altYes = new JRadioButton("Yes"); altYes.setBounds(144, 196, 51, 23); frmStravaGpxConverter.getContentPane().add(altYes); JRadioButton altNo = new JRadioButton("No"); altNo.setBounds(211, 196, 57, 23); frmStravaGpxConverter.getContentPane().add(altNo); ButtonGroup altimeterAvail = new ButtonGroup(); altimeterAvail.add(altYes); altimeterAvail.add(altNo); altYes.addActionListener(new DeviceAction()); altNo.addActionListener(new DeviceAction()); JLabel lblActivityType = new JLabel("Activity Type:"); lblActivityType.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityType.setBounds(10, 179, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityType); JLabel lblActivityName = new JLabel("Activity Name:"); lblActivityName.setHorizontalAlignment(SwingConstants.RIGHT); lblActivityName.setBounds(10, 148, 86, 14); frmStravaGpxConverter.getContentPane().add(lblActivityName); txtActivityName = new JTextField(); txtActivityName.setBounds(100, 147, 315, 20); frmStravaGpxConverter.getContentPane().add(txtActivityName); txtActivityName.setColumns(10); JButton btnConvertIt = new JButton("Upload Data"); btnConvertIt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (doLogin()) { // Check stuff //if (txtSourceFile.getText().equals(txtDestFile.getText())) { // txtStatusArea.append("Can't write to same file you read from!\n"); // return; //} Converter c = new Converter(); c.setInFile(txtSourceFile.getText()); c.setAuthToken(authToken); c.setActivityName(txtActivityName.getText()); c.setActivityType(activityType); if (altimeterEval.startsWith("Yes")) { c.setDeviceType("Garmin Edge 800"); } else { c.setDeviceType("Garmin Edge 200"); } //c.setOutFile(txtDestFile.getText()); statusLog("Starting Conversion and Upload..."); c.convert(statusTextArea); statusLog("Finished!"); } else { statusLog("Problems Authenticating."); } } }); btnConvertIt.setBounds(144, 226, 131, 23); frmStravaGpxConverter.getContentPane().add(btnConvertIt); }
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/JSONElementConverter.java b/CubicRecorder/src/main/java/org/cubictest/recorder/JSONElementConverter.java index b2539647..b2524221 100644 --- a/CubicRecorder/src/main/java/org/cubictest/recorder/JSONElementConverter.java +++ b/CubicRecorder/src/main/java/org/cubictest/recorder/JSONElementConverter.java @@ -1,224 +1,224 @@ /* * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html */ package org.cubictest.recorder; import java.text.ParseException; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.tools.ant.util.regexp.Regexp; import org.cubictest.model.Identifier; import org.cubictest.model.IdentifierType; import org.cubictest.model.Image; import org.cubictest.model.Link; import org.cubictest.model.PageElement; import org.cubictest.model.Title; import org.cubictest.model.context.SimpleContext; import org.cubictest.model.formElement.Button; import org.cubictest.model.formElement.Checkbox; import org.cubictest.model.formElement.Option; import org.cubictest.model.formElement.Password; import org.cubictest.model.formElement.RadioButton; import org.cubictest.model.formElement.Select; import org.cubictest.model.formElement.TextArea; import org.cubictest.model.formElement.TextField; import org.cubictest.recorder.utils.TextUtil; import org.json.JSONObject; public class JSONElementConverter { private HashMap<String, PageElement> pageElements = new HashMap<String, PageElement>(); private final String baseUrl; public JSONElementConverter(String baseUrl) { this.baseUrl = baseUrl; } private String getString(JSONObject object, String property) { try { return object.getString(property); } catch(NoSuchElementException e) { return null; } } private JSONObject getJSONObject(JSONObject object, String property) { try { return object.getJSONObject(property); } catch(NoSuchElementException e) { return null; } } /** * Parses a JSON structure and returns a new page element * * Example JSON structure: * { * label: "Text Input:", * properties: { * tagName: "INPUT", * type: "text", * value: "blablabla", * class: "someclass", * id: "someid" * } * } * * @param element * @return * @throws ParseException */ public PageElement createElementFromJson(String json) throws ParseException { System.out.println(json); return this.createElementFromJson(new JSONObject(json)); } public PageElement createElementFromJson(JSONObject element) { try { JSONObject properties = getJSONObject(element, "properties"); if(pageElements.get(getString(properties, "cubicId")) != null) { return pageElements.get(getString(properties, "cubicId")); } PageElement pe = null; //creating correct page element instance: if(getString(properties, "tagName").equalsIgnoreCase("INPUT")) { String type = properties.getString("type"); if(type.equalsIgnoreCase("text")) { pe = new TextField(); } else if(type.equalsIgnoreCase("password")) { pe = new Password(); } else if(type.equalsIgnoreCase("submit")) { pe = new Button(); } else if(type.equalsIgnoreCase("button")) { pe = new Button(); } else if(type.equalsIgnoreCase("radio")) { pe = new RadioButton(); } else if(type.equalsIgnoreCase("image")) { pe = new Button(); } else if(type.equalsIgnoreCase("checkbox")) { pe = new Checkbox(); } } else if(getString(properties, "tagName").equalsIgnoreCase("TEXTAREA")) { pe = new TextArea(); } else if(getString(properties, "tagName").equalsIgnoreCase("SELECT")) { pe = new Select(); } else if(getString(properties, "tagName").equalsIgnoreCase("OPTION")) { pe = new Option(); } else if(getString(properties, "tagName").equalsIgnoreCase("BUTTON")) { pe = new Button(); } else if(getString(properties, "tagName").equalsIgnoreCase("IMG")) { pe = new Image(); } else if(getString(properties, "tagName").equalsIgnoreCase("A")) { pe = new Link(); } else if(getString(properties, "tagName").equalsIgnoreCase("TITLE")) { pe = new Title(); } else if(getString(properties, "tagName").equalsIgnoreCase("DIV") || getString(properties, "tagName").equalsIgnoreCase("TABLE")) { pe = new SimpleContext(); } if(pe == null) { return null; } //looping over the created page element's ID types and setting all applicable values: for(IdentifierType idType : pe.getIdentifierTypes()){ //override default "must" typically used for direct edit: pe.getIdentifier(idType).setProbability(0); String key = null; String src = ""; // Identifiers are in prioritized order! Only record one of them (more robust) switch (idType){ case LABEL: if(pe instanceof Button) { key = "value"; - continue; + break; } else if (pe instanceof Link || pe instanceof Title || pe instanceof Option) { key = "innerHTML"; - continue; + break; } else { //TODO: Get html <label> tag key = null; } case ID: key = "id"; - continue; + break; case SRC: key = "src"; src = makeRelativeUrl(getString(properties, "src")); - continue; + break; case NAME: key = "name"; - continue; + break; case HREF: //TODO: Handle relative/absolute URLs. Selenium always gets absolute, even if page uses relative URL. //key = "href"; - //continue; + //break; case TITLE: key = "title"; - continue; + break; case VALUE: //TODO: Get value present when page loaded. // if(pe instanceof AbstractTextInput) // key = "value"; -// continue; +// break; case INDEX: key = "index"; - continue; + break; case CHECKED: //TODO: Handle checked //key = "checked"; - continue; + break; case MULTISELECT: //TODO: Handle Multiselect // key = "multiple"; - continue; + break; } //end switch (idType) if (key == null) { Identifier identifier = pe.getIdentifier(idType); identifier.setValue(""); identifier.setProbability(0); } else { String value = getString(properties, key); if (StringUtils.isNotBlank(value)) { Identifier identifier = pe.getIdentifier(idType); value = TextUtil.normalize(value); value = StringEscapeUtils.unescapeHtml(value); identifier.setValue(value); identifier.setProbability(100); } } } //end for (idTypes) pageElements.put(getString(properties, "cubicId"), pe); pe.setDirectEditIdentifier(pe.getMainIdentifier()); return pe; } catch(NoSuchElementException e) { return null; } } public PageElement getPageElement(String cubicId) { return pageElements.get(cubicId); } private String makeRelativeUrl(String url) { return url.replaceAll("^" + Pattern.quote(baseUrl), ""); } }
false
true
public PageElement createElementFromJson(JSONObject element) { try { JSONObject properties = getJSONObject(element, "properties"); if(pageElements.get(getString(properties, "cubicId")) != null) { return pageElements.get(getString(properties, "cubicId")); } PageElement pe = null; //creating correct page element instance: if(getString(properties, "tagName").equalsIgnoreCase("INPUT")) { String type = properties.getString("type"); if(type.equalsIgnoreCase("text")) { pe = new TextField(); } else if(type.equalsIgnoreCase("password")) { pe = new Password(); } else if(type.equalsIgnoreCase("submit")) { pe = new Button(); } else if(type.equalsIgnoreCase("button")) { pe = new Button(); } else if(type.equalsIgnoreCase("radio")) { pe = new RadioButton(); } else if(type.equalsIgnoreCase("image")) { pe = new Button(); } else if(type.equalsIgnoreCase("checkbox")) { pe = new Checkbox(); } } else if(getString(properties, "tagName").equalsIgnoreCase("TEXTAREA")) { pe = new TextArea(); } else if(getString(properties, "tagName").equalsIgnoreCase("SELECT")) { pe = new Select(); } else if(getString(properties, "tagName").equalsIgnoreCase("OPTION")) { pe = new Option(); } else if(getString(properties, "tagName").equalsIgnoreCase("BUTTON")) { pe = new Button(); } else if(getString(properties, "tagName").equalsIgnoreCase("IMG")) { pe = new Image(); } else if(getString(properties, "tagName").equalsIgnoreCase("A")) { pe = new Link(); } else if(getString(properties, "tagName").equalsIgnoreCase("TITLE")) { pe = new Title(); } else if(getString(properties, "tagName").equalsIgnoreCase("DIV") || getString(properties, "tagName").equalsIgnoreCase("TABLE")) { pe = new SimpleContext(); } if(pe == null) { return null; } //looping over the created page element's ID types and setting all applicable values: for(IdentifierType idType : pe.getIdentifierTypes()){ //override default "must" typically used for direct edit: pe.getIdentifier(idType).setProbability(0); String key = null; String src = ""; // Identifiers are in prioritized order! Only record one of them (more robust) switch (idType){ case LABEL: if(pe instanceof Button) { key = "value"; continue; } else if (pe instanceof Link || pe instanceof Title || pe instanceof Option) { key = "innerHTML"; continue; } else { //TODO: Get html <label> tag key = null; } case ID: key = "id"; continue; case SRC: key = "src"; src = makeRelativeUrl(getString(properties, "src")); continue; case NAME: key = "name"; continue; case HREF: //TODO: Handle relative/absolute URLs. Selenium always gets absolute, even if page uses relative URL. //key = "href"; //continue; case TITLE: key = "title"; continue; case VALUE: //TODO: Get value present when page loaded. // if(pe instanceof AbstractTextInput) // key = "value"; // continue; case INDEX: key = "index"; continue; case CHECKED: //TODO: Handle checked //key = "checked"; continue; case MULTISELECT: //TODO: Handle Multiselect // key = "multiple"; continue; } //end switch (idType) if (key == null) { Identifier identifier = pe.getIdentifier(idType); identifier.setValue(""); identifier.setProbability(0); } else { String value = getString(properties, key); if (StringUtils.isNotBlank(value)) { Identifier identifier = pe.getIdentifier(idType); value = TextUtil.normalize(value); value = StringEscapeUtils.unescapeHtml(value); identifier.setValue(value); identifier.setProbability(100); } } } //end for (idTypes) pageElements.put(getString(properties, "cubicId"), pe); pe.setDirectEditIdentifier(pe.getMainIdentifier()); return pe; } catch(NoSuchElementException e) { return null; } }
public PageElement createElementFromJson(JSONObject element) { try { JSONObject properties = getJSONObject(element, "properties"); if(pageElements.get(getString(properties, "cubicId")) != null) { return pageElements.get(getString(properties, "cubicId")); } PageElement pe = null; //creating correct page element instance: if(getString(properties, "tagName").equalsIgnoreCase("INPUT")) { String type = properties.getString("type"); if(type.equalsIgnoreCase("text")) { pe = new TextField(); } else if(type.equalsIgnoreCase("password")) { pe = new Password(); } else if(type.equalsIgnoreCase("submit")) { pe = new Button(); } else if(type.equalsIgnoreCase("button")) { pe = new Button(); } else if(type.equalsIgnoreCase("radio")) { pe = new RadioButton(); } else if(type.equalsIgnoreCase("image")) { pe = new Button(); } else if(type.equalsIgnoreCase("checkbox")) { pe = new Checkbox(); } } else if(getString(properties, "tagName").equalsIgnoreCase("TEXTAREA")) { pe = new TextArea(); } else if(getString(properties, "tagName").equalsIgnoreCase("SELECT")) { pe = new Select(); } else if(getString(properties, "tagName").equalsIgnoreCase("OPTION")) { pe = new Option(); } else if(getString(properties, "tagName").equalsIgnoreCase("BUTTON")) { pe = new Button(); } else if(getString(properties, "tagName").equalsIgnoreCase("IMG")) { pe = new Image(); } else if(getString(properties, "tagName").equalsIgnoreCase("A")) { pe = new Link(); } else if(getString(properties, "tagName").equalsIgnoreCase("TITLE")) { pe = new Title(); } else if(getString(properties, "tagName").equalsIgnoreCase("DIV") || getString(properties, "tagName").equalsIgnoreCase("TABLE")) { pe = new SimpleContext(); } if(pe == null) { return null; } //looping over the created page element's ID types and setting all applicable values: for(IdentifierType idType : pe.getIdentifierTypes()){ //override default "must" typically used for direct edit: pe.getIdentifier(idType).setProbability(0); String key = null; String src = ""; // Identifiers are in prioritized order! Only record one of them (more robust) switch (idType){ case LABEL: if(pe instanceof Button) { key = "value"; break; } else if (pe instanceof Link || pe instanceof Title || pe instanceof Option) { key = "innerHTML"; break; } else { //TODO: Get html <label> tag key = null; } case ID: key = "id"; break; case SRC: key = "src"; src = makeRelativeUrl(getString(properties, "src")); break; case NAME: key = "name"; break; case HREF: //TODO: Handle relative/absolute URLs. Selenium always gets absolute, even if page uses relative URL. //key = "href"; //break; case TITLE: key = "title"; break; case VALUE: //TODO: Get value present when page loaded. // if(pe instanceof AbstractTextInput) // key = "value"; // break; case INDEX: key = "index"; break; case CHECKED: //TODO: Handle checked //key = "checked"; break; case MULTISELECT: //TODO: Handle Multiselect // key = "multiple"; break; } //end switch (idType) if (key == null) { Identifier identifier = pe.getIdentifier(idType); identifier.setValue(""); identifier.setProbability(0); } else { String value = getString(properties, key); if (StringUtils.isNotBlank(value)) { Identifier identifier = pe.getIdentifier(idType); value = TextUtil.normalize(value); value = StringEscapeUtils.unescapeHtml(value); identifier.setValue(value); identifier.setProbability(100); } } } //end for (idTypes) pageElements.put(getString(properties, "cubicId"), pe); pe.setDirectEditIdentifier(pe.getMainIdentifier()); return pe; } catch(NoSuchElementException e) { return null; } }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.runtime.persistence/src/org/eclipse/tcf/te/runtime/persistence/internal/PersistenceDelegateBindingExtensionPointManager.java b/target_explorer/plugins/org.eclipse.tcf.te.runtime.persistence/src/org/eclipse/tcf/te/runtime/persistence/internal/PersistenceDelegateBindingExtensionPointManager.java index beb37117b..8fb7be029 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.runtime.persistence/src/org/eclipse/tcf/te/runtime/persistence/internal/PersistenceDelegateBindingExtensionPointManager.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.runtime.persistence/src/org/eclipse/tcf/te/runtime/persistence/internal/PersistenceDelegateBindingExtensionPointManager.java @@ -1,233 +1,235 @@ /******************************************************************************* * Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.runtime.persistence.internal; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.expressions.EvaluationResult; import org.eclipse.core.expressions.Expression; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.tcf.te.runtime.extensions.AbstractExtensionPointManager; import org.eclipse.tcf.te.runtime.extensions.ExecutableExtensionProxy; import org.eclipse.tcf.te.runtime.persistence.activator.CoreBundleActivator; /** */ public class PersistenceDelegateBindingExtensionPointManager extends AbstractExtensionPointManager<PersistenceDelegateBinding> { /* * Thread save singleton instance creation. */ private static class LazyInstance { public static PersistenceDelegateBindingExtensionPointManager instance = new PersistenceDelegateBindingExtensionPointManager(); } /** * Constructor. */ PersistenceDelegateBindingExtensionPointManager() { super(); } /** * Returns the singleton instance of the extension point manager. */ public static PersistenceDelegateBindingExtensionPointManager getInstance() { return LazyInstance.instance; } /* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.extensions.AbstractExtensionPointManager#getExtensionPointId() */ @Override protected String getExtensionPointId() { return "org.eclipse.tcf.te.runtime.persistence.bindings"; //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.extensions.AbstractExtensionPointManager#getConfigurationElementName() */ @Override protected String getConfigurationElementName() { return "binding"; //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.extensions.AbstractExtensionPointManager#doCreateExtensionProxy(org.eclipse.core.runtime.IConfigurationElement) */ @Override protected ExecutableExtensionProxy<PersistenceDelegateBinding> doCreateExtensionProxy(IConfigurationElement element) throws CoreException { return new ExecutableExtensionProxy<PersistenceDelegateBinding>(element) { /* (non-Javadoc) * @see org.eclipse.tcf.te.runtime.extensions.ExecutableExtensionProxy#newInstance() */ @Override public PersistenceDelegateBinding newInstance() { PersistenceDelegateBinding instance = new PersistenceDelegateBinding(); try { instance.setInitializationData(getConfigurationElement(), null, null); } catch (CoreException e) { IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e); Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status); } return instance; } }; } /** * Returns the applicable persistence delegate bindings for the given delegate context. * * @param context The delegate context or <code>null</code>. * @return The list of applicable editor page bindings or an empty array. */ public PersistenceDelegateBinding[] getApplicableBindings(Object context, Object container) { List<PersistenceDelegateBinding> applicable = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding binding : getBindings()) { Expression enablement = binding.getEnablement(); // The binding is applicable by default if no expression is specified. boolean isApplicable = enablement == null; if (enablement != null) if (context != null) { // Set the default variable to the delegate context. EvaluationContext evalContext = new EvaluationContext(null, context); evalContext.addVariable("context", context); //$NON-NLS-1$ if (context instanceof Class) evalContext.addVariable("contextClass", ((Class<?>)context).getName()); //$NON-NLS-1$ else evalContext.addVariable("contextClass", context.getClass().getName()); //$NON-NLS-1$ - evalContext.addVariable("container", container); //$NON-NLS-1$ - if (container instanceof Class) evalContext.addVariable("containerClass", ((Class<?>)container).getName()); //$NON-NLS-1$ - else evalContext.addVariable("containerClass", container.getClass().getName()); //$NON-NLS-1$ + if (container != null) { + evalContext.addVariable("container", container); //$NON-NLS-1$ + if (container instanceof Class) evalContext.addVariable("containerClass", ((Class<?>)container).getName()); //$NON-NLS-1$ + else evalContext.addVariable("containerClass", container.getClass().getName()); //$NON-NLS-1$ + } // Allow plugin activation evalContext.setAllowPluginActivation(true); // Evaluate the expression try { isApplicable = enablement.evaluate(evalContext).equals(EvaluationResult.TRUE); } catch (CoreException e) { IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e); Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status); } } else // The enablement is false by definition if no delegate context is given. isApplicable = false; // Add the binding if applicable if (isApplicable) applicable.add(binding); } // Sort the applicable bindings by priority Collections.sort(applicable, new SortByPriority()); if (applicable.size() > 1) { List<PersistenceDelegateBinding> overwritten = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding candidate : applicable) for (PersistenceDelegateBinding overwriter : applicable) { String[] overwrites = overwriter.getOverwrites(); if (overwrites != null && Arrays.asList(overwrites).contains(candidate.getId())) overwritten.add(candidate); } for (PersistenceDelegateBinding toRemove : overwritten) applicable.remove(toRemove); } return applicable.toArray(new PersistenceDelegateBinding[applicable.size()]); } /** * Persistence delegate binding sort by priority comparator implementation. */ /* default */ static class SortByPriority implements Comparator<PersistenceDelegateBinding> { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(PersistenceDelegateBinding o1, PersistenceDelegateBinding o2) { if (o1 != null && o2 != null) { String p1 = o1.getPriority(); if (p1 == null || "".equals(p1)) p1 = "normal"; //$NON-NLS-1$ //$NON-NLS-2$ String p2 = o2.getPriority(); if (p2 == null || "".equals(p1)) p2 = "normal"; //$NON-NLS-1$ //$NON-NLS-2$ int i1 = 0; if ("lowest".equalsIgnoreCase(p1)) i1 = -3; //$NON-NLS-1$ if ("lower".equalsIgnoreCase(p1)) i1 = -2; //$NON-NLS-1$ if ("low".equalsIgnoreCase(p1)) i1 = -1; //$NON-NLS-1$ if ("high".equalsIgnoreCase(p1)) i1 = 1; //$NON-NLS-1$ if ("higher".equalsIgnoreCase(p1)) i1 = 2; //$NON-NLS-1$ if ("highest".equalsIgnoreCase(p1)) i1 = 3; //$NON-NLS-1$ int i2 = 0; if ("lowest".equalsIgnoreCase(p2)) i2 = -3; //$NON-NLS-1$ if ("lower".equalsIgnoreCase(p2)) i2 = -2; //$NON-NLS-1$ if ("low".equalsIgnoreCase(p2)) i2 = -1; //$NON-NLS-1$ if ("high".equalsIgnoreCase(p2)) i2 = 1; //$NON-NLS-1$ if ("higher".equalsIgnoreCase(p2)) i2 = 2; //$NON-NLS-1$ if ("highest".equalsIgnoreCase(p2)) i2 = 3; //$NON-NLS-1$ if (i1 < i2) return 1; if (i1 > i2) return -1; } return 0; } } /** * Returns the list of all contributed persistence delegate bindings. * * @return The list of contributed persistence delegate bindings, or an empty array. */ public PersistenceDelegateBinding[] getBindings() { List<PersistenceDelegateBinding> contributions = new ArrayList<PersistenceDelegateBinding>(); Collection<ExecutableExtensionProxy<PersistenceDelegateBinding>> persistenceDelegateBindings = getExtensions().values(); for (ExecutableExtensionProxy<PersistenceDelegateBinding> persistenceDelegateBinding : persistenceDelegateBindings) { PersistenceDelegateBinding instance = persistenceDelegateBinding.getInstance(); if (instance != null && !contributions.contains(instance)) contributions.add(instance); } return contributions.toArray(new PersistenceDelegateBinding[contributions.size()]); } /** * Returns the persistence delegate binding identified by its unique id. If no persistence * delegate binding with the specified id is registered, <code>null</code> is returned. * * @param id The unique id of the persistence delegate binding or <code>null</code> * * @return The persistence delegate binding instance or <code>null</code>. */ public PersistenceDelegateBinding getBinding(String id) { PersistenceDelegateBinding contribution = null; if (getExtensions().containsKey(id)) { ExecutableExtensionProxy<PersistenceDelegateBinding> proxy = getExtensions().get(id); // Get the extension instance contribution = proxy.getInstance(); } return contribution; } }
true
true
public PersistenceDelegateBinding[] getApplicableBindings(Object context, Object container) { List<PersistenceDelegateBinding> applicable = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding binding : getBindings()) { Expression enablement = binding.getEnablement(); // The binding is applicable by default if no expression is specified. boolean isApplicable = enablement == null; if (enablement != null) if (context != null) { // Set the default variable to the delegate context. EvaluationContext evalContext = new EvaluationContext(null, context); evalContext.addVariable("context", context); //$NON-NLS-1$ if (context instanceof Class) evalContext.addVariable("contextClass", ((Class<?>)context).getName()); //$NON-NLS-1$ else evalContext.addVariable("contextClass", context.getClass().getName()); //$NON-NLS-1$ evalContext.addVariable("container", container); //$NON-NLS-1$ if (container instanceof Class) evalContext.addVariable("containerClass", ((Class<?>)container).getName()); //$NON-NLS-1$ else evalContext.addVariable("containerClass", container.getClass().getName()); //$NON-NLS-1$ // Allow plugin activation evalContext.setAllowPluginActivation(true); // Evaluate the expression try { isApplicable = enablement.evaluate(evalContext).equals(EvaluationResult.TRUE); } catch (CoreException e) { IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e); Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status); } } else // The enablement is false by definition if no delegate context is given. isApplicable = false; // Add the binding if applicable if (isApplicable) applicable.add(binding); } // Sort the applicable bindings by priority Collections.sort(applicable, new SortByPriority()); if (applicable.size() > 1) { List<PersistenceDelegateBinding> overwritten = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding candidate : applicable) for (PersistenceDelegateBinding overwriter : applicable) { String[] overwrites = overwriter.getOverwrites(); if (overwrites != null && Arrays.asList(overwrites).contains(candidate.getId())) overwritten.add(candidate); } for (PersistenceDelegateBinding toRemove : overwritten) applicable.remove(toRemove); } return applicable.toArray(new PersistenceDelegateBinding[applicable.size()]); }
public PersistenceDelegateBinding[] getApplicableBindings(Object context, Object container) { List<PersistenceDelegateBinding> applicable = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding binding : getBindings()) { Expression enablement = binding.getEnablement(); // The binding is applicable by default if no expression is specified. boolean isApplicable = enablement == null; if (enablement != null) if (context != null) { // Set the default variable to the delegate context. EvaluationContext evalContext = new EvaluationContext(null, context); evalContext.addVariable("context", context); //$NON-NLS-1$ if (context instanceof Class) evalContext.addVariable("contextClass", ((Class<?>)context).getName()); //$NON-NLS-1$ else evalContext.addVariable("contextClass", context.getClass().getName()); //$NON-NLS-1$ if (container != null) { evalContext.addVariable("container", container); //$NON-NLS-1$ if (container instanceof Class) evalContext.addVariable("containerClass", ((Class<?>)container).getName()); //$NON-NLS-1$ else evalContext.addVariable("containerClass", container.getClass().getName()); //$NON-NLS-1$ } // Allow plugin activation evalContext.setAllowPluginActivation(true); // Evaluate the expression try { isApplicable = enablement.evaluate(evalContext).equals(EvaluationResult.TRUE); } catch (CoreException e) { IStatus status = new Status(IStatus.ERROR, CoreBundleActivator.getUniqueIdentifier(), e.getLocalizedMessage(), e); Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status); } } else // The enablement is false by definition if no delegate context is given. isApplicable = false; // Add the binding if applicable if (isApplicable) applicable.add(binding); } // Sort the applicable bindings by priority Collections.sort(applicable, new SortByPriority()); if (applicable.size() > 1) { List<PersistenceDelegateBinding> overwritten = new ArrayList<PersistenceDelegateBinding>(); for (PersistenceDelegateBinding candidate : applicable) for (PersistenceDelegateBinding overwriter : applicable) { String[] overwrites = overwriter.getOverwrites(); if (overwrites != null && Arrays.asList(overwrites).contains(candidate.getId())) overwritten.add(candidate); } for (PersistenceDelegateBinding toRemove : overwritten) applicable.remove(toRemove); } return applicable.toArray(new PersistenceDelegateBinding[applicable.size()]); }
diff --git a/src/com/mpower/controller/validator/PaymentSourceValidator.java b/src/com/mpower/controller/validator/PaymentSourceValidator.java index b404c324..892c2726 100644 --- a/src/com/mpower/controller/validator/PaymentSourceValidator.java +++ b/src/com/mpower/controller/validator/PaymentSourceValidator.java @@ -1,70 +1,70 @@ package com.mpower.controller.validator; import java.util.Calendar; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.mpower.domain.PaymentSource; import com.mpower.service.SiteService; import com.mpower.type.PageType; import com.mpower.util.CalendarUtils; public class PaymentSourceValidator implements Validator { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog(getClass()); @SuppressWarnings("unused") private SiteService siteService; public void setSiteService(SiteService siteService) { this.siteService = siteService; } @SuppressWarnings("unused") private PageType pageType; public void setPageType(PageType pageType) { this.pageType = pageType; } @SuppressWarnings("unchecked") @Override public boolean supports(Class clazz) { return PaymentSource.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { logger.debug("in PaymentSourceValidator"); validatePaymentSource(target, errors); } public static void validatePaymentSource(Object target, Errors errors) { String inPath = errors.getNestedPath(); - if (target instanceof PaymentSource) { + if (!(target instanceof PaymentSource)) { errors.setNestedPath("paymentSource"); } PaymentSource source = (PaymentSource) target; if ("ACH".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achAccountNumber", "invalidAchAccountNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achRoutingNumber", "invalidAchRoutingNumber"); } else if ("Credit Card".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardNumber", "invalidCreditCardNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardExpiration", "invalidCreditCardExpiration"); if (!errors.hasErrors()) { Date expirationDate = source.getCreditCardExpiration(); Calendar today = CalendarUtils.getToday(false); if (expirationDate == null || today.getTime().after(expirationDate)) { errors.rejectValue("creditCardExpiration", "invalidCreditCardExpiration"); } } } errors.setNestedPath(inPath); } }
true
true
public static void validatePaymentSource(Object target, Errors errors) { String inPath = errors.getNestedPath(); if (target instanceof PaymentSource) { errors.setNestedPath("paymentSource"); } PaymentSource source = (PaymentSource) target; if ("ACH".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achAccountNumber", "invalidAchAccountNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achRoutingNumber", "invalidAchRoutingNumber"); } else if ("Credit Card".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardNumber", "invalidCreditCardNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardExpiration", "invalidCreditCardExpiration"); if (!errors.hasErrors()) { Date expirationDate = source.getCreditCardExpiration(); Calendar today = CalendarUtils.getToday(false); if (expirationDate == null || today.getTime().after(expirationDate)) { errors.rejectValue("creditCardExpiration", "invalidCreditCardExpiration"); } } } errors.setNestedPath(inPath); }
public static void validatePaymentSource(Object target, Errors errors) { String inPath = errors.getNestedPath(); if (!(target instanceof PaymentSource)) { errors.setNestedPath("paymentSource"); } PaymentSource source = (PaymentSource) target; if ("ACH".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achAccountNumber", "invalidAchAccountNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "achRoutingNumber", "invalidAchRoutingNumber"); } else if ("Credit Card".equals(source.getType())) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardNumber", "invalidCreditCardNumber"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creditCardExpiration", "invalidCreditCardExpiration"); if (!errors.hasErrors()) { Date expirationDate = source.getCreditCardExpiration(); Calendar today = CalendarUtils.getToday(false); if (expirationDate == null || today.getTime().after(expirationDate)) { errors.rejectValue("creditCardExpiration", "invalidCreditCardExpiration"); } } } errors.setNestedPath(inPath); }
diff --git a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java index 143eb44..546625a 100644 --- a/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java +++ b/org.eclipse.swtbot.swt.finder.test/src/org/eclipse/swtbot/swt/finder/keyboard/KeyboardTest.java @@ -1,263 +1,263 @@ /******************************************************************************* * Copyright (c) 2009 Ketan Padegaonkar and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Ketan Padegaonkar - initial API and implementation *******************************************************************************/ package org.eclipse.swtbot.swt.finder.keyboard; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.jface.bindings.keys.KeyStroke; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.finders.AbstractSWTTestCase; import org.eclipse.swtbot.swt.finder.widgets.SWTBotStyledText; import org.eclipse.swtbot.swt.finder.widgets.SWTBotText; import org.junit.Test; /** * @author Ketan Padegaonkar &lt;KetanPadegaonkar [at] gmail [dot] com&gt; * @version $Id$ */ public class KeyboardTest extends AbstractSWTTestCase { private SWTBotStyledText styledText; private SWTBotText listeners; private Keyboard keyboard; @Test public void canTypeShiftKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=332938450 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=332938540 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canTypeCTRLKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334095974 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334096084 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canTypeAltKey() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337927063 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337927163 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_CTRL_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334163451 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334163611 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334163782 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334163832 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_SHIFT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334173686 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334173996 data=null character='\\0' keyCode=262144 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334174277 data=null character='\\0' keyCode=262144 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334174347 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_CTRL_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334364901 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334365191 data=null character='\\0' keyCode=65536 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334365331 data=null character='\\0' keyCode=65536 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334365492 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_ALT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334374164 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334374324 data=null character='\\0' keyCode=262144 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334374475 data=null character='\\0' keyCode=262144 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334374495 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_SHIFT_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334403126 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334403236 data=null character='\\0' keyCode=65536 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334403366 data=null character='\\0' keyCode=65536 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334403426 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_ALT_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334417126 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=334417456 data=null character='\\0' keyCode=131072 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334417526 data=null character='\\0' keyCode=131072 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=334417577 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_SHIFT_CTRL_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.CTRL, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998217 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998548 data=null character='\\0' keyCode=262144 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=336998858 data=null character='\\0' keyCode=65536 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=336998938 data=null character='\\0' keyCode=65536 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337000000 data=null character='\\0' keyCode=262144 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337000330 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_SHIFT_ALT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.SHIFT, Keystrokes.ALT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337024085 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337024595 data=null character='\\0' keyCode=65536 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337025316 data=null character='\\0' keyCode=262144 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337026738 data=null character='\\0' keyCode=262144 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337027700 data=null character='\\0' keyCode=65536 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337028090 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canType_CTRL_SHIFT_ALT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.SHIFT, Keystrokes.ALT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337073666 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337074086 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337074527 data=null character='\\0' keyCode=65536 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337074928 data=null character='\\0' keyCode=65536 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337075999 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337076370 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_CTRL_ALT_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.ALT, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337084111 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337084592 data=null character='\\0' keyCode=65536 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337085162 data=null character='\\0' keyCode=131072 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337085753 data=null character='\\0' keyCode=131072 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337086184 data=null character='\\0' keyCode=65536 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337086584 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canType_ALT_CTRL_SHIFT_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.CTRL, Keystrokes.SHIFT); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337516292 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337516753 data=null character='\\0' keyCode=262144 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337517113 data=null character='\\0' keyCode=131072 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337517985 data=null character='\\0' keyCode=131072 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337518335 data=null character='\\0' keyCode=262144 stateMask=327680 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337518686 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canType_ALT_SHIFT_CTRL_Keys() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.ALT, Keystrokes.SHIFT, Keystrokes.CTRL); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337527028 data=null character='\\0' keyCode=65536 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337527649 data=null character='\\0' keyCode=131072 stateMask=65536 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=337528209 data=null character='\\0' keyCode=262144 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337531534 data=null character='\\0' keyCode=262144 stateMask=458752 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337532275 data=null character='\\0' keyCode=131072 stateMask=196608 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=337532666 data=null character='\\0' keyCode=65536 stateMask=65536 doit=true}"); } @Test public void canTypeCTRL_SHIFT_T() throws Exception { styledText.setFocus(); keyboard.pressShortcut(keys(Keystrokes.CTRL, Keystrokes.SHIFT, Keystrokes.create('t'))); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356391804 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356392194 data=null character='\\0' keyCode=131072 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=356393156 data=null character='' keyCode=116 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356392495 data=null character='' keyCode=116 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356393987 data=null character='\\0' keyCode=131072 stateMask=393216 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=356394307 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } @Test public void canTypeSmallCharacters() throws Exception { styledText.setFocus(); keyboard.typeText("ab"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=358259489 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=0 end=0 text=a}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=358259489 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=358259489 data=null character='a' keyCode=97 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=358259560 data=null character='a' keyCode=97 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=358264617 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=1 end=1 text=b}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=358264617 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=358264617 data=null character='b' keyCode=98 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=358259810 data=null character='b' keyCode=98 stateMask=0 doit=true}"); } @Test public void canTypeCapitalCharacters() throws Exception { styledText.setFocus(); keyboard.typeText("A"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=359800165 data=null character='\\0' keyCode=131072 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Verify [25]: VerifyEvent{StyledText {} time=359800285 data=null character='\\0' keyCode=0 stateMask=0 doit=true start=0 end=0 text=A}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=359800285 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=359800285 data=null character='A' keyCode=97 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=359800405 data=null character='A' keyCode=97 stateMask=131072 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=359800485 data=null character='\\0' keyCode=131072 stateMask=131072 doit=true}"); } @Test public void canTypeCTRL_SPACE() throws Exception { styledText.setFocus(); keyboard.pressShortcut(Keystrokes.CTRL, Keystrokes.create(' ')[0]); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=41517702 data=null character='\\0' keyCode=262144 stateMask=0 doit=true}"); assertEventMatches(listeners.getText(), "Modify [24]: ModifyEvent{StyledText {} time=41517983 data=null}"); assertEventMatches(listeners.getText(), "KeyDown [1]: KeyEvent{StyledText {} time=41517983 data=null character=' ' keyCode=32 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=41518070 data=null character=' ' keyCode=32 stateMask=262144 doit=true}"); assertEventMatches(listeners.getText(), "KeyUp [2]: KeyEvent{StyledText {} time=41518278 data=null character='\\0' keyCode=262144 stateMask=262144 doit=true}"); } private List<KeyStroke> keys(KeyStroke ctrl, KeyStroke shift, KeyStroke[] keyStrokes) { List<KeyStroke> keys = new ArrayList<KeyStroke>(); keys.add(ctrl); keys.add(shift); keys.addAll(Arrays.asList(keyStrokes)); return keys; } public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); - keyboard = new Keyboard(display); + keyboard = new Keyboard(); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); } }
true
true
public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); keyboard = new Keyboard(display); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); }
public void setUp() throws Exception { super.setUp(); bot = new SWTBot(); keyboard = new Keyboard(); bot.shell("SWT Custom Controls").activate(); bot.tabItem("StyledText").activate(); bot.checkBox("Horizontal Fill").select(); bot.checkBox("Vertical Fill").select(); bot.checkBox("Listen").deselect(); bot.checkBox("Listen").select(); styledText = bot.styledTextInGroup("StyledText"); styledText.setText(""); bot.button("Clear").click(); listeners = bot.textInGroup("Listeners"); }
diff --git a/src/java/org/apache/poi/hssf/dev/BiffViewer.java b/src/java/org/apache/poi/hssf/dev/BiffViewer.java index 12267d23d..ff2997884 100644 --- a/src/java/org/apache/poi/hssf/dev/BiffViewer.java +++ b/src/java/org/apache/poi/hssf/dev/BiffViewer.java @@ -1,713 +1,713 @@ /* ==================================================================== * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" and * "Apache POI" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * "Apache POI", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * BiffViewer.java * * Created on November 13, 2001, 9:23 AM */ package org.apache.poi.hssf.dev; import org.apache.poi.hssf.record.*; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.util.HexDump; import org.apache.poi.util.LittleEndian; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; /** * Utillity for reading in BIFF8 records and displaying data from them. * @author Andrew C. Oliver (acoliver at apache dot org) * @author Glen Stampoultzis (glens at apache.org) * @see #main */ public class BiffViewer { String filename; private boolean dump; /** * Creates new BiffViewer * * @param args */ public BiffViewer(String[] args) { if (args.length > 0) { filename = args[0]; } else { System.out.println("BIFFVIEWER REQUIRES A FILENAME***"); } } /** * Method run * * starts up BiffViewer... */ public void run() { try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename)); InputStream stream = fs.createDocumentInputStream("Workbook"); Record[] records = createRecords(stream, dump); } catch (Exception e) { e.printStackTrace(); } } /** * Create an array of records from an input stream * * @param in the InputStream from which the records will be * obtained * @param dump * * @return an array of Records created from the InputStream * * @exception RecordFormatException on error processing the * InputStream */ public static Record[] createRecords(InputStream in, boolean dump) throws RecordFormatException { ArrayList records = new ArrayList(); Record last_record = null; int loc = 0; try { // long offset = 0; short rectype = 0; do { rectype = LittleEndian.readShort(in); System.out.println("============================================"); System.out.println("Offset 0x" + Integer.toHexString(loc) + " (" + loc + ")"); loc += 2; if (rectype != 0) { short recsize = LittleEndian.readShort(in); loc += 2; byte[] data = new byte[(int) recsize]; in.read(data); if ((rectype == WSBoolRecord.sid) && (recsize == 0)) { System.out.println(loc); } loc += recsize; // offset += 4 + recsize; if (dump) { dump(rectype, recsize, data); } Record[] recs = createRecord(rectype, recsize, data); // handle MulRK records Record record = recs[0]; if ((record instanceof UnknownRecord) && !dump) // if we didn't already dump { // just cause dump was on and we're hit an unknow dumpUnknownRecord(data); } if (record != null) { if (rectype == ContinueRecord.sid) { dumpContinueRecord(last_record, dump, data); } else { last_record = record; records.add(record); } } } } while (rectype != 0); } catch (IOException e) { throw new RecordFormatException("Error reading bytes"); } Record[] retval = new Record[records.size()]; retval = (Record[]) records.toArray(retval); return retval; } private static void dumpContinueRecord(Record last_record, boolean dump, byte[] data) throws IOException { if (last_record == null) { throw new RecordFormatException( "First record is a ContinueRecord??"); } if (dump) { System.out.println( "-----PRECONTINUED LAST RECORD WOULD SERIALIZE LIKE:"); byte[] lr = last_record.serialize(); if (lr != null) { HexDump.dump(last_record.serialize(), 0, System.out, 0); } System.out.println(); System.out.println( "-----PRECONTINUED----------------------------------"); } last_record.processContinueRecord(data); if (dump) { System.out.println( "-----CONTINUED LAST RECORD WOULD SERIALIZE LIKE:"); HexDump.dump(last_record.serialize(), 0, System.out, 0); System.out.println(); System.out.println( "-----CONTINUED----------------------------------"); } } private static void dumpUnknownRecord(byte[] data) throws IOException { // record hex dump it! System.out.println( "-----UNKNOWN----------------------------------"); if (data.length > 0) { HexDump.dump(data, 0, System.out, 0); } else { System.out.print("**NO RECORD DATA**"); } System.out.println(); System.out.println( "-----UNKNOWN----------------------------------"); } private static void dump(short rectype, short recsize, byte[] data) throws IOException { // System.out // .println("fixing to recordize the following"); System.out.print("rectype = 0x" + Integer.toHexString(rectype)); System.out.println(", recsize = 0x" + Integer.toHexString(recsize)); System.out.println( "-BEGIN DUMP---------------------------------"); if (data.length > 0) { HexDump.dump(data, 0, System.out, 0); } else { System.out.println("**NO RECORD DATA**"); } // System.out.println(); System.out.println( "-END DUMP-----------------------------------"); } /** * Essentially a duplicate of RecordFactory. Kept seperate as not to * screw up non-debug operations. * */ private static Record[] createRecord(short rectype, short size, byte[] data) { Record retval = null; Record[] realretval = null; // int irectype = rectype; switch (rectype) { case ChartRecord.sid: retval = new ChartRecord(rectype, size, data); break; case ChartFormatRecord.sid: retval = new ChartFormatRecord(rectype, size, data); break; case SeriesRecord.sid: retval = new SeriesRecord(rectype, size, data); break; case BeginRecord.sid: retval = new BeginRecord(rectype, size, data); break; case EndRecord.sid: retval = new EndRecord(rectype, size, data); break; case BOFRecord.sid: retval = new BOFRecord(rectype, size, data); break; case InterfaceHdrRecord.sid: retval = new InterfaceHdrRecord(rectype, size, data); break; case MMSRecord.sid: retval = new MMSRecord(rectype, size, data); break; case InterfaceEndRecord.sid: retval = new InterfaceEndRecord(rectype, size, data); break; case WriteAccessRecord.sid: retval = new WriteAccessRecord(rectype, size, data); break; case CodepageRecord.sid: retval = new CodepageRecord(rectype, size, data); break; case DSFRecord.sid: retval = new DSFRecord(rectype, size, data); break; case TabIdRecord.sid: retval = new TabIdRecord(rectype, size, data); break; case FnGroupCountRecord.sid: retval = new FnGroupCountRecord(rectype, size, data); break; case WindowProtectRecord.sid: retval = new WindowProtectRecord(rectype, size, data); break; case ProtectRecord.sid: retval = new ProtectRecord(rectype, size, data); break; case PasswordRecord.sid: retval = new PasswordRecord(rectype, size, data); break; case ProtectionRev4Record.sid: retval = new ProtectionRev4Record(rectype, size, data); break; case PasswordRev4Record.sid: retval = new PasswordRev4Record(rectype, size, data); break; case WindowOneRecord.sid: retval = new WindowOneRecord(rectype, size, data); break; case BackupRecord.sid: retval = new BackupRecord(rectype, size, data); break; case HideObjRecord.sid: retval = new HideObjRecord(rectype, size, data); break; case DateWindow1904Record.sid: retval = new DateWindow1904Record(rectype, size, data); break; case PrecisionRecord.sid: retval = new PrecisionRecord(rectype, size, data); break; case RefreshAllRecord.sid: retval = new RefreshAllRecord(rectype, size, data); break; case BookBoolRecord.sid: retval = new BookBoolRecord(rectype, size, data); break; case FontRecord.sid: retval = new FontRecord(rectype, size, data); break; case FormatRecord.sid: retval = new FormatRecord(rectype, size, data); break; case ExtendedFormatRecord.sid: retval = new ExtendedFormatRecord(rectype, size, data); break; case StyleRecord.sid: retval = new StyleRecord(rectype, size, data); break; case UseSelFSRecord.sid: retval = new UseSelFSRecord(rectype, size, data); break; case BoundSheetRecord.sid: retval = new BoundSheetRecord(rectype, size, data); break; case CountryRecord.sid: retval = new CountryRecord(rectype, size, data); break; case SSTRecord.sid: retval = new SSTRecord(rectype, size, data); break; case ExtSSTRecord.sid: retval = new ExtSSTRecord(rectype, size, data); break; case EOFRecord.sid: retval = new EOFRecord(rectype, size, data); break; case IndexRecord.sid: retval = new IndexRecord(rectype, size, data); break; case CalcModeRecord.sid: retval = new CalcModeRecord(rectype, size, data); break; case CalcCountRecord.sid: retval = new CalcCountRecord(rectype, size, data); break; case RefModeRecord.sid: retval = new RefModeRecord(rectype, size, data); break; case IterationRecord.sid: retval = new IterationRecord(rectype, size, data); break; case DeltaRecord.sid: retval = new DeltaRecord(rectype, size, data); break; case SaveRecalcRecord.sid: retval = new SaveRecalcRecord(rectype, size, data); break; case PrintHeadersRecord.sid: retval = new PrintHeadersRecord(rectype, size, data); break; case PrintGridlinesRecord.sid: retval = new PrintGridlinesRecord(rectype, size, data); break; case GridsetRecord.sid: retval = new GridsetRecord(rectype, size, data); break; case GutsRecord.sid: retval = new GutsRecord(rectype, size, data); break; case DefaultRowHeightRecord.sid: retval = new DefaultRowHeightRecord(rectype, size, data); break; case WSBoolRecord.sid: retval = new WSBoolRecord(rectype, size, data); break; case HeaderRecord.sid: retval = new HeaderRecord(rectype, size, data); break; case FooterRecord.sid: retval = new FooterRecord(rectype, size, data); break; case HCenterRecord.sid: retval = new HCenterRecord(rectype, size, data); break; case VCenterRecord.sid: retval = new VCenterRecord(rectype, size, data); break; case PrintSetupRecord.sid: retval = new PrintSetupRecord(rectype, size, data); break; case DefaultColWidthRecord.sid: retval = new DefaultColWidthRecord(rectype, size, data); break; case DimensionsRecord.sid: retval = new DimensionsRecord(rectype, size, data); break; case RowRecord.sid: retval = new RowRecord(rectype, size, data); break; case LabelSSTRecord.sid: retval = new LabelSSTRecord(rectype, size, data); break; case RKRecord.sid: retval = new RKRecord(rectype, size, data); break; case NumberRecord.sid: retval = new NumberRecord(rectype, size, data); break; case DBCellRecord.sid: retval = new DBCellRecord(rectype, size, data); break; case WindowTwoRecord.sid: retval = new WindowTwoRecord(rectype, size, data); break; case SelectionRecord.sid: retval = new SelectionRecord(rectype, size, data); break; case ContinueRecord.sid: retval = new ContinueRecord(rectype, size, data); break; case LabelRecord.sid: retval = new LabelRecord(rectype, size, data); break; case MulRKRecord.sid: retval = new MulRKRecord(rectype, size, data); break; case MulBlankRecord.sid: retval = new MulBlankRecord(rectype, size, data); break; case BlankRecord.sid: retval = new BlankRecord(rectype, size, data); break; case BoolErrRecord.sid: retval = new BoolErrRecord(rectype, size, data); break; case ColumnInfoRecord.sid: retval = new ColumnInfoRecord(rectype, size, data); break; case MergeCellsRecord.sid: retval = new MergeCellsRecord(rectype, size, data); break; case AreaRecord.sid: retval = new AreaRecord(rectype, size, data); break; case DataFormatRecord.sid: retval = new DataFormatRecord(rectype, size, data); break; case BarRecord.sid: retval = new BarRecord(rectype, size, data); break; case DatRecord.sid: retval = new DatRecord(rectype, size, data); break; case PlotGrowthRecord.sid: retval = new PlotGrowthRecord(rectype, size, data); break; case UnitsRecord.sid: retval = new UnitsRecord(rectype, size, data); break; case FrameRecord.sid: retval = new FrameRecord(rectype, size, data); break; case ValueRangeRecord.sid: retval = new ValueRangeRecord(rectype, size, data); break; case SeriesListRecord.sid: retval = new SeriesListRecord(rectype, size, data); break; case FontBasisRecord.sid: retval = new FontBasisRecord(rectype, size, data); break; case FontIndexRecord.sid: retval = new FontIndexRecord(rectype, size, data); break; case LineFormatRecord.sid: retval = new LineFormatRecord(rectype, size, data); break; case AreaFormatRecord.sid: retval = new AreaFormatRecord(rectype, size, data); break; case LinkedDataRecord.sid: retval = new LinkedDataRecord(rectype, size, data); break; case FormulaRecord.sid: retval = new FormulaRecord(rectype, size, data); break; case SheetPropertiesRecord.sid: - retval = new FormulaRecord(rectype, size, data); + retval = new SheetPropertiesRecord(rectype, size, data); break; default : retval = new UnknownRecord(rectype, size, data); } if (realretval == null) { realretval = new Record[1]; realretval[0] = retval; System.out.println("recordid = 0x" + Integer.toHexString(rectype) + ", size =" + size); System.out.println(realretval[0].toString()); } return realretval; } /** * Method setDump - hex dump out data or not. * * * @param dump * */ public void setDump(boolean dump) { this.dump = dump; } /** * Method main * with 1 argument just run straight biffview against given file<P> * with 2 arguments where the second argument is "on" - run biffviewer<P> * with hex dumps of records <P> * * with 2 arguments where the second argument is "bfd" just run a big fat * hex dump of the file...don't worry about biffviewing it at all * * * @param args * */ public static void main(String[] args) { try { BiffViewer viewer = new BiffViewer(args); if ((args.length > 1) && args[1].equals("on")) { viewer.setDump(true); } if ((args.length > 1) && args[1].equals("bfd")) { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(args[0])); InputStream stream = fs.createDocumentInputStream("Workbook"); int size = stream.available(); byte[] data = new byte[size]; stream.read(data); HexDump.dump(data, 0, System.out, 0); } else { viewer.run(); } } catch (Exception e) { e.printStackTrace(); } } }
true
true
private static Record[] createRecord(short rectype, short size, byte[] data) { Record retval = null; Record[] realretval = null; // int irectype = rectype; switch (rectype) { case ChartRecord.sid: retval = new ChartRecord(rectype, size, data); break; case ChartFormatRecord.sid: retval = new ChartFormatRecord(rectype, size, data); break; case SeriesRecord.sid: retval = new SeriesRecord(rectype, size, data); break; case BeginRecord.sid: retval = new BeginRecord(rectype, size, data); break; case EndRecord.sid: retval = new EndRecord(rectype, size, data); break; case BOFRecord.sid: retval = new BOFRecord(rectype, size, data); break; case InterfaceHdrRecord.sid: retval = new InterfaceHdrRecord(rectype, size, data); break; case MMSRecord.sid: retval = new MMSRecord(rectype, size, data); break; case InterfaceEndRecord.sid: retval = new InterfaceEndRecord(rectype, size, data); break; case WriteAccessRecord.sid: retval = new WriteAccessRecord(rectype, size, data); break; case CodepageRecord.sid: retval = new CodepageRecord(rectype, size, data); break; case DSFRecord.sid: retval = new DSFRecord(rectype, size, data); break; case TabIdRecord.sid: retval = new TabIdRecord(rectype, size, data); break; case FnGroupCountRecord.sid: retval = new FnGroupCountRecord(rectype, size, data); break; case WindowProtectRecord.sid: retval = new WindowProtectRecord(rectype, size, data); break; case ProtectRecord.sid: retval = new ProtectRecord(rectype, size, data); break; case PasswordRecord.sid: retval = new PasswordRecord(rectype, size, data); break; case ProtectionRev4Record.sid: retval = new ProtectionRev4Record(rectype, size, data); break; case PasswordRev4Record.sid: retval = new PasswordRev4Record(rectype, size, data); break; case WindowOneRecord.sid: retval = new WindowOneRecord(rectype, size, data); break; case BackupRecord.sid: retval = new BackupRecord(rectype, size, data); break; case HideObjRecord.sid: retval = new HideObjRecord(rectype, size, data); break; case DateWindow1904Record.sid: retval = new DateWindow1904Record(rectype, size, data); break; case PrecisionRecord.sid: retval = new PrecisionRecord(rectype, size, data); break; case RefreshAllRecord.sid: retval = new RefreshAllRecord(rectype, size, data); break; case BookBoolRecord.sid: retval = new BookBoolRecord(rectype, size, data); break; case FontRecord.sid: retval = new FontRecord(rectype, size, data); break; case FormatRecord.sid: retval = new FormatRecord(rectype, size, data); break; case ExtendedFormatRecord.sid: retval = new ExtendedFormatRecord(rectype, size, data); break; case StyleRecord.sid: retval = new StyleRecord(rectype, size, data); break; case UseSelFSRecord.sid: retval = new UseSelFSRecord(rectype, size, data); break; case BoundSheetRecord.sid: retval = new BoundSheetRecord(rectype, size, data); break; case CountryRecord.sid: retval = new CountryRecord(rectype, size, data); break; case SSTRecord.sid: retval = new SSTRecord(rectype, size, data); break; case ExtSSTRecord.sid: retval = new ExtSSTRecord(rectype, size, data); break; case EOFRecord.sid: retval = new EOFRecord(rectype, size, data); break; case IndexRecord.sid: retval = new IndexRecord(rectype, size, data); break; case CalcModeRecord.sid: retval = new CalcModeRecord(rectype, size, data); break; case CalcCountRecord.sid: retval = new CalcCountRecord(rectype, size, data); break; case RefModeRecord.sid: retval = new RefModeRecord(rectype, size, data); break; case IterationRecord.sid: retval = new IterationRecord(rectype, size, data); break; case DeltaRecord.sid: retval = new DeltaRecord(rectype, size, data); break; case SaveRecalcRecord.sid: retval = new SaveRecalcRecord(rectype, size, data); break; case PrintHeadersRecord.sid: retval = new PrintHeadersRecord(rectype, size, data); break; case PrintGridlinesRecord.sid: retval = new PrintGridlinesRecord(rectype, size, data); break; case GridsetRecord.sid: retval = new GridsetRecord(rectype, size, data); break; case GutsRecord.sid: retval = new GutsRecord(rectype, size, data); break; case DefaultRowHeightRecord.sid: retval = new DefaultRowHeightRecord(rectype, size, data); break; case WSBoolRecord.sid: retval = new WSBoolRecord(rectype, size, data); break; case HeaderRecord.sid: retval = new HeaderRecord(rectype, size, data); break; case FooterRecord.sid: retval = new FooterRecord(rectype, size, data); break; case HCenterRecord.sid: retval = new HCenterRecord(rectype, size, data); break; case VCenterRecord.sid: retval = new VCenterRecord(rectype, size, data); break; case PrintSetupRecord.sid: retval = new PrintSetupRecord(rectype, size, data); break; case DefaultColWidthRecord.sid: retval = new DefaultColWidthRecord(rectype, size, data); break; case DimensionsRecord.sid: retval = new DimensionsRecord(rectype, size, data); break; case RowRecord.sid: retval = new RowRecord(rectype, size, data); break; case LabelSSTRecord.sid: retval = new LabelSSTRecord(rectype, size, data); break; case RKRecord.sid: retval = new RKRecord(rectype, size, data); break; case NumberRecord.sid: retval = new NumberRecord(rectype, size, data); break; case DBCellRecord.sid: retval = new DBCellRecord(rectype, size, data); break; case WindowTwoRecord.sid: retval = new WindowTwoRecord(rectype, size, data); break; case SelectionRecord.sid: retval = new SelectionRecord(rectype, size, data); break; case ContinueRecord.sid: retval = new ContinueRecord(rectype, size, data); break; case LabelRecord.sid: retval = new LabelRecord(rectype, size, data); break; case MulRKRecord.sid: retval = new MulRKRecord(rectype, size, data); break; case MulBlankRecord.sid: retval = new MulBlankRecord(rectype, size, data); break; case BlankRecord.sid: retval = new BlankRecord(rectype, size, data); break; case BoolErrRecord.sid: retval = new BoolErrRecord(rectype, size, data); break; case ColumnInfoRecord.sid: retval = new ColumnInfoRecord(rectype, size, data); break; case MergeCellsRecord.sid: retval = new MergeCellsRecord(rectype, size, data); break; case AreaRecord.sid: retval = new AreaRecord(rectype, size, data); break; case DataFormatRecord.sid: retval = new DataFormatRecord(rectype, size, data); break; case BarRecord.sid: retval = new BarRecord(rectype, size, data); break; case DatRecord.sid: retval = new DatRecord(rectype, size, data); break; case PlotGrowthRecord.sid: retval = new PlotGrowthRecord(rectype, size, data); break; case UnitsRecord.sid: retval = new UnitsRecord(rectype, size, data); break; case FrameRecord.sid: retval = new FrameRecord(rectype, size, data); break; case ValueRangeRecord.sid: retval = new ValueRangeRecord(rectype, size, data); break; case SeriesListRecord.sid: retval = new SeriesListRecord(rectype, size, data); break; case FontBasisRecord.sid: retval = new FontBasisRecord(rectype, size, data); break; case FontIndexRecord.sid: retval = new FontIndexRecord(rectype, size, data); break; case LineFormatRecord.sid: retval = new LineFormatRecord(rectype, size, data); break; case AreaFormatRecord.sid: retval = new AreaFormatRecord(rectype, size, data); break; case LinkedDataRecord.sid: retval = new LinkedDataRecord(rectype, size, data); break; case FormulaRecord.sid: retval = new FormulaRecord(rectype, size, data); break; case SheetPropertiesRecord.sid: retval = new FormulaRecord(rectype, size, data); break; default : retval = new UnknownRecord(rectype, size, data); } if (realretval == null) { realretval = new Record[1]; realretval[0] = retval; System.out.println("recordid = 0x" + Integer.toHexString(rectype) + ", size =" + size); System.out.println(realretval[0].toString()); } return realretval; }
private static Record[] createRecord(short rectype, short size, byte[] data) { Record retval = null; Record[] realretval = null; // int irectype = rectype; switch (rectype) { case ChartRecord.sid: retval = new ChartRecord(rectype, size, data); break; case ChartFormatRecord.sid: retval = new ChartFormatRecord(rectype, size, data); break; case SeriesRecord.sid: retval = new SeriesRecord(rectype, size, data); break; case BeginRecord.sid: retval = new BeginRecord(rectype, size, data); break; case EndRecord.sid: retval = new EndRecord(rectype, size, data); break; case BOFRecord.sid: retval = new BOFRecord(rectype, size, data); break; case InterfaceHdrRecord.sid: retval = new InterfaceHdrRecord(rectype, size, data); break; case MMSRecord.sid: retval = new MMSRecord(rectype, size, data); break; case InterfaceEndRecord.sid: retval = new InterfaceEndRecord(rectype, size, data); break; case WriteAccessRecord.sid: retval = new WriteAccessRecord(rectype, size, data); break; case CodepageRecord.sid: retval = new CodepageRecord(rectype, size, data); break; case DSFRecord.sid: retval = new DSFRecord(rectype, size, data); break; case TabIdRecord.sid: retval = new TabIdRecord(rectype, size, data); break; case FnGroupCountRecord.sid: retval = new FnGroupCountRecord(rectype, size, data); break; case WindowProtectRecord.sid: retval = new WindowProtectRecord(rectype, size, data); break; case ProtectRecord.sid: retval = new ProtectRecord(rectype, size, data); break; case PasswordRecord.sid: retval = new PasswordRecord(rectype, size, data); break; case ProtectionRev4Record.sid: retval = new ProtectionRev4Record(rectype, size, data); break; case PasswordRev4Record.sid: retval = new PasswordRev4Record(rectype, size, data); break; case WindowOneRecord.sid: retval = new WindowOneRecord(rectype, size, data); break; case BackupRecord.sid: retval = new BackupRecord(rectype, size, data); break; case HideObjRecord.sid: retval = new HideObjRecord(rectype, size, data); break; case DateWindow1904Record.sid: retval = new DateWindow1904Record(rectype, size, data); break; case PrecisionRecord.sid: retval = new PrecisionRecord(rectype, size, data); break; case RefreshAllRecord.sid: retval = new RefreshAllRecord(rectype, size, data); break; case BookBoolRecord.sid: retval = new BookBoolRecord(rectype, size, data); break; case FontRecord.sid: retval = new FontRecord(rectype, size, data); break; case FormatRecord.sid: retval = new FormatRecord(rectype, size, data); break; case ExtendedFormatRecord.sid: retval = new ExtendedFormatRecord(rectype, size, data); break; case StyleRecord.sid: retval = new StyleRecord(rectype, size, data); break; case UseSelFSRecord.sid: retval = new UseSelFSRecord(rectype, size, data); break; case BoundSheetRecord.sid: retval = new BoundSheetRecord(rectype, size, data); break; case CountryRecord.sid: retval = new CountryRecord(rectype, size, data); break; case SSTRecord.sid: retval = new SSTRecord(rectype, size, data); break; case ExtSSTRecord.sid: retval = new ExtSSTRecord(rectype, size, data); break; case EOFRecord.sid: retval = new EOFRecord(rectype, size, data); break; case IndexRecord.sid: retval = new IndexRecord(rectype, size, data); break; case CalcModeRecord.sid: retval = new CalcModeRecord(rectype, size, data); break; case CalcCountRecord.sid: retval = new CalcCountRecord(rectype, size, data); break; case RefModeRecord.sid: retval = new RefModeRecord(rectype, size, data); break; case IterationRecord.sid: retval = new IterationRecord(rectype, size, data); break; case DeltaRecord.sid: retval = new DeltaRecord(rectype, size, data); break; case SaveRecalcRecord.sid: retval = new SaveRecalcRecord(rectype, size, data); break; case PrintHeadersRecord.sid: retval = new PrintHeadersRecord(rectype, size, data); break; case PrintGridlinesRecord.sid: retval = new PrintGridlinesRecord(rectype, size, data); break; case GridsetRecord.sid: retval = new GridsetRecord(rectype, size, data); break; case GutsRecord.sid: retval = new GutsRecord(rectype, size, data); break; case DefaultRowHeightRecord.sid: retval = new DefaultRowHeightRecord(rectype, size, data); break; case WSBoolRecord.sid: retval = new WSBoolRecord(rectype, size, data); break; case HeaderRecord.sid: retval = new HeaderRecord(rectype, size, data); break; case FooterRecord.sid: retval = new FooterRecord(rectype, size, data); break; case HCenterRecord.sid: retval = new HCenterRecord(rectype, size, data); break; case VCenterRecord.sid: retval = new VCenterRecord(rectype, size, data); break; case PrintSetupRecord.sid: retval = new PrintSetupRecord(rectype, size, data); break; case DefaultColWidthRecord.sid: retval = new DefaultColWidthRecord(rectype, size, data); break; case DimensionsRecord.sid: retval = new DimensionsRecord(rectype, size, data); break; case RowRecord.sid: retval = new RowRecord(rectype, size, data); break; case LabelSSTRecord.sid: retval = new LabelSSTRecord(rectype, size, data); break; case RKRecord.sid: retval = new RKRecord(rectype, size, data); break; case NumberRecord.sid: retval = new NumberRecord(rectype, size, data); break; case DBCellRecord.sid: retval = new DBCellRecord(rectype, size, data); break; case WindowTwoRecord.sid: retval = new WindowTwoRecord(rectype, size, data); break; case SelectionRecord.sid: retval = new SelectionRecord(rectype, size, data); break; case ContinueRecord.sid: retval = new ContinueRecord(rectype, size, data); break; case LabelRecord.sid: retval = new LabelRecord(rectype, size, data); break; case MulRKRecord.sid: retval = new MulRKRecord(rectype, size, data); break; case MulBlankRecord.sid: retval = new MulBlankRecord(rectype, size, data); break; case BlankRecord.sid: retval = new BlankRecord(rectype, size, data); break; case BoolErrRecord.sid: retval = new BoolErrRecord(rectype, size, data); break; case ColumnInfoRecord.sid: retval = new ColumnInfoRecord(rectype, size, data); break; case MergeCellsRecord.sid: retval = new MergeCellsRecord(rectype, size, data); break; case AreaRecord.sid: retval = new AreaRecord(rectype, size, data); break; case DataFormatRecord.sid: retval = new DataFormatRecord(rectype, size, data); break; case BarRecord.sid: retval = new BarRecord(rectype, size, data); break; case DatRecord.sid: retval = new DatRecord(rectype, size, data); break; case PlotGrowthRecord.sid: retval = new PlotGrowthRecord(rectype, size, data); break; case UnitsRecord.sid: retval = new UnitsRecord(rectype, size, data); break; case FrameRecord.sid: retval = new FrameRecord(rectype, size, data); break; case ValueRangeRecord.sid: retval = new ValueRangeRecord(rectype, size, data); break; case SeriesListRecord.sid: retval = new SeriesListRecord(rectype, size, data); break; case FontBasisRecord.sid: retval = new FontBasisRecord(rectype, size, data); break; case FontIndexRecord.sid: retval = new FontIndexRecord(rectype, size, data); break; case LineFormatRecord.sid: retval = new LineFormatRecord(rectype, size, data); break; case AreaFormatRecord.sid: retval = new AreaFormatRecord(rectype, size, data); break; case LinkedDataRecord.sid: retval = new LinkedDataRecord(rectype, size, data); break; case FormulaRecord.sid: retval = new FormulaRecord(rectype, size, data); break; case SheetPropertiesRecord.sid: retval = new SheetPropertiesRecord(rectype, size, data); break; default : retval = new UnknownRecord(rectype, size, data); } if (realretval == null) { realretval = new Record[1]; realretval[0] = retval; System.out.println("recordid = 0x" + Integer.toHexString(rectype) + ", size =" + size); System.out.println(realretval[0].toString()); } return realretval; }
diff --git a/src/contributions/resources/wiki/src/java/org/wyona/yanel/impl/resources/LinkChecker.java b/src/contributions/resources/wiki/src/java/org/wyona/yanel/impl/resources/LinkChecker.java index b85ac9794..0115d7326 100644 --- a/src/contributions/resources/wiki/src/java/org/wyona/yanel/impl/resources/LinkChecker.java +++ b/src/contributions/resources/wiki/src/java/org/wyona/yanel/impl/resources/LinkChecker.java @@ -1,122 +1,122 @@ package org.wyona.yanel.impl.resources; import java.io.ByteArrayInputStream; import org.apache.log4j.Category; import org.wyona.yarep.core.RepositoryFactory; import org.wyona.yarep.util.RepoPath; import org.wyona.yanel.core.Yanel; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class LinkChecker extends DefaultHandler { private static Category log = Category.getInstance(LinkChecker.class); private ByteArrayInputStream byteArrayInputStream = null; private StringBuffer transformedXmlAsBuffer = null; private String path2Resource = null; /** * this array with protocols will all be handled as external links * and therefor they dont have to be checked if they exist in repository */ private String[] externalLinks = { "http:", "ftp:", "https:", "mailto:", "news:", "file:", "rtsp:", "mms:", "ldap:", "gopher:", "nntp:", "telnet:", "wais:", "prospero:", "z39.50s", "z39.50r", "vemmi:", "imap:", "nfs:", "acap:", "tip:", "pop:", "dav:", "opaquelocktoken:", "sip:", "sips:", "tel:", "fax:", "modem:", "soap.beep:", "soap.beeps", "xmlrpc.beep", "xmlrpc.beeps", "urn:", "go:", "h323:", "ipp:", "tftp:", "mupdate:", "pres:", "im:", "mtqp", "smb:" }; public LinkChecker(String path2Resource) { this.path2Resource = path2Resource; } public void startDocument() throws SAXException { transformedXmlAsBuffer = new StringBuffer(); } public void endDocument() throws SAXException { setResultInputStream(); } public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { String eName = ("".equals(localName)) ? qName : localName; transformedXmlAsBuffer.append("<" + eName); if(eName.equals("Link")) { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); if(aName.equals("href")) { if(aValue.startsWith("external_")) { //do not check this link cause it is EXTERNAL aValue = aValue.substring(9); } else {//check internal links if they already exist boolean externalLink = false; for(int j=0; j<externalLinks.length; j++) { if(aValue.startsWith(externalLinks[j])) { externalLink = true; break; } } if(!externalLink && !resourceExists(aValue)) { - log.error("Resource : [" + aValue + "] does not exist"); + log.warn("Link : [" + aValue + "] does not exist"); transformedXmlAsBuffer.append(" exist=\"false\""); } } } transformedXmlAsBuffer.append(" " + aName + "=\"" + aValue + "\""); } } else { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); StringBuffer tmp = new StringBuffer(); for(int j=0; j<aValue.length(); j++) { if(aValue.charAt(j) == '"') tmp.append("&#34;"); else tmp.append(aValue.charAt(j)); } transformedXmlAsBuffer.append(" " + aName + "=\"" + tmp.toString() + "\""); } } transformedXmlAsBuffer.append(">"); } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { String eName = ("".equals(localName)) ? qName : localName; transformedXmlAsBuffer.append("</" + eName + ">"); } public void characters(char[] buf, int offset, int len) throws SAXException { String s = new String(buf, offset, len); transformedXmlAsBuffer.append(s); } private void setResultInputStream() { this.byteArrayInputStream = new ByteArrayInputStream(transformedXmlAsBuffer.toString().getBytes()); } public ByteArrayInputStream getInputStream() { return this.byteArrayInputStream; } private boolean resourceExists(String path) { if(!path.startsWith("/")) { path = path2Resource + path; } log.debug("checking link --> " + path); RepoPath rp; try { rp = new org.wyona.yarep.util.YarepUtil().getRepositoryPath(new org.wyona.yarep.core.Path(path), Yanel.getInstance().getRepositoryFactory("DefaultRepositoryFactory")); return rp.getRepo().isResource(new org.wyona.yarep.core.Path(rp.getPath().toString())); } catch (Exception e) { log.error(e.getMessage(), e); } return false; } }
true
true
public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { String eName = ("".equals(localName)) ? qName : localName; transformedXmlAsBuffer.append("<" + eName); if(eName.equals("Link")) { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); if(aName.equals("href")) { if(aValue.startsWith("external_")) { //do not check this link cause it is EXTERNAL aValue = aValue.substring(9); } else {//check internal links if they already exist boolean externalLink = false; for(int j=0; j<externalLinks.length; j++) { if(aValue.startsWith(externalLinks[j])) { externalLink = true; break; } } if(!externalLink && !resourceExists(aValue)) { log.error("Resource : [" + aValue + "] does not exist"); transformedXmlAsBuffer.append(" exist=\"false\""); } } } transformedXmlAsBuffer.append(" " + aName + "=\"" + aValue + "\""); } } else { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); StringBuffer tmp = new StringBuffer(); for(int j=0; j<aValue.length(); j++) { if(aValue.charAt(j) == '"') tmp.append("&#34;"); else tmp.append(aValue.charAt(j)); } transformedXmlAsBuffer.append(" " + aName + "=\"" + tmp.toString() + "\""); } } transformedXmlAsBuffer.append(">"); }
public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { String eName = ("".equals(localName)) ? qName : localName; transformedXmlAsBuffer.append("<" + eName); if(eName.equals("Link")) { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); if(aName.equals("href")) { if(aValue.startsWith("external_")) { //do not check this link cause it is EXTERNAL aValue = aValue.substring(9); } else {//check internal links if they already exist boolean externalLink = false; for(int j=0; j<externalLinks.length; j++) { if(aValue.startsWith(externalLinks[j])) { externalLink = true; break; } } if(!externalLink && !resourceExists(aValue)) { log.warn("Link : [" + aValue + "] does not exist"); transformedXmlAsBuffer.append(" exist=\"false\""); } } } transformedXmlAsBuffer.append(" " + aName + "=\"" + aValue + "\""); } } else { for(int i = 0; i < attrs.getLength(); i++) { String aName = attrs.getQName(i); String aValue = attrs.getValue(i); StringBuffer tmp = new StringBuffer(); for(int j=0; j<aValue.length(); j++) { if(aValue.charAt(j) == '"') tmp.append("&#34;"); else tmp.append(aValue.charAt(j)); } transformedXmlAsBuffer.append(" " + aName + "=\"" + tmp.toString() + "\""); } } transformedXmlAsBuffer.append(">"); }
diff --git a/src/com/jpii/navalbattle/game/gui/RightHud.java b/src/com/jpii/navalbattle/game/gui/RightHud.java index 347bbd8a..f2ff973a 100644 --- a/src/com/jpii/navalbattle/game/gui/RightHud.java +++ b/src/com/jpii/navalbattle/game/gui/RightHud.java @@ -1,112 +1,112 @@ package com.jpii.navalbattle.game.gui; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import com.jpii.navalbattle.game.entity.MoveableEntity; import com.jpii.navalbattle.game.entity.PortEntity; import com.jpii.navalbattle.pavo.grid.Entity; import com.jpii.navalbattle.pavo.gui.controls.Control; import com.jpii.navalbattle.util.FileUtils; public class RightHud { BufferedImage entityImg; int boxwidth,boxheight,boxx,boxy; int centerx,centery; int imgx,imgy; String location = new String(""); String health = new String(""); String movement = new String(""); String missiles = new String(""); Entity display; MoveableEntity move; public RightHud(Control parent,int width, int height){ centerx = width-210; centery = height/2; } public void draw(Graphics2D g){ drawFrame(g, boxx, boxy, boxwidth, boxheight); if(display!=null){ g.drawImage(entityImg,boxx+50,boxy+50,null); drawString(g,location, centerx, centery+60); drawString(g,health, centerx, centery-45); drawString(g,movement, centerx, centery+40); drawString(g,missiles, centerx, centery-25); } } public void setEntity(Entity e,MoveableEntity me){ display = e; move = me; } private void drawFrame(Graphics2D g,int x, int y, int width, int height) { g.setColor(new Color(126,105,65)); g.fillRect(x,y,width,height); g.setColor(new Color(65,54,33)); for (int x22 = x+8; x22 < (x+width)-8; x22 += 8) { g.drawLine(x22+x-50,y,x+x22+4-50,y+8); } for (int x22 = x+8; x22 < (x+width)-8; x22 += 8) { g.drawLine(x22+4+x-50,y+height-9,x22+x-50,y+height); } for (int y22 = 8+y; y22 < (y+height)-8; y22 += 8) { g.drawLine(x,y22+y,8+x,y+y22+4); } for (int y22 = 8+y; y22 < (y+height)-8; y22 += 8) { g.drawLine(x+height-9,y+y22+4,x+width,y+y22); } g.setColor(new Color(169,140,86)); g.fillRect(8+x,y+8,width-16,height-16); g.setColor(Color.black); g.drawRect(x,y,width-1,height-1); g.drawRect(8+x,8+y,width-16,height-16); } private void drawString(Graphics2D g,String s,int x, int y){ if(s!=null){ g.drawString(s, x-(getWidth(g,s))/2, y); } } private int getWidth(Graphics2D g,String s){ return 4+g.getFontMetrics().stringWidth(s); } public void update(){ boxx = boxy = boxheight = boxwidth = 0; missiles = health = movement = ""; if(display!=null){ if (display.getHandle()%10 == 2) { PortEntity display = (PortEntity)this.display; entityImg = display.getIcon(); } else entityImg = FileUtils.getImage(display.imgLocation); int tempwidth = entityImg.getWidth(); int tempheight = entityImg.getHeight(); boxx = centerx - (tempwidth/2) - 50; boxy = centery - (tempheight/2) - 50; boxwidth = tempwidth+100; boxheight = tempheight+100; - location = ("[X:"+display.getLocation().getCol()+" Y:"+display.getLocation().getRow()+"]"); + location = ("[R:"+display.getLocation().getRow()+" C:"+display.getLocation().getCol()+"]"); if(move!=null){ health = ("Health: "+move.getPercentHealth()+"%"); movement = ("Movement Left: "+(move.getMaxMovement()-move.getMoved())+" out of "+move.getMaxMovement()); if(move.getMissileCount()>0){ if(move.getHandle()!=21){ missiles="Missiles Left: "+move.getMissileCount(); } } } else if(display.getHandle()%10 == 2){ PortEntity temp = (PortEntity) display; health = ("Health: "+temp.getPercentHealth()+"%"); } } } }
true
true
public void update(){ boxx = boxy = boxheight = boxwidth = 0; missiles = health = movement = ""; if(display!=null){ if (display.getHandle()%10 == 2) { PortEntity display = (PortEntity)this.display; entityImg = display.getIcon(); } else entityImg = FileUtils.getImage(display.imgLocation); int tempwidth = entityImg.getWidth(); int tempheight = entityImg.getHeight(); boxx = centerx - (tempwidth/2) - 50; boxy = centery - (tempheight/2) - 50; boxwidth = tempwidth+100; boxheight = tempheight+100; location = ("[X:"+display.getLocation().getCol()+" Y:"+display.getLocation().getRow()+"]"); if(move!=null){ health = ("Health: "+move.getPercentHealth()+"%"); movement = ("Movement Left: "+(move.getMaxMovement()-move.getMoved())+" out of "+move.getMaxMovement()); if(move.getMissileCount()>0){ if(move.getHandle()!=21){ missiles="Missiles Left: "+move.getMissileCount(); } } } else if(display.getHandle()%10 == 2){ PortEntity temp = (PortEntity) display; health = ("Health: "+temp.getPercentHealth()+"%"); } } }
public void update(){ boxx = boxy = boxheight = boxwidth = 0; missiles = health = movement = ""; if(display!=null){ if (display.getHandle()%10 == 2) { PortEntity display = (PortEntity)this.display; entityImg = display.getIcon(); } else entityImg = FileUtils.getImage(display.imgLocation); int tempwidth = entityImg.getWidth(); int tempheight = entityImg.getHeight(); boxx = centerx - (tempwidth/2) - 50; boxy = centery - (tempheight/2) - 50; boxwidth = tempwidth+100; boxheight = tempheight+100; location = ("[R:"+display.getLocation().getRow()+" C:"+display.getLocation().getCol()+"]"); if(move!=null){ health = ("Health: "+move.getPercentHealth()+"%"); movement = ("Movement Left: "+(move.getMaxMovement()-move.getMoved())+" out of "+move.getMaxMovement()); if(move.getMissileCount()>0){ if(move.getHandle()!=21){ missiles="Missiles Left: "+move.getMissileCount(); } } } else if(display.getHandle()%10 == 2){ PortEntity temp = (PortEntity) display; health = ("Health: "+temp.getPercentHealth()+"%"); } } }
diff --git a/source/ch/ethz/ssh2/sftp/SFTPv3Client.java b/source/ch/ethz/ssh2/sftp/SFTPv3Client.java index a75debba4..bd9a46d56 100644 --- a/source/ch/ethz/ssh2/sftp/SFTPv3Client.java +++ b/source/ch/ethz/ssh2/sftp/SFTPv3Client.java @@ -1,1378 +1,1365 @@ package ch.ethz.ssh2.sftp; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.channel.Channel; import ch.ethz.ssh2.log.Logger; import ch.ethz.ssh2.packets.TypesReader; import ch.ethz.ssh2.packets.TypesWriter; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; /** * A <code>SFTPv3Client</code> represents a SFTP (protocol version 3) * client connection tunnelled over a SSH-2 connection. This is a very simple * (synchronous) implementation. * <p/> * Basically, most methods in this class map directly to one of * the packet types described in draft-ietf-secsh-filexfer-02.txt. * <p/> * Note: this is experimental code. * <p/> * Error handling: the methods of this class throw IOExceptions. However, unless * there is catastrophic failure, exceptions of the type {@link SFTPv3Client} will * be thrown (a subclass of IOException). Therefore, you can implement more verbose * behavior by checking if a thrown exception if of this type. If yes, then you * can cast the exception and access detailed information about the failure. * <p/> * Notes about file names, directory names and paths, copy-pasted * from the specs: * <ul> * <li>SFTP v3 represents file names as strings. File names are * assumed to use the slash ('/') character as a directory separator.</li> * <li>File names starting with a slash are "absolute", and are relative to * the root of the file system. Names starting with any other character * are relative to the user's default directory (home directory).</li> * <li>Servers SHOULD interpret a path name component ".." as referring to * the parent directory, and "." as referring to the current directory. * If the server implementation limits access to certain parts of the * file system, it must be extra careful in parsing file names when * enforcing such restrictions. There have been numerous reported * security bugs where a ".." in a path name has allowed access outside * the intended area.</li> * <li>An empty path name is valid, and it refers to the user's default * directory (usually the user's home directory).</li> * </ul> * <p/> * If you are still not tired then please go on and read the comment for * {@link #setCharset(String)}. * * @author Christian Plattner, [email protected] * @version $Id$ */ public class SFTPv3Client { private static final Logger log = Logger.getLogger(SFTPv3Client.class); private final Connection conn; private final Session sess; private boolean flag_closed = false; private InputStream is; private OutputStream os; private int protocol_version = 0; private Map<String, byte[]> server_extensions = new HashMap<String, byte[]>(); private int next_request_id = 1000; private String charsetName = null; /** * Create a SFTP v3 client. * * @param conn The underlying SSH-2 connection to be used. * @throws IOException */ public SFTPv3Client(Connection conn) throws IOException { if(conn == null) { throw new IllegalArgumentException("Cannot accept null argument!"); } this.conn = conn; log.log("Opening session and starting SFTP subsystem."); sess = conn.openSession(); sess.startSubSystem("sftp"); is = sess.getStdout(); os = new BufferedOutputStream(sess.getStdin(), 2048); if(is == null) { throw new IOException("There is a problem with the streams of the underlying channel."); } init(); } /** * Set the charset used to convert between Java Unicode Strings and byte encodings * used by the server for paths and file names. Unfortunately, the SFTP v3 draft * says NOTHING about such conversions (well, with the exception of error messages * which have to be in UTF-8). Newer drafts specify to use UTF-8 for file names * (if I remember correctly). However, a quick test using OpenSSH serving a EXT-3 * filesystem has shown that UTF-8 seems to be a bad choice for SFTP v3 (tested with * filenames containing german umlauts). "windows-1252" seems to work better for Europe. * Luckily, "windows-1252" is the platform default in my case =). * <p/> * If you don't set anything, then the platform default will be used (this is the default * behavior). * * @param charset the name of the charset to be used or <code>null</code> to use the platform's * default encoding. * @throws IOException * @see #getCharset() */ public void setCharset(String charset) throws IOException { if(charset == null) { charsetName = charset; return; } try { Charset.forName(charset); } catch(UnsupportedCharsetException e) { throw (IOException) new IOException("This charset is not supported").initCause(e); } charsetName = charset; } /** * The currently used charset for filename encoding/decoding. * * @return The name of the charset (<code>null</code> if the platform's default charset is being used) * @see #setCharset(String) */ public String getCharset() { return charsetName; } private void checkHandleValidAndOpen(SFTPv3FileHandle handle) throws IOException { if(handle.client != this) { throw new IOException("The file handle was created with another SFTPv3FileHandle instance."); } if(handle.isClosed) { throw new IOException("The file handle is closed."); } } private void sendMessage(int type, int requestId, byte[] msg, int off, int len) throws IOException { int msglen = len + 1; if(type != Packet.SSH_FXP_INIT) { msglen += 4; } os.write(msglen >> 24); os.write(msglen >> 16); os.write(msglen >> 8); os.write(msglen); os.write(type); if(type != Packet.SSH_FXP_INIT) { os.write(requestId >> 24); os.write(requestId >> 16); os.write(requestId >> 8); os.write(requestId); } os.write(msg, off, len); os.flush(); } private void sendMessage(int type, int requestId, byte[] msg) throws IOException { sendMessage(type, requestId, msg, 0, msg.length); } private void readBytes(byte[] buff, int pos, int len) throws IOException { while(len > 0) { int count = is.read(buff, pos, len); if(count < 0) { throw new IOException("Unexpected end of sftp stream."); } if((count == 0) || (count > len)) { throw new IOException("Underlying stream implementation is bogus!"); } len -= count; pos += count; } } /** * Read a message and guarantee that the <b>contents</b> is not larger than * <code>maxlen</code> bytes. * <p/> * Note: receiveMessage(34000) actually means that the message may be up to 34004 * bytes (the length attribute preceeding the contents is 4 bytes). * * @param maxlen * @return the message contents * @throws IOException */ private byte[] receiveMessage(int maxlen) throws IOException { byte[] msglen = new byte[4]; readBytes(msglen, 0, 4); int len = (((msglen[0] & 0xff) << 24) | ((msglen[1] & 0xff) << 16) | ((msglen[2] & 0xff) << 8) | (msglen[3] & 0xff)); if((len > maxlen) || (len <= 0)) { throw new IOException("Illegal sftp packet len: " + len); } byte[] msg = new byte[len]; readBytes(msg, 0, len); return msg; } private int generateNextRequestID() { synchronized(this) { return next_request_id++; } } private void closeHandle(byte[] handle) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(handle, 0, handle.length); sendMessage(Packet.SSH_FXP_CLOSE, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } private SFTPv3FileAttributes readAttrs(TypesReader tr) throws IOException { /* * uint32 flags * uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE * uint32 uid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID * uint32 gid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID * uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS * uint32 atime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME * uint32 mtime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME * uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED * string extended_type * string extended_data * ... more extended data (extended_type - extended_data pairs), * so that number of pairs equals extended_count */ SFTPv3FileAttributes fa = new SFTPv3FileAttributes(); int flags = tr.readUINT32(); if((flags & AttribFlags.SSH_FILEXFER_ATTR_SIZE) != 0) { log.log("SSH_FILEXFER_ATTR_SIZE"); fa.size = tr.readUINT64(); } if((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID) != 0) { log.log("SSH_FILEXFER_ATTR_V3_UIDGID"); fa.uid = tr.readUINT32(); fa.gid = tr.readUINT32(); } if((flags & AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) { log.log("SSH_FILEXFER_ATTR_PERMISSIONS"); fa.permissions = tr.readUINT32(); } if((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME) != 0) { log.log("SSH_FILEXFER_ATTR_V3_ACMODTIME"); fa.atime = tr.readUINT32(); fa.mtime = tr.readUINT32(); } if((flags & AttribFlags.SSH_FILEXFER_ATTR_EXTENDED) != 0) { int count = tr.readUINT32(); log.log("SSH_FILEXFER_ATTR_EXTENDED (" + count + ")"); /* Read it anyway to detect corrupt packets */ while(count > 0) { tr.readByteString(); tr.readByteString(); count--; } } return fa; } /** * Retrieve the file attributes of an open file. * * @param handle a SFTPv3FileHandle handle. * @return a SFTPv3FileAttributes object. * @throws IOException */ public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle) throws IOException { checkHandleValidAndOpen(handle); int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(handle.fileHandle, 0, handle.fileHandle.length); log.log("Sending SSH_FXP_FSTAT..."); sendMessage(Packet.SSH_FXP_FSTAT, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_ATTRS) { return readAttrs(tr); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); throw new SFTPException(tr.readString(), errorCode); } private SFTPv3FileAttributes statBoth(String path, int statMethod) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(path, charsetName); log.log("Sending SSH_FXP_STAT/SSH_FXP_LSTAT..."); sendMessage(statMethod, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_ATTRS) { return readAttrs(tr); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); throw new SFTPException(tr.readString(), errorCode); } /** * Retrieve the file attributes of a file. This method * follows symbolic links on the server. * * @param path See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileAttributes object. * @throws IOException * @see #lstat(String) */ public SFTPv3FileAttributes stat(String path) throws IOException { return statBoth(path, Packet.SSH_FXP_STAT); } /** * Retrieve the file attributes of a file. This method * does NOT follow symbolic links on the server. * * @param path See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileAttributes object. * @throws IOException * @see #stat(String) */ public SFTPv3FileAttributes lstat(String path) throws IOException { return statBoth(path, Packet.SSH_FXP_LSTAT); } /** * Read the target of a symbolic link. Note: OpenSSH (as of version 4.4) gets very upset * (SSH_FX_BAD_MESSAGE error) if you want to read the target of a file that is not a * symbolic link. Better check first with {@link #lstat(String)}. * * @param path See the {@link SFTPv3Client comment} for the class for more details. * @return The target of the link. * @throws IOException */ public String readLink(String path) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(path, charsetName); log.log("Sending SSH_FXP_READLINK..."); sendMessage(Packet.SSH_FXP_READLINK, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_NAME) { int count = tr.readUINT32(); if(count != 1) { throw new IOException("The server sent an invalid SSH_FXP_NAME packet."); } return tr.readString(charsetName); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); throw new SFTPException(tr.readString(), errorCode); } private void expectStatusOKMessage(int id) throws IOException { byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != id) { throw new IOException("The server sent an invalid id field."); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); if(errorCode == ErrorCodes.SSH_FX_OK) { return; } throw new SFTPException(tr.readString(), errorCode); } /** * Modify the attributes of a file. Used for operations such as changing * the ownership, permissions or access times, as well as for truncating a file. * * @param path See the {@link SFTPv3Client comment} for the class for more details. * @param attr A SFTPv3FileAttributes object. Specifies the modifications to be * made to the attributes of the file. Empty fields will be ignored. * @throws IOException */ public void setstat(String path, SFTPv3FileAttributes attr) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(path, charsetName); tw.writeBytes(createAttrs(attr)); log.log("Sending SSH_FXP_SETSTAT..."); sendMessage(Packet.SSH_FXP_SETSTAT, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Modify the attributes of a file. Used for operations such as changing * the ownership, permissions or access times, as well as for truncating a file. * * @param handle a SFTPv3FileHandle handle * @param attr A SFTPv3FileAttributes object. Specifies the modifications to be * made to the attributes of the file. Empty fields will be ignored. * @throws IOException */ public void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr) throws IOException { checkHandleValidAndOpen(handle); int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(handle.fileHandle, 0, handle.fileHandle.length); tw.writeBytes(createAttrs(attr)); log.log("Sending SSH_FXP_FSETSTAT..."); sendMessage(Packet.SSH_FXP_FSETSTAT, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Create a symbolic link on the server. Creates a link "src" that points * to "target". * * @param src See the {@link SFTPv3Client comment} for the class for more details. * @param target See the {@link SFTPv3Client comment} for the class for more details. * @throws IOException */ public void createSymlink(String src, String target) throws IOException { int req_id = generateNextRequestID(); /* Either I am too stupid to understand the SFTP draft * or the OpenSSH guys changed the semantics of src and target. */ TypesWriter tw = new TypesWriter(); tw.writeString(target, charsetName); tw.writeString(src, charsetName); log.log("Sending SSH_FXP_SYMLINK..."); sendMessage(Packet.SSH_FXP_SYMLINK, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Have the server canonicalize any given path name to an absolute path. * This is useful for converting path names containing ".." components or * relative pathnames without a leading slash into absolute paths. * * @param path See the {@link SFTPv3Client comment} for the class for more details. * @return An absolute path. * @throws IOException */ public String canonicalPath(String path) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(path, charsetName); log.log("Sending SSH_FXP_REALPATH..."); sendMessage(Packet.SSH_FXP_REALPATH, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_NAME) { int count = tr.readUINT32(); if(count != 1) { throw new IOException("The server sent an invalid SSH_FXP_NAME packet."); } return tr.readString(charsetName); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); throw new SFTPException(tr.readString(), errorCode); } private List scanDirectory(byte[] handle) throws IOException { List<SFTPv3DirectoryEntry> files = new Vector<SFTPv3DirectoryEntry>(); while(true) { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(handle, 0, handle.length); log.log("Sending SSH_FXP_READDIR..."); sendMessage(Packet.SSH_FXP_READDIR, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_NAME) { int count = tr.readUINT32(); log.log("Parsing " + count + " name entries..."); while(count > 0) { SFTPv3DirectoryEntry dirEnt = new SFTPv3DirectoryEntry(); dirEnt.filename = tr.readString(charsetName); dirEnt.longEntry = tr.readString(charsetName); dirEnt.attributes = readAttrs(tr); files.add(dirEnt); log.log("File: '" + dirEnt.filename + "'"); count--; } continue; } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); if(errorCode == ErrorCodes.SSH_FX_EOF) { return files; } throw new SFTPException(tr.readString(), errorCode); } } public final SFTPv3FileHandle openDirectory(String path) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(path, charsetName); log.log("Sending SSH_FXP_OPENDIR..."); sendMessage(Packet.SSH_FXP_OPENDIR, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_HANDLE) { log.log("Got SSH_FXP_HANDLE."); return new SFTPv3FileHandle(this, tr.readByteString()); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); String errorMessage = tr.readString(); throw new SFTPException(errorMessage, errorCode); } private String expandString(byte[] b, int off, int len) { StringBuilder sb = new StringBuilder(); for(int i = 0; i < len; i++) { int c = b[off + i] & 0xff; if((c >= 32) && (c <= 126)) { sb.append((char) c); } else { sb.append("{0x" + Integer.toHexString(c) + "}"); } } return sb.toString(); } private void init() throws IOException { /* Send SSH_FXP_INIT (version 3) */ final int client_version = 3; log.log("Sending SSH_FXP_INIT (" + client_version + ")..."); TypesWriter tw = new TypesWriter(); tw.writeUINT32(client_version); sendMessage(Packet.SSH_FXP_INIT, 0, tw.getBytes()); /* Receive SSH_FXP_VERSION */ log.log("Waiting for SSH_FXP_VERSION..."); TypesReader tr = new TypesReader(receiveMessage(34000)); /* Should be enough for any reasonable server */ int type = tr.readByte(); if(type != Packet.SSH_FXP_VERSION) { throw new IOException("The server did not send a SSH_FXP_VERSION packet (got " + type + ")"); } protocol_version = tr.readUINT32(); log.log("SSH_FXP_VERSION: protocol_version = " + protocol_version); if(protocol_version != 3) { throw new IOException("Server version " + protocol_version + " is currently not supported"); } /* Read and save extensions (if any) for later use */ while(tr.remain() != 0) { String name = tr.readString(); byte[] value = tr.readByteString(); log.log("SSH_FXP_VERSION: extension: " + name + " = '" + expandString(value, 0, value.length) + "'"); server_extensions.put(name, value); } } /** * Returns the negotiated SFTP protocol version between the client and the server. * * @return SFTP protocol version, i.e., "3". */ public int getProtocolVersion() { return protocol_version; } public boolean isConnected() { return sess.getState() == Channel.STATE_OPEN; } /** * Close this SFTP session. NEVER forget to call this method to free up * resources - even if you got an exception from one of the other methods. * Sometimes these other methods may throw an exception, saying that the * underlying channel is closed (this can happen, e.g., if the other server * sent a close message.) However, as long as you have not called the * <code>close()</code> method, you are likely wasting resources. */ public void close() { sess.close(); } /** * List the contents of a directory. * * @param dirName See the {@link SFTPv3Client comment} for the class for more details. * @return A Vector containing {@link SFTPv3DirectoryEntry} objects. * @throws IOException */ public List ls(String dirName) throws IOException { byte[] handle = openDirectory(dirName).fileHandle; List result = scanDirectory(handle); closeHandle(handle); return result; } /** * Create a new directory. * * @param dirName See the {@link SFTPv3Client comment} for the class for more details. * @param posixPermissions the permissions for this directory, e.g., "0700" (remember that * this is octal noation). The server will likely apply a umask. * @throws IOException */ public void mkdir(String dirName, int posixPermissions) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(dirName, charsetName); tw.writeUINT32(AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS); tw.writeUINT32(posixPermissions); sendMessage(Packet.SSH_FXP_MKDIR, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Remove a file. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @throws IOException */ public void rm(String fileName) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(fileName, charsetName); sendMessage(Packet.SSH_FXP_REMOVE, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Remove an empty directory. * * @param dirName See the {@link SFTPv3Client comment} for the class for more details. * @throws IOException */ public void rmdir(String dirName) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(dirName, charsetName); sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Move a file or directory. * * @param oldPath See the {@link SFTPv3Client comment} for the class for more details. * @param newPath See the {@link SFTPv3Client comment} for the class for more details. * @throws IOException */ public void mv(String oldPath, String newPath) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(oldPath, charsetName); tw.writeString(newPath, charsetName); sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes()); expectStatusOKMessage(req_id); } /** * Open the file for reading. */ public static final int SSH_FXF_READ = 0x00000001; /** * Open the file for writing. If both this and SSH_FXF_READ are * specified, the file is opened for both reading and writing. */ public static final int SSH_FXF_WRITE = 0x00000002; /** * Force all writes to append data at the end of the file. */ public static final int SSH_FXF_APPEND = 0x00000004; /** * If this flag is specified, then a new file will be created if one * does not alread exist (if O_TRUNC is specified, the new file will * be truncated to zero length if it previously exists). */ public static final int SSH_FXF_CREAT = 0x00000008; /** * Forces an existing file with the same name to be truncated to zero * length when creating a file by specifying SSH_FXF_CREAT. * SSH_FXF_CREAT MUST also be specified if this flag is used. */ public static final int SSH_FXF_TRUNC = 0x00000010; /** * Causes the request to fail if the named file already exists. */ public static final int SSH_FXF_EXCL = 0x00000020; /** * Open a file for reading. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle openFileRO(String fileName) throws IOException { return openFile(fileName, SSH_FXF_READ, null); } /** * Open a file for reading and writing. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle openFileRW(String fileName) throws IOException { return openFile(fileName, SSH_FXF_READ | SSH_FXF_WRITE, null); } /** * Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX * behavior, all writes will be appendend to the end of the file, no matter which offset * one specifies. * <p/> * A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(), * even for writes to files opened in O_APPEND mode. However, bear in mind that when working * in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file * (well, this is what the newsgroups say). * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle openFileRWAppend(String fileName) throws IOException { return openFile(fileName, SSH_FXF_READ | SSH_FXF_WRITE | SSH_FXF_APPEND, null); } /** * Open a file in append mode. The SFTP v3 draft says nothing but assuming normal POSIX * behavior, all writes will be appendend to the end of the file, no matter which offset * one specifies. * <p/> * A side note for the curious: OpenSSH does an lseek() to the specified writing offset before each write(), * even for writes to files opened in O_APPEND mode. However, bear in mind that when working * in the O_APPEND mode, each write() includes an implicit lseek() to the end of the file * (well, this is what the newsgroups say). * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle openFileWAppend(String fileName) throws IOException { return openFile(fileName, SSH_FXF_WRITE | SSH_FXF_APPEND, null); } /** * Create a file and open it for reading and writing. * Same as {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName, null)}. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFile(String fileName) throws IOException { return createFile(fileName, null); } /** * Create a file and open it for reading and writing. * You can specify the default attributes of the file (the server may or may * not respect your wishes). * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @param attr may be <code>null</code> to use server defaults. Probably only * the <code>uid</code>, <code>gid</code> and <code>permissions</code> * (remember the server may apply a umask) entries of the {@link SFTPv3FileHandle} * structure make sense. You need only to set those fields where you want * to override the server's defaults. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFile(String fileName, SFTPv3FileAttributes attr) throws IOException { return openFile(fileName, SSH_FXF_CREAT | SSH_FXF_READ | SSH_FXF_WRITE, attr); } /** * Create a file (truncate it if it already exists) and open it for writing. * Same as {@link #createFileTruncate(String, SFTPv3FileAttributes) createFileTruncate(fileName, null)}. * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFileTruncate(String fileName) throws IOException { return createFileTruncate(fileName, null); } /** * reate a file (truncate it if it already exists) and open it for writing. * You can specify the default attributes of the file (the server may or may * not respect your wishes). * * @param fileName See the {@link SFTPv3Client comment} for the class for more details. * @param attr may be <code>null</code> to use server defaults. Probably only * the <code>uid</code>, <code>gid</code> and <code>permissions</code> * (remember the server may apply a umask) entries of the {@link SFTPv3FileHandle} * structure make sense. You need only to set those fields where you want * to override the server's defaults. * @return a SFTPv3FileHandle handle * @throws IOException */ public SFTPv3FileHandle createFileTruncate(String fileName, SFTPv3FileAttributes attr) throws IOException { return openFile(fileName, SSH_FXF_CREAT | SSH_FXF_TRUNC | SSH_FXF_WRITE, attr); } private byte[] createAttrs(SFTPv3FileAttributes attr) { TypesWriter tw = new TypesWriter(); int attrFlags = 0; if(attr == null) { tw.writeUINT32(0); } else { if(attr.size != null) { attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_SIZE; } if((attr.uid != null) && (attr.gid != null)) { attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID; } if(attr.permissions != null) { attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS; } if((attr.atime != null) && (attr.mtime != null)) { attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME; } tw.writeUINT32(attrFlags); if(attr.size != null) { tw.writeUINT64(attr.size); } if((attr.uid != null) && (attr.gid != null)) { tw.writeUINT32(attr.uid); tw.writeUINT32(attr.gid); } if(attr.permissions != null) { tw.writeUINT32(attr.permissions); } if((attr.atime != null) && (attr.mtime != null)) { tw.writeUINT32(attr.atime); tw.writeUINT32(attr.mtime); } } return tw.getBytes(); } public SFTPv3FileHandle openFile(String fileName, int flags, SFTPv3FileAttributes attr) throws IOException { int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(fileName, charsetName); tw.writeUINT32(flags); tw.writeBytes(createAttrs(attr)); log.log("Sending SSH_FXP_OPEN..."); sendMessage(Packet.SSH_FXP_OPEN, req_id, tw.getBytes()); byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t == Packet.SSH_FXP_HANDLE) { log.log("Got SSH_FXP_HANDLE."); return new SFTPv3FileHandle(this, tr.readByteString()); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); String errorMessage = tr.readString(); throw new SFTPException(errorMessage, errorCode); } private static class OutstandingRequest { long serverOffset; int clientOffset; int len; int req_id; int offset; byte[] buffer; } private void sendReadRequest(int id, SFTPv3FileHandle handle, long offset, int len) throws IOException { TypesWriter tw = new TypesWriter(); tw.writeString(handle.fileHandle, 0, handle.fileHandle.length); tw.writeUINT64(offset); tw.writeUINT32(len); log.log("Sending SSH_FXP_READ (" + id + ") " + offset + "/" + len); sendMessage(Packet.SSH_FXP_READ, id, tw.getBytes()); } /** * Parallel read requests maximum size. */ private static final int DEFAULT_MAX_PARALLELISM = 64; /** * Parallel read requests. */ private int parallelism = DEFAULT_MAX_PARALLELISM; /** * @param parallelism */ public void setDownloadRequestParallelism(int parallelism) { this.parallelism = Math.min(parallelism, DEFAULT_MAX_PARALLELISM); log.log("setDownloadRequestParallelism:" + this.parallelism); } /** * Mapping request ID to request. */ Map<Integer, OutstandingRequest> pendingQueue = new HashMap<Integer, OutstandingRequest>(); /** * Read bytes from a file in a parallel fashion. As many bytes as you want will be read. * <p/> * <ul> * <li>The server will read as many bytes as it can from the file (up to <code>len</code>), * and return them.</li> * <li>If EOF is encountered before reading any data, <code>-1</code> is returned. * <li>If an error occurs, an exception is thrown</li>. * <li>For normal disk files, it is guaranteed that the server will return the specified * number of bytes, or up to end of file. For, e.g., device files this may return * fewer bytes than requested.</li> * </ul> * * @param handle a SFTPv3FileHandle handle * @param fileOffset offset (in bytes) in the file * @param dst the destination byte array * @param dstoff offset in the destination byte array * @param len how many bytes to read, 0 &lt; len * @return the number of bytes that could be read, may be less than requested if * the end of the file is reached, -1 is returned in case of <code>EOF</code> * @throws IOException */ public int download(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException { boolean errorOccured = false; - int errorCode = 0; - String errorMessage = null; - int errorClientOffset = 0; checkHandleValidAndOpen(handle); int remaining = len * parallelism; int clientOffset = dstoff; long serverOffset = fileOffset; for(OutstandingRequest r : pendingQueue.values()) { // Server offset should take pending requests into account. serverOffset += r.len; } while(true) { /* If there was an error and no outstanding request - stop */ if((pendingQueue.size() == 0) && errorOccured) { break; } /* Send as many requests as we are allowed to */ while(pendingQueue.size() < parallelism) { if(errorOccured) { break; } /* Send the next request */ OutstandingRequest req = new OutstandingRequest(); req.req_id = generateNextRequestID(); req.serverOffset = serverOffset; req.clientOffset = clientOffset; req.len = (remaining > len) ? len : remaining; req.buffer = dst; req.offset = dstoff; serverOffset += req.len; clientOffset += req.len; remaining -= req.len; sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } /* Are we done? */ if(pendingQueue.size() == 0) { break; } /* No, receive a single answer */ byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int type = tr.readByte(); int rep_id = tr.readUINT32(); /* Search the pending queue */ OutstandingRequest req = pendingQueue.get(rep_id); /* Should shutdown here, no point in going on */ - if(req == null) { + if(null == req) { throw new IOException("The server sent an invalid id field."); } pendingQueue.remove(rep_id); /* Evaluate the answer */ if(type == Packet.SSH_FXP_STATUS) { /* In any case, stop sending more packets */ int code = tr.readUINT32(); String msg = tr.readString(); if(log.isEnabled()) { String[] desc = ErrorCodes.getDescription(code); log.log("Got SSH_FXP_STATUS (" + req.req_id + ") (" + ((desc != null) ? desc[0] : "UNKNOWN") + ")"); } - if((!errorOccured) || (errorClientOffset > req.clientOffset)) { - errorOccured = true; - errorCode = code; - errorMessage = msg; - errorClientOffset = req.clientOffset; + // Flag to read all pending requests but don't send any more. + errorOccured = true; + if(pendingQueue.isEmpty()) { + if(ErrorCodes.SSH_FX_EOF == code) { + return -1; + } + throw new SFTPException(msg, code); } } else if(type == Packet.SSH_FXP_DATA) { /* OK, collect data */ int readLen = tr.readUINT32(); if((readLen < 0) || (readLen > req.len)) { throw new IOException("The server sent an invalid length field in a SSH_FXP_DATA packet."); } if(log.isEnabled()) { log.log("Got SSH_FXP_DATA (" + req.req_id + ") " + req.serverOffset + "/" + readLen + " (requested: " + req.len + ")"); } // Read bytes into buffer tr.readBytes(req.buffer, req.offset, readLen); if(readLen < req.len) { /* Send this request packet again to request the remaing data in this slot. */ req.req_id = generateNextRequestID(); req.serverOffset += readLen; req.clientOffset += readLen; req.len -= readLen; log.log("Requesting again: " + req.serverOffset + "/" + req.len); sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } return readLen; } else { throw new IOException("The SFTP server sent an unexpected packet type (" + type + ")"); } } - if(errorOccured) { - if(ErrorCodes.SSH_FX_EOF == errorCode) { - log.log("Got SSH_FX_EOF."); - if(0 == errorClientOffset) { - return -1; - } - if(dstoff == errorClientOffset) { - return -1; - } - return errorClientOffset; - } - throw new SFTPException(errorMessage, errorCode); - } + // Should never reach here. throw new SFTPException("No EOF reached", -1); } /** * Write bytes to a file. If <code>len</code> &gt; 32768, then the write operation will * be split into multiple writes. * * @param handle a SFTPv3FileHandle handle. * @param fileOffset offset (in bytes) in the file. * @param src the source byte array. * @param srcoff offset in the source byte array. * @param len how many bytes to write. * @throws IOException */ public void upload(SFTPv3FileHandle handle, long fileOffset, byte[] src, int srcoff, int len) throws IOException { checkHandleValidAndOpen(handle); while(len > 0) { int writeRequestLen = len; if(writeRequestLen > 32768) { writeRequestLen = 32768; } int req_id = generateNextRequestID(); TypesWriter tw = new TypesWriter(); tw.writeString(handle.fileHandle, 0, handle.fileHandle.length); tw.writeUINT64(fileOffset); tw.writeString(src, srcoff, writeRequestLen); log.log("Sending SSH_FXP_WRITE..."); sendMessage(Packet.SSH_FXP_WRITE, req_id, tw.getBytes()); fileOffset += writeRequestLen; srcoff += writeRequestLen; len -= writeRequestLen; byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int t = tr.readByte(); int rep_id = tr.readUINT32(); if(rep_id != req_id) { throw new IOException("The server sent an invalid id field."); } if(t != Packet.SSH_FXP_STATUS) { throw new IOException("The SFTP server sent an unexpected packet type (" + t + ")"); } int errorCode = tr.readUINT32(); if(errorCode == ErrorCodes.SSH_FX_OK) { continue; } String errorMessage = tr.readString(); throw new SFTPException(errorMessage, errorCode); } } /** * Close a file. * * @param handle a SFTPv3FileHandle handle * @throws IOException */ public void closeFile(SFTPv3FileHandle handle) throws IOException { if(handle == null) { throw new IllegalArgumentException("the handle argument may not be null"); } try { if(!handle.isClosed) { closeHandle(handle.fileHandle); } } finally { handle.isClosed = true; } } }
false
true
public int download(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException { boolean errorOccured = false; int errorCode = 0; String errorMessage = null; int errorClientOffset = 0; checkHandleValidAndOpen(handle); int remaining = len * parallelism; int clientOffset = dstoff; long serverOffset = fileOffset; for(OutstandingRequest r : pendingQueue.values()) { // Server offset should take pending requests into account. serverOffset += r.len; } while(true) { /* If there was an error and no outstanding request - stop */ if((pendingQueue.size() == 0) && errorOccured) { break; } /* Send as many requests as we are allowed to */ while(pendingQueue.size() < parallelism) { if(errorOccured) { break; } /* Send the next request */ OutstandingRequest req = new OutstandingRequest(); req.req_id = generateNextRequestID(); req.serverOffset = serverOffset; req.clientOffset = clientOffset; req.len = (remaining > len) ? len : remaining; req.buffer = dst; req.offset = dstoff; serverOffset += req.len; clientOffset += req.len; remaining -= req.len; sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } /* Are we done? */ if(pendingQueue.size() == 0) { break; } /* No, receive a single answer */ byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int type = tr.readByte(); int rep_id = tr.readUINT32(); /* Search the pending queue */ OutstandingRequest req = pendingQueue.get(rep_id); /* Should shutdown here, no point in going on */ if(req == null) { throw new IOException("The server sent an invalid id field."); } pendingQueue.remove(rep_id); /* Evaluate the answer */ if(type == Packet.SSH_FXP_STATUS) { /* In any case, stop sending more packets */ int code = tr.readUINT32(); String msg = tr.readString(); if(log.isEnabled()) { String[] desc = ErrorCodes.getDescription(code); log.log("Got SSH_FXP_STATUS (" + req.req_id + ") (" + ((desc != null) ? desc[0] : "UNKNOWN") + ")"); } if((!errorOccured) || (errorClientOffset > req.clientOffset)) { errorOccured = true; errorCode = code; errorMessage = msg; errorClientOffset = req.clientOffset; } } else if(type == Packet.SSH_FXP_DATA) { /* OK, collect data */ int readLen = tr.readUINT32(); if((readLen < 0) || (readLen > req.len)) { throw new IOException("The server sent an invalid length field in a SSH_FXP_DATA packet."); } if(log.isEnabled()) { log.log("Got SSH_FXP_DATA (" + req.req_id + ") " + req.serverOffset + "/" + readLen + " (requested: " + req.len + ")"); } // Read bytes into buffer tr.readBytes(req.buffer, req.offset, readLen); if(readLen < req.len) { /* Send this request packet again to request the remaing data in this slot. */ req.req_id = generateNextRequestID(); req.serverOffset += readLen; req.clientOffset += readLen; req.len -= readLen; log.log("Requesting again: " + req.serverOffset + "/" + req.len); sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } return readLen; } else { throw new IOException("The SFTP server sent an unexpected packet type (" + type + ")"); } } if(errorOccured) { if(ErrorCodes.SSH_FX_EOF == errorCode) { log.log("Got SSH_FX_EOF."); if(0 == errorClientOffset) { return -1; } if(dstoff == errorClientOffset) { return -1; } return errorClientOffset; } throw new SFTPException(errorMessage, errorCode); } throw new SFTPException("No EOF reached", -1); }
public int download(SFTPv3FileHandle handle, long fileOffset, byte[] dst, int dstoff, int len) throws IOException { boolean errorOccured = false; checkHandleValidAndOpen(handle); int remaining = len * parallelism; int clientOffset = dstoff; long serverOffset = fileOffset; for(OutstandingRequest r : pendingQueue.values()) { // Server offset should take pending requests into account. serverOffset += r.len; } while(true) { /* If there was an error and no outstanding request - stop */ if((pendingQueue.size() == 0) && errorOccured) { break; } /* Send as many requests as we are allowed to */ while(pendingQueue.size() < parallelism) { if(errorOccured) { break; } /* Send the next request */ OutstandingRequest req = new OutstandingRequest(); req.req_id = generateNextRequestID(); req.serverOffset = serverOffset; req.clientOffset = clientOffset; req.len = (remaining > len) ? len : remaining; req.buffer = dst; req.offset = dstoff; serverOffset += req.len; clientOffset += req.len; remaining -= req.len; sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } /* Are we done? */ if(pendingQueue.size() == 0) { break; } /* No, receive a single answer */ byte[] resp = receiveMessage(34000); TypesReader tr = new TypesReader(resp); int type = tr.readByte(); int rep_id = tr.readUINT32(); /* Search the pending queue */ OutstandingRequest req = pendingQueue.get(rep_id); /* Should shutdown here, no point in going on */ if(null == req) { throw new IOException("The server sent an invalid id field."); } pendingQueue.remove(rep_id); /* Evaluate the answer */ if(type == Packet.SSH_FXP_STATUS) { /* In any case, stop sending more packets */ int code = tr.readUINT32(); String msg = tr.readString(); if(log.isEnabled()) { String[] desc = ErrorCodes.getDescription(code); log.log("Got SSH_FXP_STATUS (" + req.req_id + ") (" + ((desc != null) ? desc[0] : "UNKNOWN") + ")"); } // Flag to read all pending requests but don't send any more. errorOccured = true; if(pendingQueue.isEmpty()) { if(ErrorCodes.SSH_FX_EOF == code) { return -1; } throw new SFTPException(msg, code); } } else if(type == Packet.SSH_FXP_DATA) { /* OK, collect data */ int readLen = tr.readUINT32(); if((readLen < 0) || (readLen > req.len)) { throw new IOException("The server sent an invalid length field in a SSH_FXP_DATA packet."); } if(log.isEnabled()) { log.log("Got SSH_FXP_DATA (" + req.req_id + ") " + req.serverOffset + "/" + readLen + " (requested: " + req.len + ")"); } // Read bytes into buffer tr.readBytes(req.buffer, req.offset, readLen); if(readLen < req.len) { /* Send this request packet again to request the remaing data in this slot. */ req.req_id = generateNextRequestID(); req.serverOffset += readLen; req.clientOffset += readLen; req.len -= readLen; log.log("Requesting again: " + req.serverOffset + "/" + req.len); sendReadRequest(req.req_id, handle, req.serverOffset, req.len); pendingQueue.put(req.req_id, req); } return readLen; } else { throw new IOException("The SFTP server sent an unexpected packet type (" + type + ")"); } } // Should never reach here. throw new SFTPException("No EOF reached", -1); }
diff --git a/java/src/main/java/com/flexpoker/bso/DeckBsoImpl.java b/java/src/main/java/com/flexpoker/bso/DeckBsoImpl.java index fd16fc4a..81c68130 100644 --- a/java/src/main/java/com/flexpoker/bso/DeckBsoImpl.java +++ b/java/src/main/java/com/flexpoker/bso/DeckBsoImpl.java @@ -1,131 +1,131 @@ package com.flexpoker.bso; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import org.springframework.stereotype.Service; import com.flexpoker.model.Card; import com.flexpoker.model.CardRank; import com.flexpoker.model.CardSuit; import com.flexpoker.model.Deck; import com.flexpoker.model.FlopCards; import com.flexpoker.model.Game; import com.flexpoker.model.PocketCards; import com.flexpoker.model.RiverCard; import com.flexpoker.model.Table; import com.flexpoker.model.TurnCard; import com.flexpoker.model.User; import edu.emory.mathcs.backport.java.util.Arrays; @Service("deckBso") public class DeckBsoImpl implements DeckBso { private Map<Game, Map<Table, Deck>> gameToTableToDeckMap = new HashMap<Game, Map<Table,Deck>>(); private final List<Card> cardList; @SuppressWarnings("unchecked") public DeckBsoImpl() { cardList = Arrays.asList(new Card[]{ new Card(0, CardRank.TWO, CardSuit.HEARTS), new Card(1, CardRank.THREE, CardSuit.HEARTS), new Card(2, CardRank.FOUR, CardSuit.HEARTS), new Card(3, CardRank.FIVE, CardSuit.HEARTS), new Card(4, CardRank.SIX, CardSuit.HEARTS), new Card(5, CardRank.SEVEN, CardSuit.HEARTS), new Card(6, CardRank.EIGHT, CardSuit.HEARTS), new Card(7, CardRank.NINE, CardSuit.HEARTS), new Card(8, CardRank.TEN, CardSuit.HEARTS), new Card(9, CardRank.JACK, CardSuit.HEARTS), new Card(10, CardRank.QUEEN, CardSuit.HEARTS), new Card(11, CardRank.KING, CardSuit.HEARTS), new Card(12, CardRank.ACE, CardSuit.HEARTS), new Card(13, CardRank.TWO, CardSuit.SPADES), new Card(14, CardRank.THREE, CardSuit.SPADES), new Card(15, CardRank.FOUR, CardSuit.SPADES), new Card(16, CardRank.FIVE, CardSuit.SPADES), new Card(17, CardRank.SIX, CardSuit.SPADES), new Card(18, CardRank.SEVEN, CardSuit.SPADES), new Card(19, CardRank.EIGHT, CardSuit.SPADES), new Card(20, CardRank.NINE, CardSuit.SPADES), new Card(21, CardRank.TEN, CardSuit.SPADES), new Card(22, CardRank.JACK, CardSuit.SPADES), new Card(23, CardRank.QUEEN, CardSuit.SPADES), new Card(24, CardRank.KING, CardSuit.SPADES), new Card(25, CardRank.ACE, CardSuit.SPADES), new Card(26, CardRank.TWO, CardSuit.DIAMONDS), new Card(27, CardRank.THREE, CardSuit.DIAMONDS), new Card(28, CardRank.FOUR, CardSuit.DIAMONDS), - new Card(28, CardRank.FIVE, CardSuit.DIAMONDS), + new Card(29, CardRank.FIVE, CardSuit.DIAMONDS), new Card(30, CardRank.SIX, CardSuit.DIAMONDS), new Card(31, CardRank.SEVEN, CardSuit.DIAMONDS), new Card(32, CardRank.EIGHT, CardSuit.DIAMONDS), new Card(33, CardRank.NINE, CardSuit.DIAMONDS), new Card(34, CardRank.TEN, CardSuit.DIAMONDS), new Card(35, CardRank.JACK, CardSuit.DIAMONDS), new Card(36, CardRank.QUEEN, CardSuit.DIAMONDS), new Card(37, CardRank.KING, CardSuit.DIAMONDS), new Card(38, CardRank.ACE, CardSuit.DIAMONDS), new Card(39, CardRank.TWO, CardSuit.CLUBS), new Card(40, CardRank.THREE, CardSuit.CLUBS), new Card(41, CardRank.FOUR, CardSuit.CLUBS), new Card(42, CardRank.FIVE, CardSuit.CLUBS), new Card(43, CardRank.SIX, CardSuit.CLUBS), new Card(44, CardRank.SEVEN, CardSuit.CLUBS), new Card(45, CardRank.EIGHT, CardSuit.CLUBS), new Card(46, CardRank.NINE, CardSuit.CLUBS), new Card(47, CardRank.TEN, CardSuit.CLUBS), new Card(48, CardRank.JACK, CardSuit.CLUBS), new Card(49, CardRank.QUEEN, CardSuit.CLUBS), new Card(50, CardRank.KING, CardSuit.CLUBS), new Card(51, CardRank.ACE, CardSuit.CLUBS) }); } @Override public void shuffleDeck(Game game, Table table) { synchronized (gameToTableToDeckMap) { Collections.shuffle(cardList, new Random()); Deck deck = new Deck(cardList, table); if (gameToTableToDeckMap.get(game) == null) { gameToTableToDeckMap.put(game, new HashMap<Table, Deck>()); } gameToTableToDeckMap.get(game).put(table, deck); } } @Override public void removeDeck(Game game, Table table) { synchronized (gameToTableToDeckMap) { gameToTableToDeckMap.get(game).remove(table); } } @Override public FlopCards fetchFlopCards(Game game, Table table) { return gameToTableToDeckMap.get(game).get(table).getFlopCards(); } @Override public PocketCards fetchPocketCards(User user, Game game, Table table) { return gameToTableToDeckMap.get(game).get(table).getPocketCards(user); } @Override public RiverCard fetchRiverCard(Game game, Table table) { return gameToTableToDeckMap.get(game).get(table).getRiverCard(); } @Override public TurnCard fetchTurnCard(Game game, Table table) { return gameToTableToDeckMap.get(game).get(table).getTurnCard(); } }
true
true
public DeckBsoImpl() { cardList = Arrays.asList(new Card[]{ new Card(0, CardRank.TWO, CardSuit.HEARTS), new Card(1, CardRank.THREE, CardSuit.HEARTS), new Card(2, CardRank.FOUR, CardSuit.HEARTS), new Card(3, CardRank.FIVE, CardSuit.HEARTS), new Card(4, CardRank.SIX, CardSuit.HEARTS), new Card(5, CardRank.SEVEN, CardSuit.HEARTS), new Card(6, CardRank.EIGHT, CardSuit.HEARTS), new Card(7, CardRank.NINE, CardSuit.HEARTS), new Card(8, CardRank.TEN, CardSuit.HEARTS), new Card(9, CardRank.JACK, CardSuit.HEARTS), new Card(10, CardRank.QUEEN, CardSuit.HEARTS), new Card(11, CardRank.KING, CardSuit.HEARTS), new Card(12, CardRank.ACE, CardSuit.HEARTS), new Card(13, CardRank.TWO, CardSuit.SPADES), new Card(14, CardRank.THREE, CardSuit.SPADES), new Card(15, CardRank.FOUR, CardSuit.SPADES), new Card(16, CardRank.FIVE, CardSuit.SPADES), new Card(17, CardRank.SIX, CardSuit.SPADES), new Card(18, CardRank.SEVEN, CardSuit.SPADES), new Card(19, CardRank.EIGHT, CardSuit.SPADES), new Card(20, CardRank.NINE, CardSuit.SPADES), new Card(21, CardRank.TEN, CardSuit.SPADES), new Card(22, CardRank.JACK, CardSuit.SPADES), new Card(23, CardRank.QUEEN, CardSuit.SPADES), new Card(24, CardRank.KING, CardSuit.SPADES), new Card(25, CardRank.ACE, CardSuit.SPADES), new Card(26, CardRank.TWO, CardSuit.DIAMONDS), new Card(27, CardRank.THREE, CardSuit.DIAMONDS), new Card(28, CardRank.FOUR, CardSuit.DIAMONDS), new Card(28, CardRank.FIVE, CardSuit.DIAMONDS), new Card(30, CardRank.SIX, CardSuit.DIAMONDS), new Card(31, CardRank.SEVEN, CardSuit.DIAMONDS), new Card(32, CardRank.EIGHT, CardSuit.DIAMONDS), new Card(33, CardRank.NINE, CardSuit.DIAMONDS), new Card(34, CardRank.TEN, CardSuit.DIAMONDS), new Card(35, CardRank.JACK, CardSuit.DIAMONDS), new Card(36, CardRank.QUEEN, CardSuit.DIAMONDS), new Card(37, CardRank.KING, CardSuit.DIAMONDS), new Card(38, CardRank.ACE, CardSuit.DIAMONDS), new Card(39, CardRank.TWO, CardSuit.CLUBS), new Card(40, CardRank.THREE, CardSuit.CLUBS), new Card(41, CardRank.FOUR, CardSuit.CLUBS), new Card(42, CardRank.FIVE, CardSuit.CLUBS), new Card(43, CardRank.SIX, CardSuit.CLUBS), new Card(44, CardRank.SEVEN, CardSuit.CLUBS), new Card(45, CardRank.EIGHT, CardSuit.CLUBS), new Card(46, CardRank.NINE, CardSuit.CLUBS), new Card(47, CardRank.TEN, CardSuit.CLUBS), new Card(48, CardRank.JACK, CardSuit.CLUBS), new Card(49, CardRank.QUEEN, CardSuit.CLUBS), new Card(50, CardRank.KING, CardSuit.CLUBS), new Card(51, CardRank.ACE, CardSuit.CLUBS) }); }
public DeckBsoImpl() { cardList = Arrays.asList(new Card[]{ new Card(0, CardRank.TWO, CardSuit.HEARTS), new Card(1, CardRank.THREE, CardSuit.HEARTS), new Card(2, CardRank.FOUR, CardSuit.HEARTS), new Card(3, CardRank.FIVE, CardSuit.HEARTS), new Card(4, CardRank.SIX, CardSuit.HEARTS), new Card(5, CardRank.SEVEN, CardSuit.HEARTS), new Card(6, CardRank.EIGHT, CardSuit.HEARTS), new Card(7, CardRank.NINE, CardSuit.HEARTS), new Card(8, CardRank.TEN, CardSuit.HEARTS), new Card(9, CardRank.JACK, CardSuit.HEARTS), new Card(10, CardRank.QUEEN, CardSuit.HEARTS), new Card(11, CardRank.KING, CardSuit.HEARTS), new Card(12, CardRank.ACE, CardSuit.HEARTS), new Card(13, CardRank.TWO, CardSuit.SPADES), new Card(14, CardRank.THREE, CardSuit.SPADES), new Card(15, CardRank.FOUR, CardSuit.SPADES), new Card(16, CardRank.FIVE, CardSuit.SPADES), new Card(17, CardRank.SIX, CardSuit.SPADES), new Card(18, CardRank.SEVEN, CardSuit.SPADES), new Card(19, CardRank.EIGHT, CardSuit.SPADES), new Card(20, CardRank.NINE, CardSuit.SPADES), new Card(21, CardRank.TEN, CardSuit.SPADES), new Card(22, CardRank.JACK, CardSuit.SPADES), new Card(23, CardRank.QUEEN, CardSuit.SPADES), new Card(24, CardRank.KING, CardSuit.SPADES), new Card(25, CardRank.ACE, CardSuit.SPADES), new Card(26, CardRank.TWO, CardSuit.DIAMONDS), new Card(27, CardRank.THREE, CardSuit.DIAMONDS), new Card(28, CardRank.FOUR, CardSuit.DIAMONDS), new Card(29, CardRank.FIVE, CardSuit.DIAMONDS), new Card(30, CardRank.SIX, CardSuit.DIAMONDS), new Card(31, CardRank.SEVEN, CardSuit.DIAMONDS), new Card(32, CardRank.EIGHT, CardSuit.DIAMONDS), new Card(33, CardRank.NINE, CardSuit.DIAMONDS), new Card(34, CardRank.TEN, CardSuit.DIAMONDS), new Card(35, CardRank.JACK, CardSuit.DIAMONDS), new Card(36, CardRank.QUEEN, CardSuit.DIAMONDS), new Card(37, CardRank.KING, CardSuit.DIAMONDS), new Card(38, CardRank.ACE, CardSuit.DIAMONDS), new Card(39, CardRank.TWO, CardSuit.CLUBS), new Card(40, CardRank.THREE, CardSuit.CLUBS), new Card(41, CardRank.FOUR, CardSuit.CLUBS), new Card(42, CardRank.FIVE, CardSuit.CLUBS), new Card(43, CardRank.SIX, CardSuit.CLUBS), new Card(44, CardRank.SEVEN, CardSuit.CLUBS), new Card(45, CardRank.EIGHT, CardSuit.CLUBS), new Card(46, CardRank.NINE, CardSuit.CLUBS), new Card(47, CardRank.TEN, CardSuit.CLUBS), new Card(48, CardRank.JACK, CardSuit.CLUBS), new Card(49, CardRank.QUEEN, CardSuit.CLUBS), new Card(50, CardRank.KING, CardSuit.CLUBS), new Card(51, CardRank.ACE, CardSuit.CLUBS) }); }
diff --git a/src/com/stumbleupon/hbaseadmin/HBaseCompact.java b/src/com/stumbleupon/hbaseadmin/HBaseCompact.java index f1d4946..daae06b 100644 --- a/src/com/stumbleupon/hbaseadmin/HBaseCompact.java +++ b/src/com/stumbleupon/hbaseadmin/HBaseCompact.java @@ -1,228 +1,228 @@ /** * This file is part of hbaseadmin. * Copyright (C) 2011 StumbleUpon, Inc. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. This program is distributed in the hope that it * will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. You should have received a copy * of the GNU Lesser General Public License along with this program. If not, * see <http: *www.gnu.org/licenses/>. */ package com.stumbleupon.hbaseadmin; import java.util.Set; import java.util.List; import java.util.HashMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.ipc.RemoteException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.stringparsers.DateStringParser; import com.martiansoftware.jsap.stringparsers.DoubleStringParser; import com.martiansoftware.jsap.JSAPResult; /** * Handles offline HBase compactions - runs compactions between * pre-set times. */ public class HBaseCompact { private final static Logger log = LoggerFactory.getLogger(HBaseCompact.class); //Initialize the HBase config. private static int throttle_factor; private static int num_cycles; private static int sleep_between_compacts; private static int sleep_between_checks; private static HBaseAdmin admin; private static JSAPResult config; /** * cycles through all the servers and compacts regions. We process one * region on each server, delete it from the region list, compact it, move * on to the next server and so on. Once we are done with a server sweep * across all of them, we start over and repeat utill we are done with the * regions. */ private static void compactAllServers(int throttleFactor) throws Exception { Set<String> server_set = ClusterUtils.getServers(); String startHHmm = Utils.dateString(config.getDate("start_time"), "HHmm"); String stopHHmm = Utils.dateString(config.getDate("end_time"), "HHmm"); while (!server_set.isEmpty()) { HRegionInfo region = null; try { Double skip_factor = config.getDouble("skip_factor"); for (final String hostport: server_set) { if (skip_factor <= Math.random()) { region = ClusterUtils.getNextRegion(hostport, throttleFactor); Utils.waitTillTime(startHHmm, stopHHmm, sleep_between_checks); try { if (region != null) { log.info("Compacting: " + region.getRegionNameAsString() + " on server " + hostport); admin.majorCompact(region.getRegionName()); } } catch (TableNotFoundException ex) { log.warn("Could not compact: " + ex); } } else { log.info("Skipping compactions on " + hostport + " because it's not in the cards this time."); } } Thread.sleep(sleep_between_compacts); server_set = ClusterUtils.getServers(); } catch (RemoteException ex) { log.warn("Failed compaction for: " + region + ", Exception thrown: " + ex); } } } /** * command line parsing, this will most likely be replaced by fetching * these values from some property file, instead of from the command line. * This is purely for the stand-alone version. */ private static JSAP prepCmdLineParser() throws Exception { final JSAP jsap = new JSAP(); final FlaggedOption site_xml = new FlaggedOption("hbase_site") .setStringParser(JSAP.STRING_PARSER) .setDefault("") .setRequired(true) .setShortFlag('c') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Path to hbase-site.xml."); jsap.registerParameter(site_xml); final FlaggedOption throttle_factor = new FlaggedOption("throttle_factor") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('t') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Throttle factor to limit the compaction queue. The default (1) limits it to num threads / 1"); + throttle_factor.setHelp("Throttle factor to limit the compaction queue. The default (1) limits it to num threads / 1"); jsap.registerParameter(throttle_factor); final FlaggedOption num_cycles = new FlaggedOption("num_cycles") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('n') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Number of iterations to run. The default is 1. Set to 0 to run forever."); + num_cycles.setHelp("Number of iterations to run. The default is 1. Set to 0 to run forever."); jsap.registerParameter(num_cycles); DoubleStringParser double_parser = DoubleStringParser.getParser(); final FlaggedOption skip_factor = new FlaggedOption("skip_factor") .setStringParser(double_parser) .setDefault("0.0") .setRequired(false) .setShortFlag('f') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Probability that the server is skipped during this compaction cycle. The default is 0 (always compact regions on the server)."); + skip_factor.setHelp("Probability that the server is skipped during this compaction cycle. The default is 0 (always compact regions on the server)."); jsap.registerParameter(skip_factor); final FlaggedOption pause_interval = new FlaggedOption("pause_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("30000") .setRequired(false) .setShortFlag('p') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Time (in milliseconds) to pause between compactions."); + pause_interval.setHelp("Time (in milliseconds) to pause between compactions."); jsap.registerParameter(pause_interval); final FlaggedOption wait_interval = new FlaggedOption("wait_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("60000") .setRequired(false) .setShortFlag('w') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Time (in milliseconds) to wait between " + + wait_interval.setHelp("Time (in milliseconds) to wait between " + "time (are we there yet?) checks."); jsap.registerParameter(wait_interval); DateStringParser date_parser = DateStringParser.getParser(); date_parser.setProperty("format", "HH:mm"); final FlaggedOption start_time = new FlaggedOption("start_time") .setStringParser(date_parser) .setDefault("01:00") .setRequired(true) .setShortFlag('s') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Time to start compactions."); + start_time.setHelp("Time to start compactions."); jsap.registerParameter(start_time); final FlaggedOption end_time = new FlaggedOption("end_time") .setStringParser(date_parser) .setDefault("07:00") .setRequired(true) .setShortFlag('e') .setLongFlag(JSAP.NO_LONGFLAG); - site_xml.setHelp("Time to stop compactions."); + end_time.setHelp("Time to stop compactions."); jsap.registerParameter(end_time); return jsap; } public static void main(String[] args) throws Exception { //parse command line args final JSAP jsap = prepCmdLineParser(); final Configuration hbase_conf = HBaseConfiguration.create(); int iteration = 0; config = jsap.parse(args); if (!config.success()) { System.err.println("Usage: java " + HBaseCompact.class.getName() + " " + jsap.getUsage()); } hbase_conf.addResource(new Path(config.getString("hbase_site"))); sleep_between_compacts = config.getInt("pause_interval"); sleep_between_checks = config.getInt("wait_interval"); throttle_factor = config.getInt("throttle_factor"); num_cycles = config.getInt("num_cycles"); admin = new HBaseAdmin(hbase_conf); final String startHHmm = Utils.dateString(config.getDate("start_time"), "HHmm"); final String stopHHmm = Utils.dateString(config.getDate("end_time"), "HHmm"); if (num_cycles == 0) iteration = -1; while (iteration < num_cycles) { Utils.waitTillTime(startHHmm, stopHHmm, sleep_between_checks); ClusterUtils.updateStatus(admin); compactAllServers(throttle_factor); if (num_cycles > 0) ++iteration; } } }
false
true
private static JSAP prepCmdLineParser() throws Exception { final JSAP jsap = new JSAP(); final FlaggedOption site_xml = new FlaggedOption("hbase_site") .setStringParser(JSAP.STRING_PARSER) .setDefault("") .setRequired(true) .setShortFlag('c') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Path to hbase-site.xml."); jsap.registerParameter(site_xml); final FlaggedOption throttle_factor = new FlaggedOption("throttle_factor") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('t') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Throttle factor to limit the compaction queue. The default (1) limits it to num threads / 1"); jsap.registerParameter(throttle_factor); final FlaggedOption num_cycles = new FlaggedOption("num_cycles") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('n') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Number of iterations to run. The default is 1. Set to 0 to run forever."); jsap.registerParameter(num_cycles); DoubleStringParser double_parser = DoubleStringParser.getParser(); final FlaggedOption skip_factor = new FlaggedOption("skip_factor") .setStringParser(double_parser) .setDefault("0.0") .setRequired(false) .setShortFlag('f') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Probability that the server is skipped during this compaction cycle. The default is 0 (always compact regions on the server)."); jsap.registerParameter(skip_factor); final FlaggedOption pause_interval = new FlaggedOption("pause_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("30000") .setRequired(false) .setShortFlag('p') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Time (in milliseconds) to pause between compactions."); jsap.registerParameter(pause_interval); final FlaggedOption wait_interval = new FlaggedOption("wait_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("60000") .setRequired(false) .setShortFlag('w') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Time (in milliseconds) to wait between " + "time (are we there yet?) checks."); jsap.registerParameter(wait_interval); DateStringParser date_parser = DateStringParser.getParser(); date_parser.setProperty("format", "HH:mm"); final FlaggedOption start_time = new FlaggedOption("start_time") .setStringParser(date_parser) .setDefault("01:00") .setRequired(true) .setShortFlag('s') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Time to start compactions."); jsap.registerParameter(start_time); final FlaggedOption end_time = new FlaggedOption("end_time") .setStringParser(date_parser) .setDefault("07:00") .setRequired(true) .setShortFlag('e') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Time to stop compactions."); jsap.registerParameter(end_time); return jsap; }
private static JSAP prepCmdLineParser() throws Exception { final JSAP jsap = new JSAP(); final FlaggedOption site_xml = new FlaggedOption("hbase_site") .setStringParser(JSAP.STRING_PARSER) .setDefault("") .setRequired(true) .setShortFlag('c') .setLongFlag(JSAP.NO_LONGFLAG); site_xml.setHelp("Path to hbase-site.xml."); jsap.registerParameter(site_xml); final FlaggedOption throttle_factor = new FlaggedOption("throttle_factor") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('t') .setLongFlag(JSAP.NO_LONGFLAG); throttle_factor.setHelp("Throttle factor to limit the compaction queue. The default (1) limits it to num threads / 1"); jsap.registerParameter(throttle_factor); final FlaggedOption num_cycles = new FlaggedOption("num_cycles") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("1") .setRequired(false) .setShortFlag('n') .setLongFlag(JSAP.NO_LONGFLAG); num_cycles.setHelp("Number of iterations to run. The default is 1. Set to 0 to run forever."); jsap.registerParameter(num_cycles); DoubleStringParser double_parser = DoubleStringParser.getParser(); final FlaggedOption skip_factor = new FlaggedOption("skip_factor") .setStringParser(double_parser) .setDefault("0.0") .setRequired(false) .setShortFlag('f') .setLongFlag(JSAP.NO_LONGFLAG); skip_factor.setHelp("Probability that the server is skipped during this compaction cycle. The default is 0 (always compact regions on the server)."); jsap.registerParameter(skip_factor); final FlaggedOption pause_interval = new FlaggedOption("pause_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("30000") .setRequired(false) .setShortFlag('p') .setLongFlag(JSAP.NO_LONGFLAG); pause_interval.setHelp("Time (in milliseconds) to pause between compactions."); jsap.registerParameter(pause_interval); final FlaggedOption wait_interval = new FlaggedOption("wait_interval") .setStringParser(JSAP.INTEGER_PARSER) .setDefault("60000") .setRequired(false) .setShortFlag('w') .setLongFlag(JSAP.NO_LONGFLAG); wait_interval.setHelp("Time (in milliseconds) to wait between " + "time (are we there yet?) checks."); jsap.registerParameter(wait_interval); DateStringParser date_parser = DateStringParser.getParser(); date_parser.setProperty("format", "HH:mm"); final FlaggedOption start_time = new FlaggedOption("start_time") .setStringParser(date_parser) .setDefault("01:00") .setRequired(true) .setShortFlag('s') .setLongFlag(JSAP.NO_LONGFLAG); start_time.setHelp("Time to start compactions."); jsap.registerParameter(start_time); final FlaggedOption end_time = new FlaggedOption("end_time") .setStringParser(date_parser) .setDefault("07:00") .setRequired(true) .setShortFlag('e') .setLongFlag(JSAP.NO_LONGFLAG); end_time.setHelp("Time to stop compactions."); jsap.registerParameter(end_time); return jsap; }
diff --git a/src/main/java/com/hydrasmp/godPowers/MaimCommand.java b/src/main/java/com/hydrasmp/godPowers/MaimCommand.java index f01bf88..8addc1a 100755 --- a/src/main/java/com/hydrasmp/godPowers/MaimCommand.java +++ b/src/main/java/com/hydrasmp/godPowers/MaimCommand.java @@ -1,48 +1,48 @@ package com.hydrasmp.godPowers; //import org.bukkit.World; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class MaimCommand implements CommandExecutor { private Player player; private final godPowers plugin; public MaimCommand(godPowers instance) { plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String[] split = args; if (sender instanceof Player) { player = (Player) sender; if (player.hasPermission("godpowers.maim")) { if (split.length == 1) { Player targetPlayer = plugin.getServer().getPlayer(split[0]); if (targetPlayer == null) { player.sendMessage(ChatColor.RED + "The user " + split[0] + " does not exist or is not currently logged in."); } else if (plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot maim a god!"); } else { targetPlayer.setHealth(2); - player.sendMessage(ChatColor.BLUE + "You viciously beat " + targetPlayer.getName() + " within an inch of thier life."); + player.sendMessage(ChatColor.BLUE + "You viciously beat " + targetPlayer.getName() + " within an inch of their life."); targetPlayer.sendMessage(ChatColor.BLUE + player.getName() + " has beaten you within an inch of your life!"); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/maim [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String[] split = args; if (sender instanceof Player) { player = (Player) sender; if (player.hasPermission("godpowers.maim")) { if (split.length == 1) { Player targetPlayer = plugin.getServer().getPlayer(split[0]); if (targetPlayer == null) { player.sendMessage(ChatColor.RED + "The user " + split[0] + " does not exist or is not currently logged in."); } else if (plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot maim a god!"); } else { targetPlayer.setHealth(2); player.sendMessage(ChatColor.BLUE + "You viciously beat " + targetPlayer.getName() + " within an inch of thier life."); targetPlayer.sendMessage(ChatColor.BLUE + player.getName() + " has beaten you within an inch of your life!"); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/maim [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String[] split = args; if (sender instanceof Player) { player = (Player) sender; if (player.hasPermission("godpowers.maim")) { if (split.length == 1) { Player targetPlayer = plugin.getServer().getPlayer(split[0]); if (targetPlayer == null) { player.sendMessage(ChatColor.RED + "The user " + split[0] + " does not exist or is not currently logged in."); } else if (plugin.godmodeEnabled.contains(targetPlayer.getName())) { player.sendMessage(ChatColor.RED + "Fool! You cannot maim a god!"); } else { targetPlayer.setHealth(2); player.sendMessage(ChatColor.BLUE + "You viciously beat " + targetPlayer.getName() + " within an inch of their life."); targetPlayer.sendMessage(ChatColor.BLUE + player.getName() + " has beaten you within an inch of your life!"); } return true; } else { player.sendMessage(ChatColor.RED + "Incorrect syntax, use '/maim [playerName]'"); return true; } } else { player.sendMessage(ChatColor.DARK_RED + "The gods prevent you from using this command."); return true; } } return false; }
diff --git a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HTMLParser.java b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HTMLParser.java index 6fa76e0d4..6f2644489 100644 --- a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HTMLParser.java +++ b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HTMLParser.java @@ -1,407 +1,407 @@ /* * Copyright (c) 2002, 2004 Gargoyle Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: * * "This product includes software developed by Gargoyle Software Inc. * (http://www.GargoyleSoftware.com/)." * * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * 4. The name "Gargoyle Software" must not be used to endorse or promote * products derived from this software without prior written permission. * For written permission, please contact [email protected]. * 5. Products derived from this software may not be called "HtmlUnit", nor may * "HtmlUnit" appear in their name, without prior written permission of * Gargoyle Software Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE * SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.gargoylesoftware.htmlunit.html; import org.apache.xerces.parsers.AbstractSAXParser; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.cyberneko.html.HTMLConfiguration; import org.xml.sax.SAXException; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.Attributes; import java.util.Stack; import java.util.Map; import java.util.HashMap; import java.io.IOException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.WebWindow; import com.gargoylesoftware.htmlunit.ScriptFilter; import com.gargoylesoftware.htmlunit.ObjectInstantiationException; /** * SAX parser implementation that uses the neko {@link org.cyberneko.html.HTMLConfiguration} * to parse HTML into a HtmlUnit-specific DOM (HU-DOM) tree. * <p> * <em>Note that the parser currently does not handle CDATA or comment sections, i.e. these * do not appear in the resulting DOM tree</em> * * @version $Revision$ * @author <a href="mailto:[email protected]">Christian Sell</a> * @author David K. Taylor */ public class HTMLParser { private static final Map ELEMENT_FACTORIES = new HashMap(); static { ELEMENT_FACTORIES.put("input", InputElementFactory.instance); putFactory( HtmlAnchor.TAG_NAME, HtmlAnchor.class); putFactory( HtmlApplet.TAG_NAME, HtmlApplet.class); putFactory( HtmlAddress.TAG_NAME, HtmlAddress.class); putFactory( HtmlArea.TAG_NAME, HtmlArea.class); putFactory( HtmlBase.TAG_NAME, HtmlBase.class); putFactory( HtmlBaseFont.TAG_NAME, HtmlBaseFont.class); putFactory( HtmlBidirectionalOverride.TAG_NAME, HtmlBidirectionalOverride.class); putFactory( HtmlBlockQuote.TAG_NAME, HtmlBlockQuote.class); putFactory( HtmlBody.TAG_NAME, HtmlBody.class); putFactory( HtmlBreak.TAG_NAME, HtmlBreak.class); putFactory( HtmlButton.TAG_NAME, HtmlButton.class); putFactory( HtmlCaption.TAG_NAME, HtmlCaption.class); putFactory( HtmlCenter.TAG_NAME, HtmlCenter.class); putFactory( HtmlTableColumn.TAG_NAME, HtmlTableColumn.class); putFactory( HtmlTableColumnGroup.TAG_NAME, HtmlTableColumnGroup.class); putFactory( HtmlDefinitionDescription.TAG_NAME, HtmlDefinitionDescription.class); putFactory( HtmlDeletedText.TAG_NAME, HtmlDeletedText.class); putFactory( HtmlTextDirection.TAG_NAME, HtmlTextDirection.class); putFactory( HtmlDivision.TAG_NAME, HtmlDivision.class); putFactory( HtmlDefinitionList.TAG_NAME, HtmlDefinitionList.class); putFactory( HtmlDefinitionTerm.TAG_NAME, HtmlDefinitionTerm.class); putFactory( HtmlFieldSet.TAG_NAME, HtmlFieldSet.class); putFactory( HtmlFont.TAG_NAME, HtmlFont.class); putFactory( HtmlForm.TAG_NAME, HtmlForm.class); putFactory( HtmlFrame.TAG_NAME, HtmlFrame.class); putFactory( HtmlFrameSet.TAG_NAME, HtmlFrameSet.class); putFactory( HtmlHeader1.TAG_NAME, HtmlHeader1.class); putFactory( HtmlHeader2.TAG_NAME, HtmlHeader2.class); putFactory( HtmlHeader3.TAG_NAME, HtmlHeader3.class); putFactory( HtmlHeader4.TAG_NAME, HtmlHeader4.class); putFactory( HtmlHeader5.TAG_NAME, HtmlHeader5.class); putFactory( HtmlHeader6.TAG_NAME, HtmlHeader6.class); putFactory( HtmlHead.TAG_NAME, HtmlHead.class); putFactory( HtmlHorizontalRule.TAG_NAME, HtmlHorizontalRule.class); putFactory( HtmlHtml.TAG_NAME, HtmlHtml.class); putFactory( HtmlInlineFrame.TAG_NAME, HtmlInlineFrame.class); putFactory( HtmlImage.TAG_NAME, HtmlImage.class); putFactory( HtmlInsertedText.TAG_NAME, HtmlInsertedText.class); putFactory( HtmlIsIndex.TAG_NAME, HtmlIsIndex.class); putFactory( HtmlLabel.TAG_NAME, HtmlLabel.class); putFactory( HtmlLegend.TAG_NAME, HtmlLegend.class); putFactory( HtmlListItem.TAG_NAME, HtmlListItem.class); putFactory( HtmlLink.TAG_NAME, HtmlLink.class); putFactory( HtmlMap.TAG_NAME, HtmlMap.class); putFactory( HtmlMenu.TAG_NAME, HtmlMenu.class); putFactory( HtmlMeta.TAG_NAME, HtmlMeta.class); putFactory( HtmlNoFrames.TAG_NAME, HtmlNoFrames.class); putFactory( HtmlNoScript.TAG_NAME, HtmlNoScript.class); putFactory( HtmlObject.TAG_NAME, HtmlObject.class); putFactory( HtmlOrderedList.TAG_NAME, HtmlOrderedList.class); putFactory( HtmlOptionGroup.TAG_NAME, HtmlOptionGroup.class); putFactory( HtmlOption.TAG_NAME, HtmlOption.class); putFactory( HtmlParagraph.TAG_NAME, HtmlParagraph.class); putFactory( HtmlParameter.TAG_NAME, HtmlParameter.class); putFactory( HtmlPreformattedText.TAG_NAME, HtmlPreformattedText.class); putFactory( HtmlInlineQuotation.TAG_NAME, HtmlInlineQuotation.class); putFactory( HtmlScript.TAG_NAME, HtmlScript.class); putFactory( HtmlSelect.TAG_NAME, HtmlSelect.class); putFactory( HtmlSpan.TAG_NAME, HtmlSpan.class); putFactory( HtmlStyle.TAG_NAME, HtmlStyle.class); putFactory( HtmlTitle.TAG_NAME, HtmlTitle.class); putFactory( HtmlTable.TAG_NAME, HtmlTable.class); putFactory( HtmlTableBody.TAG_NAME, HtmlTableBody.class); putFactory( HtmlTableDataCell.TAG_NAME, HtmlTableDataCell.class); putFactory( HtmlTableHeaderCell.TAG_NAME, HtmlTableHeaderCell.class); putFactory( HtmlTableRow.TAG_NAME, HtmlTableRow.class); putFactory( HtmlTextArea.TAG_NAME, HtmlTextArea.class); putFactory( HtmlTableFooter.TAG_NAME, HtmlTableFooter.class); putFactory( HtmlTableHeader.TAG_NAME, HtmlTableHeader.class); putFactory( HtmlUnorderedList.TAG_NAME, HtmlUnorderedList.class); } private static void putFactory(String tagName, Class elementClass) { ELEMENT_FACTORIES.put(tagName, new DefaultElementFactory(elementClass)); } /** * @param tagName an HTML element tag name * @return a factory for creating HtmlElements representing the given tag */ public static IElementFactory getFactory(String tagName) { IElementFactory result = (IElementFactory)ELEMENT_FACTORIES.get(tagName); //return result != null ? result : UnknownElementFactory.instance; if(result != null) { return result; } else { return UnknownElementFactory.instance; } } /** * You should never need to create one of these! * @deprecated */ public HTMLParser() { } /** * This method should no longer be used * * @param webClient NOT USED * @param webResponse the response data * @param webWindow the web window into which the page is to be loaded * @return the page object which forms the root of the DOM tree, or <code>null</code> if the &lt;HTML&gt; * tag is missing * @throws java.io.IOException io error * @deprecated */ public HtmlPage parse( final WebClient webClient, final WebResponse webResponse, final WebWindow webWindow) throws IOException { return parse(webResponse, webWindow); } /** * parse the HTML content from the given WebResponse into an object tree representation * * @param webResponse the response data * @param webWindow the web window into which the page is to be loaded * @return the page object which forms the root of the DOM tree, or <code>null</code> if the &lt;HTML&gt; * tag is missing * @throws java.io.IOException io error */ public static HtmlPage parse(final WebResponse webResponse, final WebWindow webWindow) throws IOException { HtmlUnitDOMBuilder domBuilder = new HtmlUnitDOMBuilder(webResponse, webWindow); XMLInputSource in = new XMLInputSource( null, webResponse.getUrl().toString(), null, webResponse.getContentAsStream(), webResponse.getContentCharSet()); domBuilder.parse(in); return domBuilder.page_; } /** * The parser and DOM builder. This class subclasses Xerces's AbstractSAXParser and implements * the ContentHandler interface. Thus all parser APIs are kept private. The ContentHandler methods * consume SAX events to build the page DOM */ private static class HtmlUnitDOMBuilder extends AbstractSAXParser implements ContentHandler /*, LexicalHandler */ { private final WebResponse webResponse_; private final WebWindow webWindow_; private final ScriptFilter scriptFilter_; private HtmlPage page_; private Locator locator_; private final Stack stack_ = new Stack(); private DomNode currentNode_; private StringBuffer characters_; /** * create a new builder for parsing the given response contents * @param webResponse the response data * @param webWindow the web window into which the page is to be loaded */ public HtmlUnitDOMBuilder(final WebResponse webResponse, final WebWindow webWindow) { super(new HTMLConfiguration()); webResponse_ = webResponse; webWindow_ = webWindow; scriptFilter_ = new ScriptFilter((HTMLConfiguration)fConfiguration); try { XMLDocumentFilter[] filters = {scriptFilter_}; setProperty( "http://cyberneko.org/html/properties/filters", filters); setFeature( "http://cyberneko.org/html/features/augmentations", true ); setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); - setFeature("http://cyberneko.org/html/features/report-errors", true); + setFeature("http://cyberneko.org/html/features/report-errors", false); } catch (SAXException e) { throw new ObjectInstantiationException("unable to create HTML parser", e); } } /** * parse the input source. This is the only parse() method that should be called. * * @param inputSource an XMLInputSource * @throws java.io.IOException */ public void parse(XMLInputSource inputSource) throws IOException { setContentHandler(this); //setLexicalHandler(this); comments and CDATA super.parse(inputSource); } /** * @return the document locator */ public Locator getLocator() { return locator_; } /** * set the document locator * @param locator */ public void setDocumentLocator(Locator locator) { this.locator_ = locator; } /** SAX start document event */ public void startDocument() throws SAXException { page_ = new HtmlPage(webResponse_.getUrl(), webResponse_, webWindow_); page_.setScriptFilter(scriptFilter_); scriptFilter_.setHtmlPage(page_); webWindow_.setEnclosedPage(page_); currentNode_ = page_; stack_.push(currentNode_); } /** SAX start event */ public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { handleCharacters(); final String tagLower = localName.toLowerCase(); IElementFactory factory = getElementFactory(tagLower); HtmlElement newElement = factory.createElement(page_, tagLower, atts); currentNode_.appendChild(newElement); currentNode_ = newElement; stack_.push(currentNode_); } /** SAX end event */ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { handleCharacters(); stack_.pop(); //remove currentElement from stack if(!stack_.isEmpty()) { currentNode_ = (DomNode)stack_.peek(); } } /** SAX characters event */ public void characters(char ch[], int start, int length) throws SAXException { if(characters_ == null) { characters_ = new StringBuffer(); } characters_.append(ch, start, length); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { if(characters_ == null) { characters_ = new StringBuffer(); } characters_.append(ch, start, length); } /** * pick up the chacracter data accumulated so far and add it to the * current element as a text node */ private void handleCharacters() { if(characters_ != null && characters_.length() > 0) { DomText text = new DomText(page_, characters_.toString()); currentNode_.appendChild(text); characters_.setLength(0); } } /** * @param tagName an HTML tag name, in lowercase * @return the pre-registered element factory for the tag, or an UnknownElementFactory */ private IElementFactory getElementFactory(String tagName) { IElementFactory factory = (IElementFactory)ELEMENT_FACTORIES.get(tagName); //return factory != null ? factory : UnknownElementFactory.instance; if(factory != null) { return factory; } else { return UnknownElementFactory.instance; } } /** unused SAX event */ public void endDocument() throws SAXException { } /** unused SAX event */ public void startPrefixMapping(String prefix, String uri) throws SAXException { } /** unused SAX event */ public void endPrefixMapping(String prefix) throws SAXException { } /** unused SAX event */ public void processingInstruction(String target, String data) throws SAXException { } /** unused SAX event */ public void skippedEntity(String name) throws SAXException { } } }
true
true
public HtmlUnitDOMBuilder(final WebResponse webResponse, final WebWindow webWindow) { super(new HTMLConfiguration()); webResponse_ = webResponse; webWindow_ = webWindow; scriptFilter_ = new ScriptFilter((HTMLConfiguration)fConfiguration); try { XMLDocumentFilter[] filters = {scriptFilter_}; setProperty( "http://cyberneko.org/html/properties/filters", filters); setFeature( "http://cyberneko.org/html/features/augmentations", true ); setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); setFeature("http://cyberneko.org/html/features/report-errors", true); } catch (SAXException e) { throw new ObjectInstantiationException("unable to create HTML parser", e); } }
public HtmlUnitDOMBuilder(final WebResponse webResponse, final WebWindow webWindow) { super(new HTMLConfiguration()); webResponse_ = webResponse; webWindow_ = webWindow; scriptFilter_ = new ScriptFilter((HTMLConfiguration)fConfiguration); try { XMLDocumentFilter[] filters = {scriptFilter_}; setProperty( "http://cyberneko.org/html/properties/filters", filters); setFeature( "http://cyberneko.org/html/features/augmentations", true ); setProperty("http://cyberneko.org/html/properties/names/elems", "lower"); setFeature("http://cyberneko.org/html/features/report-errors", false); } catch (SAXException e) { throw new ObjectInstantiationException("unable to create HTML parser", e); } }
diff --git a/MultiROMMgr/src/main/java/com/tassadar/multirommgr/MultiROMInstallTask.java b/MultiROMMgr/src/main/java/com/tassadar/multirommgr/MultiROMInstallTask.java index 87f5c07..3393ac5 100644 --- a/MultiROMMgr/src/main/java/com/tassadar/multirommgr/MultiROMInstallTask.java +++ b/MultiROMMgr/src/main/java/com/tassadar/multirommgr/MultiROMInstallTask.java @@ -1,259 +1,258 @@ /* * This file is part of MultiROM Manager. * * MultiROM Manager 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. * * MultiROM Manager 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 MultiROM Manager. If not, see <http://www.gnu.org/licenses/>. */ package com.tassadar.multirommgr; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import eu.chainfire.libsuperuser.Shell; public class MultiROMInstallTask extends InstallAsyncTask { public MultiROMInstallTask(Manifest man, Device dev) { super(); m_manifest = man; m_dev = dev; } public void setParts(boolean multirom, boolean recovery, String kernel) { m_multirom = multirom; m_recovery = recovery; m_kernel = kernel; } public void setListener(InstallListener listener) { m_listener = listener; } public void setCanceled(boolean canceled) { m_canceled = canceled; } @Override protected Void doInBackground(Void... results) { String dest = Utils.getDownloadDir(); File destDir = new File(dest); destDir.mkdirs(); Log.d("MultiROMInstallTask", "Using download directory: " + dest); ArrayList<Manifest.InstallationFile> files = new ArrayList<Manifest.InstallationFile>(); if(m_recovery) files.add(m_manifest.getRecoveryFile()); if(m_multirom) files.add(m_manifest.getMultiromFile()); if(m_kernel != null) files.add(m_manifest.getKernelFile(m_kernel)); m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.preparing_downloads, "")); m_listener.onInstallLog(Utils.getString(R.string.preparing_downloads, "<br>")); for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); String filename = Utils.getFilenameFromUrl(f.url); if(filename == null || filename.isEmpty()) { m_listener.onInstallLog(Utils.getString(R.string.invalid_url, f.url)); m_listener.onInstallComplete(false); return null; } f.destFile = new File(destDir, filename); if(f.destFile.exists()) { String md5 = Utils.calculateMD5(f.destFile); if(f.md5.equals(md5)) { m_listener.onInstallLog(Utils.getString(R.string.skipping_file, filename)); continue; } } if(!downloadFile(files.get(i).url, f.destFile)) { if(!m_canceled) m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.checking_file, filename)); String md5 = Utils.calculateMD5(f.destFile); if(f.md5.isEmpty() || f.md5.equals(md5)) m_listener.onInstallLog(Utils.getString(R.string.ok)); else { m_listener.onInstallLog(Utils.getString(R.string.failed)); m_listener.onInstallComplete(false); return null; } } m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.installing_files)); m_listener.enableCancel(false); boolean needsRecovery = false; File script = Utils.getCacheOpenRecoveryScript(); if(script.exists()) script.delete(); String cache = mountTmpCache(m_dev.getCacheDev()); if(cache == null) { m_listener.onInstallComplete(false); return null; } for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); m_listener.onInstallLog(Utils.getString(R.string.installing_file, f.destFile.getName())); if(f.type.equals("recovery")) { if(!flashRecovery(f, m_dev)) { m_listener.onInstallComplete(false); return null; } } else if(f.type.equals("multirom") || f.type.equals("kernel")) { needsRecovery = true; if(!addScriptInstall(f, script, cache)) { m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.needs_recovery)); } } unmountTmpCache(cache); if(UpdateChecker.isEnabled()) { String m_ver = null, r_ver = null; if(m_multirom) { - // assume installation completes successfully in recovery, - // if not, it version will be update when the user returns to - // the MainActivity + // Assume installation completes successfully in recovery - if not, + // the version will be updated when the user returns to the MainActivity. m_ver = m_manifest.getMultiromVersion(); } if(m_recovery) { Recovery r = new Recovery(); if(r.findRecoveryVersion(m_dev)) r_ver = r.getVersionString(); } UpdateChecker.lazyUpdateVersions(m_dev, m_ver, r_ver); } if(needsRecovery) m_listener.requestRecovery(false); m_listener.onInstallComplete(true); return null; } private boolean flashRecovery(Manifest.InstallationFile f, Device dev) { String p = Utils.extractAsset("busybox"); if(p == null) { Log.e("InstallAsyncTask", "Failed to extract busybox!"); return false; } File tmprecovery = new File(MultiROMMgrApplication.getAppContext().getCacheDir(), f.destFile.getName()); Utils.copyFile(f.destFile, tmprecovery); String cmd = String.format("$(\"%s\" dd if=\"%s\" of=\"%s\" bs=8192 conv=fsync);" + "if [ \"$?\" = \"0\" ]; then echo success; fi;", p, tmprecovery.getAbsolutePath(), dev.getRecoveryDev()); List<String> out = Shell.SU.run(cmd); tmprecovery.delete(); if(out == null || out.isEmpty() || !out.get(out.size()-1).equals("success")) { m_listener.onInstallLog(Utils.getString(R.string.failed)); return false; } m_listener.onInstallLog(Utils.getString(R.string.success)); return true; } private boolean addScriptInstall(Manifest.InstallationFile f, File scriptFile, String cache) { String bb = Utils.extractAsset("busybox"); File tmpfile = new File(MultiROMMgrApplication.getAppContext().getCacheDir(), f.destFile.getName()); Utils.copyFile(f.destFile, tmpfile); List<String> res = Shell.SU.run("%s cp \"%s\" \"%s/recovery/\" && echo success", bb, tmpfile.getAbsolutePath(), cache); tmpfile.delete(); if(res == null || res.size() != 1 || !res.get(0).equals("success")) { m_listener.onInstallLog("Failed to copy file to cache!"); return false; } FileOutputStream out = null; try { out = new FileOutputStream(scriptFile, true); String line = String.format("install /cache/recovery/%s\n", f.destFile.getName()); out.write(line.getBytes()); line = String.format("cmd rm \"/cache/recovery/%s\"\n", f.destFile.getName()); out.write(line.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { if(out != null) try { out.close(); } catch(IOException e) {} } return true; } private String mountTmpCache(String cacheDev) { String bb = Utils.extractAsset("busybox"); if(bb == null) { Log.e("InstallAsyncTask", "Failed to extract busybox!"); return null; } // We need to mount the real /cache, we might be running in secondary ROM String cmd = "mkdir -p /data/local/tmp/tmpcache; " + "cd /data/local/tmp/; " + bb + " mount -t auto " + cacheDev + " tmpcache && " + "mkdir -p tmpcache/recovery && " + "sync && echo /data/local/tmp/tmpcache"; List<String> out = Shell.SU.run(cmd); if(out == null || out.size() != 1) { m_listener.onInstallLog("Failed to mount /cache!<br>"); return null; } return out.get(0); } private void unmountTmpCache(String path) { Shell.SU.run("umount \"%s\" && rmdir \"%s\"", path, path); } @Override public boolean isCanceled() { return m_canceled; } private boolean m_multirom; private boolean m_recovery; private String m_kernel; private Manifest m_manifest; private Device m_dev; }
true
true
protected Void doInBackground(Void... results) { String dest = Utils.getDownloadDir(); File destDir = new File(dest); destDir.mkdirs(); Log.d("MultiROMInstallTask", "Using download directory: " + dest); ArrayList<Manifest.InstallationFile> files = new ArrayList<Manifest.InstallationFile>(); if(m_recovery) files.add(m_manifest.getRecoveryFile()); if(m_multirom) files.add(m_manifest.getMultiromFile()); if(m_kernel != null) files.add(m_manifest.getKernelFile(m_kernel)); m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.preparing_downloads, "")); m_listener.onInstallLog(Utils.getString(R.string.preparing_downloads, "<br>")); for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); String filename = Utils.getFilenameFromUrl(f.url); if(filename == null || filename.isEmpty()) { m_listener.onInstallLog(Utils.getString(R.string.invalid_url, f.url)); m_listener.onInstallComplete(false); return null; } f.destFile = new File(destDir, filename); if(f.destFile.exists()) { String md5 = Utils.calculateMD5(f.destFile); if(f.md5.equals(md5)) { m_listener.onInstallLog(Utils.getString(R.string.skipping_file, filename)); continue; } } if(!downloadFile(files.get(i).url, f.destFile)) { if(!m_canceled) m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.checking_file, filename)); String md5 = Utils.calculateMD5(f.destFile); if(f.md5.isEmpty() || f.md5.equals(md5)) m_listener.onInstallLog(Utils.getString(R.string.ok)); else { m_listener.onInstallLog(Utils.getString(R.string.failed)); m_listener.onInstallComplete(false); return null; } } m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.installing_files)); m_listener.enableCancel(false); boolean needsRecovery = false; File script = Utils.getCacheOpenRecoveryScript(); if(script.exists()) script.delete(); String cache = mountTmpCache(m_dev.getCacheDev()); if(cache == null) { m_listener.onInstallComplete(false); return null; } for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); m_listener.onInstallLog(Utils.getString(R.string.installing_file, f.destFile.getName())); if(f.type.equals("recovery")) { if(!flashRecovery(f, m_dev)) { m_listener.onInstallComplete(false); return null; } } else if(f.type.equals("multirom") || f.type.equals("kernel")) { needsRecovery = true; if(!addScriptInstall(f, script, cache)) { m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.needs_recovery)); } } unmountTmpCache(cache); if(UpdateChecker.isEnabled()) { String m_ver = null, r_ver = null; if(m_multirom) { // assume installation completes successfully in recovery, // if not, it version will be update when the user returns to // the MainActivity m_ver = m_manifest.getMultiromVersion(); } if(m_recovery) { Recovery r = new Recovery(); if(r.findRecoveryVersion(m_dev)) r_ver = r.getVersionString(); } UpdateChecker.lazyUpdateVersions(m_dev, m_ver, r_ver); } if(needsRecovery) m_listener.requestRecovery(false); m_listener.onInstallComplete(true); return null; }
protected Void doInBackground(Void... results) { String dest = Utils.getDownloadDir(); File destDir = new File(dest); destDir.mkdirs(); Log.d("MultiROMInstallTask", "Using download directory: " + dest); ArrayList<Manifest.InstallationFile> files = new ArrayList<Manifest.InstallationFile>(); if(m_recovery) files.add(m_manifest.getRecoveryFile()); if(m_multirom) files.add(m_manifest.getMultiromFile()); if(m_kernel != null) files.add(m_manifest.getKernelFile(m_kernel)); m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.preparing_downloads, "")); m_listener.onInstallLog(Utils.getString(R.string.preparing_downloads, "<br>")); for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); String filename = Utils.getFilenameFromUrl(f.url); if(filename == null || filename.isEmpty()) { m_listener.onInstallLog(Utils.getString(R.string.invalid_url, f.url)); m_listener.onInstallComplete(false); return null; } f.destFile = new File(destDir, filename); if(f.destFile.exists()) { String md5 = Utils.calculateMD5(f.destFile); if(f.md5.equals(md5)) { m_listener.onInstallLog(Utils.getString(R.string.skipping_file, filename)); continue; } } if(!downloadFile(files.get(i).url, f.destFile)) { if(!m_canceled) m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.checking_file, filename)); String md5 = Utils.calculateMD5(f.destFile); if(f.md5.isEmpty() || f.md5.equals(md5)) m_listener.onInstallLog(Utils.getString(R.string.ok)); else { m_listener.onInstallLog(Utils.getString(R.string.failed)); m_listener.onInstallComplete(false); return null; } } m_listener.onProgressUpdate(0, 0, true, Utils.getString(R.string.installing_files)); m_listener.enableCancel(false); boolean needsRecovery = false; File script = Utils.getCacheOpenRecoveryScript(); if(script.exists()) script.delete(); String cache = mountTmpCache(m_dev.getCacheDev()); if(cache == null) { m_listener.onInstallComplete(false); return null; } for(int i = 0; i < files.size(); ++i) { Manifest.InstallationFile f = files.get(i); m_listener.onInstallLog(Utils.getString(R.string.installing_file, f.destFile.getName())); if(f.type.equals("recovery")) { if(!flashRecovery(f, m_dev)) { m_listener.onInstallComplete(false); return null; } } else if(f.type.equals("multirom") || f.type.equals("kernel")) { needsRecovery = true; if(!addScriptInstall(f, script, cache)) { m_listener.onInstallComplete(false); return null; } m_listener.onInstallLog(Utils.getString(R.string.needs_recovery)); } } unmountTmpCache(cache); if(UpdateChecker.isEnabled()) { String m_ver = null, r_ver = null; if(m_multirom) { // Assume installation completes successfully in recovery - if not, // the version will be updated when the user returns to the MainActivity. m_ver = m_manifest.getMultiromVersion(); } if(m_recovery) { Recovery r = new Recovery(); if(r.findRecoveryVersion(m_dev)) r_ver = r.getVersionString(); } UpdateChecker.lazyUpdateVersions(m_dev, m_ver, r_ver); } if(needsRecovery) m_listener.requestRecovery(false); m_listener.onInstallComplete(true); return null; }
diff --git a/src/cn/edu/tsinghua/academic/c00740273/magictower/standard/FightMixin.java b/src/cn/edu/tsinghua/academic/c00740273/magictower/standard/FightMixin.java index 1567cc8..d0777d4 100644 --- a/src/cn/edu/tsinghua/academic/c00740273/magictower/standard/FightMixin.java +++ b/src/cn/edu/tsinghua/academic/c00740273/magictower/standard/FightMixin.java @@ -1,82 +1,82 @@ package cn.edu.tsinghua.academic.c00740273.magictower.standard; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import cn.edu.tsinghua.academic.c00740273.magictower.engine.Coordinate; public class FightMixin implements RegularTileMixin { private static final long serialVersionUID = 1L; protected String attackAttributeName; protected String defenseAttributeName; protected String healthAttributeName; protected String deathAttributeName; protected long opponentInitialAttack; protected long opponentInitialDefense; protected long opponentInitialHealth; @Override public void initialize(JSONObject dataMixinValue) throws JSONException, DataFormatException { this.attackAttributeName = dataMixinValue.getString("attack-attribute"); this.defenseAttributeName = dataMixinValue .getString("defense-attribute"); this.healthAttributeName = dataMixinValue.getString("health-attribute"); this.deathAttributeName = dataMixinValue.getString("death-attribute"); this.opponentInitialAttack = dataMixinValue.getLong("attack-opponent"); this.opponentInitialDefense = dataMixinValue .getLong("defense-opponent"); this.opponentInitialHealth = dataMixinValue.getLong("health-opponent"); } @Override public boolean enter(StandardEvent event, Coordinate coord, RegularTile tile, Coordinate sourceCoord, CharacterTile sourceTile, StandardGame game) { long opponentAttack = this.opponentInitialAttack; long opponentDefense = this.opponentInitialDefense; long opponentHealth = this.opponentInitialHealth; long selfAttack = ((Number) game.getAttribute(event, this.attackAttributeName)).longValue(); long selfDefense = ((Number) game.getAttribute(event, this.defenseAttributeName)).longValue(); long selfHealth = ((Number) game.getAttribute(event, this.healthAttributeName)).longValue(); Map<String, Long> fightDetails = new HashMap<String, Long>(); fightDetails.put("opponent-attack-before", opponentAttack); fightDetails.put("opponent-defense-before", opponentDefense); fightDetails.put("opponent-health-before", opponentHealth); fightDetails.put("self-attack-before", selfAttack); fightDetails.put("self-defense-before", selfDefense); fightDetails.put("self-health-before", selfHealth); if (selfAttack <= opponentDefense) { fightDetails.put("quick-death", -1L); event.setAttributeChange(this.deathAttributeName, -1L); event.addExtraInformation("fight-details", fightDetails); return true; } else { fightDetails.put("quick-death", 0L); } while (opponentHealth > 0) { opponentHealth -= selfAttack - opponentDefense; - selfHealth -= opponentAttack - selfDefense; + selfHealth -= Math.max(0L, opponentAttack - selfDefense); } event.setAttributeChange(this.attackAttributeName, selfAttack); event.setAttributeChange(this.defenseAttributeName, selfDefense); event.setAttributeChange(this.healthAttributeName, selfHealth); fightDetails.put("opponent-attack-after", opponentAttack); fightDetails.put("opponent-defense-after", opponentDefense); fightDetails.put("opponent-health-after", opponentHealth); fightDetails.put("self-attack-after", selfAttack); fightDetails.put("self-defense-after", selfDefense); fightDetails.put("self-health-after", selfHealth); event.addExtraInformation("fight-details", fightDetails); return true; } }
true
true
public boolean enter(StandardEvent event, Coordinate coord, RegularTile tile, Coordinate sourceCoord, CharacterTile sourceTile, StandardGame game) { long opponentAttack = this.opponentInitialAttack; long opponentDefense = this.opponentInitialDefense; long opponentHealth = this.opponentInitialHealth; long selfAttack = ((Number) game.getAttribute(event, this.attackAttributeName)).longValue(); long selfDefense = ((Number) game.getAttribute(event, this.defenseAttributeName)).longValue(); long selfHealth = ((Number) game.getAttribute(event, this.healthAttributeName)).longValue(); Map<String, Long> fightDetails = new HashMap<String, Long>(); fightDetails.put("opponent-attack-before", opponentAttack); fightDetails.put("opponent-defense-before", opponentDefense); fightDetails.put("opponent-health-before", opponentHealth); fightDetails.put("self-attack-before", selfAttack); fightDetails.put("self-defense-before", selfDefense); fightDetails.put("self-health-before", selfHealth); if (selfAttack <= opponentDefense) { fightDetails.put("quick-death", -1L); event.setAttributeChange(this.deathAttributeName, -1L); event.addExtraInformation("fight-details", fightDetails); return true; } else { fightDetails.put("quick-death", 0L); } while (opponentHealth > 0) { opponentHealth -= selfAttack - opponentDefense; selfHealth -= opponentAttack - selfDefense; } event.setAttributeChange(this.attackAttributeName, selfAttack); event.setAttributeChange(this.defenseAttributeName, selfDefense); event.setAttributeChange(this.healthAttributeName, selfHealth); fightDetails.put("opponent-attack-after", opponentAttack); fightDetails.put("opponent-defense-after", opponentDefense); fightDetails.put("opponent-health-after", opponentHealth); fightDetails.put("self-attack-after", selfAttack); fightDetails.put("self-defense-after", selfDefense); fightDetails.put("self-health-after", selfHealth); event.addExtraInformation("fight-details", fightDetails); return true; }
public boolean enter(StandardEvent event, Coordinate coord, RegularTile tile, Coordinate sourceCoord, CharacterTile sourceTile, StandardGame game) { long opponentAttack = this.opponentInitialAttack; long opponentDefense = this.opponentInitialDefense; long opponentHealth = this.opponentInitialHealth; long selfAttack = ((Number) game.getAttribute(event, this.attackAttributeName)).longValue(); long selfDefense = ((Number) game.getAttribute(event, this.defenseAttributeName)).longValue(); long selfHealth = ((Number) game.getAttribute(event, this.healthAttributeName)).longValue(); Map<String, Long> fightDetails = new HashMap<String, Long>(); fightDetails.put("opponent-attack-before", opponentAttack); fightDetails.put("opponent-defense-before", opponentDefense); fightDetails.put("opponent-health-before", opponentHealth); fightDetails.put("self-attack-before", selfAttack); fightDetails.put("self-defense-before", selfDefense); fightDetails.put("self-health-before", selfHealth); if (selfAttack <= opponentDefense) { fightDetails.put("quick-death", -1L); event.setAttributeChange(this.deathAttributeName, -1L); event.addExtraInformation("fight-details", fightDetails); return true; } else { fightDetails.put("quick-death", 0L); } while (opponentHealth > 0) { opponentHealth -= selfAttack - opponentDefense; selfHealth -= Math.max(0L, opponentAttack - selfDefense); } event.setAttributeChange(this.attackAttributeName, selfAttack); event.setAttributeChange(this.defenseAttributeName, selfDefense); event.setAttributeChange(this.healthAttributeName, selfHealth); fightDetails.put("opponent-attack-after", opponentAttack); fightDetails.put("opponent-defense-after", opponentDefense); fightDetails.put("opponent-health-after", opponentHealth); fightDetails.put("self-attack-after", selfAttack); fightDetails.put("self-defense-after", selfDefense); fightDetails.put("self-health-after", selfHealth); event.addExtraInformation("fight-details", fightDetails); return true; }
diff --git a/src/main/java/org/atlasapi/feeds/radioplayer/upload/CachingFTPUploadResultStore.java b/src/main/java/org/atlasapi/feeds/radioplayer/upload/CachingFTPUploadResultStore.java index 2071de95..b26e3ab0 100644 --- a/src/main/java/org/atlasapi/feeds/radioplayer/upload/CachingFTPUploadResultStore.java +++ b/src/main/java/org/atlasapi/feeds/radioplayer/upload/CachingFTPUploadResultStore.java @@ -1,80 +1,80 @@ package org.atlasapi.feeds.radioplayer.upload; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import org.atlasapi.feeds.radioplayer.RadioPlayerService; import org.atlasapi.feeds.radioplayer.RadioPlayerServices; import org.joda.time.LocalDate; import com.google.common.base.Function; import com.google.common.collect.ImmutableSet; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class CachingFTPUploadResultStore implements RadioPlayerFTPUploadResultStore { private final RadioPlayerFTPUploadResultStore delegate; private final Map<RadioPlayerService, ConcurrentMap<LocalDate, Set<RadioPlayerFTPUploadResult>>> cache; public CachingFTPUploadResultStore(final RadioPlayerFTPUploadResultStore delegate) { this.delegate = delegate; this.cache = Maps.newHashMap(); loadCache(); } private void loadCache() { for (final RadioPlayerService service : RadioPlayerServices.services) { - cache.put(service, new MapMaker().softValues().expireAfterWrite(30, TimeUnit.MINUTES).makeComputingMap(new Function<LocalDate, Set<RadioPlayerFTPUploadResult>>() { + cache.put(service, new MapMaker().softValues().expireAfterWrite(30, TimeUnit.MINUTES).<LocalDate, Set<RadioPlayerFTPUploadResult>>makeComputingMap(new Function<LocalDate, Set<RadioPlayerFTPUploadResult>>() { @Override public Set<RadioPlayerFTPUploadResult> apply(LocalDate day) { TreeSet<RadioPlayerFTPUploadResult> set = Sets.newTreeSet(resultComparator); set.addAll(delegate.resultsFor(service, day)); return set; } })); } } @Override public void record(RadioPlayerFTPUploadResult result) { delegate.record(result); ConcurrentMap<LocalDate, Set<RadioPlayerFTPUploadResult>> serviceMap = cache.get(result.service()); Set<RadioPlayerFTPUploadResult> current = serviceMap.putIfAbsent(result.day(), treeSetWith(result)); if (current != null) { current.remove(result); current.add(result); } } private Set<RadioPlayerFTPUploadResult> treeSetWith(RadioPlayerFTPUploadResult result) { TreeSet<RadioPlayerFTPUploadResult> set = Sets.newTreeSet(resultComparator); set.add(result); return set; } @Override public Set<RadioPlayerFTPUploadResult> resultsFor(RadioPlayerService service, LocalDate day) { return ImmutableSet.copyOf(cache.get(service).get(day)); } private final Comparator<RadioPlayerFTPUploadResult> resultComparator = new Comparator<RadioPlayerFTPUploadResult>() { @Override public int compare(RadioPlayerFTPUploadResult r1, RadioPlayerFTPUploadResult r2) { int compareDays = r1.day().compareTo(r2.day()); if (compareDays != 0) { return compareDays; } return r1.type().compareTo(r2.type()); } }; }
true
true
private void loadCache() { for (final RadioPlayerService service : RadioPlayerServices.services) { cache.put(service, new MapMaker().softValues().expireAfterWrite(30, TimeUnit.MINUTES).makeComputingMap(new Function<LocalDate, Set<RadioPlayerFTPUploadResult>>() { @Override public Set<RadioPlayerFTPUploadResult> apply(LocalDate day) { TreeSet<RadioPlayerFTPUploadResult> set = Sets.newTreeSet(resultComparator); set.addAll(delegate.resultsFor(service, day)); return set; } })); } }
private void loadCache() { for (final RadioPlayerService service : RadioPlayerServices.services) { cache.put(service, new MapMaker().softValues().expireAfterWrite(30, TimeUnit.MINUTES).<LocalDate, Set<RadioPlayerFTPUploadResult>>makeComputingMap(new Function<LocalDate, Set<RadioPlayerFTPUploadResult>>() { @Override public Set<RadioPlayerFTPUploadResult> apply(LocalDate day) { TreeSet<RadioPlayerFTPUploadResult> set = Sets.newTreeSet(resultComparator); set.addAll(delegate.resultsFor(service, day)); return set; } })); } }
diff --git a/org.eclipse.virgo.kernel.smoketest/src/test/java/org/eclipse/virgo/kernel/smoketest/KernelStartupAndShutdownTests.java b/org.eclipse.virgo.kernel.smoketest/src/test/java/org/eclipse/virgo/kernel/smoketest/KernelStartupAndShutdownTests.java index 95c515be..2797a028 100644 --- a/org.eclipse.virgo.kernel.smoketest/src/test/java/org/eclipse/virgo/kernel/smoketest/KernelStartupAndShutdownTests.java +++ b/org.eclipse.virgo.kernel.smoketest/src/test/java/org/eclipse/virgo/kernel/smoketest/KernelStartupAndShutdownTests.java @@ -1,32 +1,33 @@ /******************************************************************************* * Copyright (c) 2008, 2010 VMware Inc. * 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: * VMware Inc. - initial contribution *******************************************************************************/ package org.eclipse.virgo.kernel.smoketest; import static org.junit.Assert.assertEquals; import org.junit.Test; public class KernelStartupAndShutdownTests extends AbstractKernelTests { @Test public void testKernelStartUpStatus() throws Exception { new Thread(new KernelStartUpThread()).start(); AbstractKernelTests.waitForKernelStartFully(); + Thread.sleep(20000); // wait for startup to complete in case it fails assertEquals(STATUS_STARTED, getKernelStartUpStatus()); } @Test public void testKernelShutdownStatus() throws Exception { new Thread(new KernelShutdownThread()).start(); AbstractKernelTests.waitForKernelShutdownFully(); } }
true
true
public void testKernelStartUpStatus() throws Exception { new Thread(new KernelStartUpThread()).start(); AbstractKernelTests.waitForKernelStartFully(); assertEquals(STATUS_STARTED, getKernelStartUpStatus()); }
public void testKernelStartUpStatus() throws Exception { new Thread(new KernelStartUpThread()).start(); AbstractKernelTests.waitForKernelStartFully(); Thread.sleep(20000); // wait for startup to complete in case it fails assertEquals(STATUS_STARTED, getKernelStartUpStatus()); }
diff --git a/src/main/java/stirling/fix/messages/Parser.java b/src/main/java/stirling/fix/messages/Parser.java index 806c0062..f03e97a8 100644 --- a/src/main/java/stirling/fix/messages/Parser.java +++ b/src/main/java/stirling/fix/messages/Parser.java @@ -1,84 +1,87 @@ /* * Copyright 2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package stirling.fix.messages; import org.joda.time.DateTime; import java.nio.ByteBuffer; import stirling.fix.messages.FixMessage; import stirling.fix.messages.fix42.DefaultMessageFactory; import stirling.fix.tags.fix42.MsgSeqNum; public class Parser { public interface Callback { void message(Message m); void invalidMessage(int msgSeqNum, Value<Integer> reason, String text); void unsupportedMsgType(String msgType, int msgSeqNum); void invalidMsgType(String msgType, int msgSeqNum); } public static void parse(FixMessage m, Callback callback) { parse(new DefaultMessageFactory(), m, callback); } public static void parse(MessageFactory messageFactory, FixMessage m, Callback callback) { parse(messageFactory, m.toByteBuffer(), callback, m.getReceiveTime()); } private static void parse(MessageFactory messageFactory, ByteBuffer b, Callback callback, DateTime receiveTime) { MessageHeader header = null; try { header = messageFactory.createHeader(); header.parse(b); header.validate(); Message msg = messageFactory.create(header.getMsgType(), header); msg.parse(b); msg.validate(); msg.setReceiveTime(receiveTime); callback.message(msg); } catch (InvalidMsgTypeException e) { callback.invalidMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (UnsupportedMsgTypeException e) { callback.unsupportedMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (ParseException e) { - callback.invalidMessage(header.getInteger(MsgSeqNum.Tag()), e.getReason(), e.getMessage()); + int msgSeqNum = 0; + if (header.hasValue(MsgSeqNum.Tag())) + msgSeqNum = header.getInteger(MsgSeqNum.Tag()); + callback.invalidMessage(msgSeqNum, e.getReason(), e.getMessage()); } } public static int parseMsgSeqNum(FixMessage message) { String value = parseField(message, MsgSeqNum.Tag()); IntegerField field = new IntegerField(MsgSeqNum.Tag()); field.parse(value); if (!field.isFormatValid()) throw new InvalidValueFormatException(MsgSeqNum.Tag().prettyName() + " has invalid value format: " + value); return field.intValue(); } private static String parseField(FixMessage message, Tag tagToFind) { ByteBuffer b = message.toByteBuffer(); while (b.hasRemaining()) { try { int tag = Tag.parseTag(b); String value = AbstractField.parseValue(b); if (tag == tagToFind.value()) return value; } catch (NonDataValueIncludesFieldDelimiterException e) { /* Ignore tag that cannot be parsed due to delimiter in tag */ } } throw new ParseException(tagToFind.prettyName() + " is missing"); } }
true
true
private static void parse(MessageFactory messageFactory, ByteBuffer b, Callback callback, DateTime receiveTime) { MessageHeader header = null; try { header = messageFactory.createHeader(); header.parse(b); header.validate(); Message msg = messageFactory.create(header.getMsgType(), header); msg.parse(b); msg.validate(); msg.setReceiveTime(receiveTime); callback.message(msg); } catch (InvalidMsgTypeException e) { callback.invalidMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (UnsupportedMsgTypeException e) { callback.unsupportedMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (ParseException e) { callback.invalidMessage(header.getInteger(MsgSeqNum.Tag()), e.getReason(), e.getMessage()); } }
private static void parse(MessageFactory messageFactory, ByteBuffer b, Callback callback, DateTime receiveTime) { MessageHeader header = null; try { header = messageFactory.createHeader(); header.parse(b); header.validate(); Message msg = messageFactory.create(header.getMsgType(), header); msg.parse(b); msg.validate(); msg.setReceiveTime(receiveTime); callback.message(msg); } catch (InvalidMsgTypeException e) { callback.invalidMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (UnsupportedMsgTypeException e) { callback.unsupportedMsgType(header.getMsgType(), header.getInteger(MsgSeqNum.Tag())); } catch (ParseException e) { int msgSeqNum = 0; if (header.hasValue(MsgSeqNum.Tag())) msgSeqNum = header.getInteger(MsgSeqNum.Tag()); callback.invalidMessage(msgSeqNum, e.getReason(), e.getMessage()); } }
diff --git a/JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java b/JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java index 2bf4a94..3e69aab 100644 --- a/JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java +++ b/JsTestDriver/src/com/google/jstestdriver/output/FileNameFormatter.java @@ -1,43 +1,42 @@ /* * Copyright 2011 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.jstestdriver.output; /** * Escapes and formats a filename. * * @author Cory Smith ([email protected]) */ public class FileNameFormatter { public String format(String path, String format) { String escaped = path .replace('/', 'a') .replace('\\', 'a') .replace(">", "a") - .replace(".", "a") .replace(":", "a") .replace(":", "a") .replace(";", "a") .replace("+", "a") .replace(",", "a") .replace("<", "a") .replace("?", "a") .replace("*", "a") .replace(" ", "a"); return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped); } }
true
true
public String format(String path, String format) { String escaped = path .replace('/', 'a') .replace('\\', 'a') .replace(">", "a") .replace(".", "a") .replace(":", "a") .replace(":", "a") .replace(";", "a") .replace("+", "a") .replace(",", "a") .replace("<", "a") .replace("?", "a") .replace("*", "a") .replace(" ", "a"); return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped); }
public String format(String path, String format) { String escaped = path .replace('/', 'a') .replace('\\', 'a') .replace(">", "a") .replace(":", "a") .replace(":", "a") .replace(";", "a") .replace("+", "a") .replace(",", "a") .replace("<", "a") .replace("?", "a") .replace("*", "a") .replace(" ", "a"); return String.format(format, escaped.length() > 200 ? escaped.substring(0, 200) : escaped); }
diff --git a/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java b/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java index c828c1d95..e270aa262 100644 --- a/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java +++ b/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java @@ -1,169 +1,169 @@ /* * Copyright 2005-2006 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.servicemix.common; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.PrintWriter; import java.io.StringWriter; /** * ManagementMessageHelper is a class that ease the building of management messages. */ public class ManagementSupport { private static final Log logger = LogFactory.getLog(ManagementSupport.class); public static class Message { private String task; private String component; private String result; private Exception exception; private String type; private String message; public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } public static String createComponentMessage(Message msg) { try { StringBuffer sw = new StringBuffer(); // component-task-result sw.append("<component-task-result "); sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\">"); sw.append("\n\t"); // component-name sw.append("<component-name>"); sw.append(msg.getComponent()); sw.append("</component-name>"); // component-task-result-details sw.append("\n\t"); sw.append("<component-task-result-details>"); // task-result-details sw.append("\n\t\t"); sw.append("<task-result-details>"); // task-id sw.append("\n\t\t\t"); sw.append("<task-id>"); sw.append(msg.getTask()); sw.append("</task-id>"); // task-result sw.append("\n\t\t\t"); sw.append("<task-result>"); sw.append(msg.getResult()); sw.append("</task-result>"); // message-type if (msg.getType() != null) { sw.append("\n\t\t\t"); sw.append("<message-type>"); sw.append(msg.getType()); sw.append("</message-type>"); } // task-status-message if (msg.getMessage() != null) { sw.append("\n\t\t\t"); - sw.append("<task-status-message>"); + sw.append("<task-status-msg>"); sw.append("<msg-loc-info>"); sw.append("<loc-token/>"); sw.append("<loc-message>"); sw.append(msg.getMessage()); sw.append("</loc-message>"); sw.append("</msg-loc-info>"); - sw.append("</task-status-message>"); + sw.append("</task-status-msg>"); } // exception-info if (msg.getException() != null) { sw.append("\n\t\t\t"); sw.append("<exception-info>"); sw.append("\n\t\t\t\t"); sw.append("<nesting-level>1</nesting-level>"); sw.append("\n\t\t\t\t"); sw.append("<msg-loc-info>"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-token />"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-message>"); sw.append(msg.getException().getMessage()); sw.append("</loc-message>"); sw.append("\n\t\t\t\t\t"); sw.append("<stack-trace>"); StringWriter sw2 = new StringWriter(); PrintWriter pw = new PrintWriter(sw2); msg.getException().printStackTrace(pw); pw.close(); sw.append("<![CDATA["); sw.append(sw2.toString()); sw.append("]]>"); sw.append("</stack-trace>"); sw.append("\n\t\t\t\t"); sw.append("</msg-loc-info>"); sw.append("\n\t\t\t"); sw.append("</exception-info>"); } // end: task-result-details sw.append("\n\t\t"); sw.append("</task-result-details>"); // end: component-task-result-details sw.append("\n\t"); sw.append("</component-task-result-details>"); // end: component-task-result sw.append("\n"); sw.append("</component-task-result>"); // return result return sw.toString(); } catch (Exception e) { logger.warn("Error generating component management message", e); return null; } } }
false
true
public static String createComponentMessage(Message msg) { try { StringBuffer sw = new StringBuffer(); // component-task-result sw.append("<component-task-result "); sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\">"); sw.append("\n\t"); // component-name sw.append("<component-name>"); sw.append(msg.getComponent()); sw.append("</component-name>"); // component-task-result-details sw.append("\n\t"); sw.append("<component-task-result-details>"); // task-result-details sw.append("\n\t\t"); sw.append("<task-result-details>"); // task-id sw.append("\n\t\t\t"); sw.append("<task-id>"); sw.append(msg.getTask()); sw.append("</task-id>"); // task-result sw.append("\n\t\t\t"); sw.append("<task-result>"); sw.append(msg.getResult()); sw.append("</task-result>"); // message-type if (msg.getType() != null) { sw.append("\n\t\t\t"); sw.append("<message-type>"); sw.append(msg.getType()); sw.append("</message-type>"); } // task-status-message if (msg.getMessage() != null) { sw.append("\n\t\t\t"); sw.append("<task-status-message>"); sw.append("<msg-loc-info>"); sw.append("<loc-token/>"); sw.append("<loc-message>"); sw.append(msg.getMessage()); sw.append("</loc-message>"); sw.append("</msg-loc-info>"); sw.append("</task-status-message>"); } // exception-info if (msg.getException() != null) { sw.append("\n\t\t\t"); sw.append("<exception-info>"); sw.append("\n\t\t\t\t"); sw.append("<nesting-level>1</nesting-level>"); sw.append("\n\t\t\t\t"); sw.append("<msg-loc-info>"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-token />"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-message>"); sw.append(msg.getException().getMessage()); sw.append("</loc-message>"); sw.append("\n\t\t\t\t\t"); sw.append("<stack-trace>"); StringWriter sw2 = new StringWriter(); PrintWriter pw = new PrintWriter(sw2); msg.getException().printStackTrace(pw); pw.close(); sw.append("<![CDATA["); sw.append(sw2.toString()); sw.append("]]>"); sw.append("</stack-trace>"); sw.append("\n\t\t\t\t"); sw.append("</msg-loc-info>"); sw.append("\n\t\t\t"); sw.append("</exception-info>"); } // end: task-result-details sw.append("\n\t\t"); sw.append("</task-result-details>"); // end: component-task-result-details sw.append("\n\t"); sw.append("</component-task-result-details>"); // end: component-task-result sw.append("\n"); sw.append("</component-task-result>"); // return result return sw.toString(); } catch (Exception e) { logger.warn("Error generating component management message", e); return null; } }
public static String createComponentMessage(Message msg) { try { StringBuffer sw = new StringBuffer(); // component-task-result sw.append("<component-task-result "); sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\">"); sw.append("\n\t"); // component-name sw.append("<component-name>"); sw.append(msg.getComponent()); sw.append("</component-name>"); // component-task-result-details sw.append("\n\t"); sw.append("<component-task-result-details>"); // task-result-details sw.append("\n\t\t"); sw.append("<task-result-details>"); // task-id sw.append("\n\t\t\t"); sw.append("<task-id>"); sw.append(msg.getTask()); sw.append("</task-id>"); // task-result sw.append("\n\t\t\t"); sw.append("<task-result>"); sw.append(msg.getResult()); sw.append("</task-result>"); // message-type if (msg.getType() != null) { sw.append("\n\t\t\t"); sw.append("<message-type>"); sw.append(msg.getType()); sw.append("</message-type>"); } // task-status-message if (msg.getMessage() != null) { sw.append("\n\t\t\t"); sw.append("<task-status-msg>"); sw.append("<msg-loc-info>"); sw.append("<loc-token/>"); sw.append("<loc-message>"); sw.append(msg.getMessage()); sw.append("</loc-message>"); sw.append("</msg-loc-info>"); sw.append("</task-status-msg>"); } // exception-info if (msg.getException() != null) { sw.append("\n\t\t\t"); sw.append("<exception-info>"); sw.append("\n\t\t\t\t"); sw.append("<nesting-level>1</nesting-level>"); sw.append("\n\t\t\t\t"); sw.append("<msg-loc-info>"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-token />"); sw.append("\n\t\t\t\t\t"); sw.append("<loc-message>"); sw.append(msg.getException().getMessage()); sw.append("</loc-message>"); sw.append("\n\t\t\t\t\t"); sw.append("<stack-trace>"); StringWriter sw2 = new StringWriter(); PrintWriter pw = new PrintWriter(sw2); msg.getException().printStackTrace(pw); pw.close(); sw.append("<![CDATA["); sw.append(sw2.toString()); sw.append("]]>"); sw.append("</stack-trace>"); sw.append("\n\t\t\t\t"); sw.append("</msg-loc-info>"); sw.append("\n\t\t\t"); sw.append("</exception-info>"); } // end: task-result-details sw.append("\n\t\t"); sw.append("</task-result-details>"); // end: component-task-result-details sw.append("\n\t"); sw.append("</component-task-result-details>"); // end: component-task-result sw.append("\n"); sw.append("</component-task-result>"); // return result return sw.toString(); } catch (Exception e) { logger.warn("Error generating component management message", e); return null; } }
diff --git a/hudson-core/src/main/java/hudson/model/ItemGroupMixIn.java b/hudson-core/src/main/java/hudson/model/ItemGroupMixIn.java index 3d22a2d2..93633496 100644 --- a/hudson-core/src/main/java/hudson/model/ItemGroupMixIn.java +++ b/hudson-core/src/main/java/hudson/model/ItemGroupMixIn.java @@ -1,303 +1,303 @@ /******************************************************************************* * * Copyright (c) 2004-2009 Oracle 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: * * Kohsuke Kawaguchi, CloudBees, Inc. * * *******************************************************************************/ package hudson.model; import hudson.Util; import hudson.model.listeners.ItemListener; import hudson.security.AccessControlled; import hudson.util.CopyOnWriteMap; import hudson.util.Function1; import hudson.util.IOUtils; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.eclipse.hudson.security.team.Team; import org.eclipse.hudson.security.team.TeamManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Defines a bunch of static methods to be used as a "mix-in" for * {@link ItemGroup} implementations. Not meant for a consumption from outside * {@link ItemGroup}s. * * @author Kohsuke Kawaguchi */ public abstract class ItemGroupMixIn { private transient Logger logger = LoggerFactory.getLogger(ItemGroupMixIn.class); /** * {@link ItemGroup} for which we are working. */ private final ItemGroup parent; private final AccessControlled acl; protected ItemGroupMixIn(ItemGroup parent, AccessControlled acl) { this.parent = parent; this.acl = acl; } /* * Callback methods to be implemented by the ItemGroup implementation. */ /** * Adds a newly created item to the parent. */ protected abstract void add(TopLevelItem item); /** * Assigns the root directory for a prospective item. */ protected abstract File getRootDirFor(String name); /* * The rest is the methods that provide meat. */ /** * Loads all the child {@link Item}s. * * @param modulesDir Directory that contains sub-directories for each child * item. */ public static <K, V extends Item> Map<K, V> loadChildren(ItemGroup parent, File modulesDir, Function1<? extends K, ? super V> key) { modulesDir.mkdirs(); // make sure it exists File[] subdirs = modulesDir.listFiles(new FileFilter() { public boolean accept(File child) { return child.isDirectory(); } }); CopyOnWriteMap.Tree<K, V> configurations = new CopyOnWriteMap.Tree<K, V>(); for (File subdir : subdirs) { try { V item = (V) Items.load(parent, subdir); configurations.put(key.call(item), item); } catch (IOException e) { e.printStackTrace(); // TODO: logging } } return configurations; } /** * {@link Item} -> name function. */ public static final Function1<String, Item> KEYED_BY_NAME = new Function1<String, Item>() { public String call(Item item) { return item.getName(); } }; /** * Creates a {@link TopLevelItem} from the submission of the * '/lib/hudson/newFromList/formList' or throws an exception if it fails. */ public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Job.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if (requestContentType == null) { throw new Failure("No Content-Type header set"); } boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if (name == null) { throw new Failure("Query parameter 'name' is required"); } Team requestedTeam = null; { // check if the name looks good Hudson hudson = Hudson.getInstance(); Hudson.checkGoodName(name); name = name.trim(); if (hudson.isTeamManagementEnabled() && (name.indexOf(TeamManager.TEAM_SEPARATOR) != -1)) { throw new Failure("The job name cannot contain" + TeamManager.TEAM_SEPARATOR + "when team management is enabled. "); } String existingJobName = name; if (hudson.isTeamManagementEnabled()){ existingJobName = hudson.getTeamManager().getTeamQualifiedJobName(name); } if (parent.getItem(existingJobName) != null) { throw new Failure(Messages.Hudson_JobAlreadyExists(existingJobName)); } // see if team requested if (hudson.isTeamManagementEnabled()) { String team = req.getParameter("team"); if (team != null){ String teamName = team.trim(); if (teamName.length() > 0) { try { requestedTeam = hudson.getTeamManager().findTeam(teamName); } catch (TeamManager.TeamNotFoundException ex) { - logger.error("Requested team " + teamName + " not found"); + throw new Failure("Requested team " + teamName + " not found"); } } } } } String mode = req.getParameter("mode"); if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = parent.getItem(from); if (src == null) { src = Hudson.getInstance().getItemByFullName(from); } if (src == null) { if (Util.fixEmpty(from) == null) { throw new Failure("Specify which job to copy"); } else { throw new Failure("No such job: " + from); } } if (!(src instanceof TopLevelItem)) { throw new Failure(from + " cannot be copied"); } result = copy((TopLevelItem) src, name); } else { if (isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if (mode == null) { throw new Failure("No mode given"); } // create empty job and redirect to the project config screen result = createProject(Items.getDescriptor(mode), name, true); } } if (Hudson.getInstance().isTeamManagementEnabled() && requestedTeam != null) { TeamManager teamManager = Hudson.getInstance().getTeamManager(); teamManager.ensureJobInTeam(result, requestedTeam); } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; } /** * Computes the redirection target URL for the newly created * {@link TopLevelItem}. */ protected String redirectAfterCreateItem(StaplerRequest req, TopLevelItem result) throws IOException { return req.getContextPath() + '/' + result.getUrl() + "configure"; } /** * Copies an existing {@link TopLevelItem} to a new name. * * The caller is responsible for calling * {@link ItemListener#fireOnCopied(Item, Item)}. This method cannot do that * because it doesn't know how to make the newly added item reachable from * the parent. */ @SuppressWarnings({"unchecked" }) public synchronized <T extends TopLevelItem> T copy(T src, String name) throws IOException { acl.checkPermission(Job.CREATE); T result = (T) createProject(src.getDescriptor(), name, false); // copy config Util.copyFile(Items.getConfigFile(src).getFile(), Items.getConfigFile(result).getFile()); // reload from the new config result = (T) Items.load(parent, result.getRootDir()); result.onCopiedFrom(src); add(result); ItemListener.fireOnCopied(src, result); return result; } public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml) throws IOException { acl.checkPermission(Job.CREATE); // place it as config.xml File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); configXml.getParentFile().mkdirs(); try { IOUtils.copy(xml, configXml); // load it TopLevelItem result = (TopLevelItem) Items.load(parent, configXml.getParentFile()); add(result); ItemListener.fireOnCreated(result); Hudson.getInstance().rebuildDependencyGraph(); return result; } catch (IOException e) { // if anything fails, delete the config file to avoid further confusion Util.deleteRecursive(configXml.getParentFile()); throw e; } } public synchronized TopLevelItem createProject(TopLevelItemDescriptor type, String name, boolean notify) throws IOException { acl.checkPermission(Job.CREATE); Hudson hudson = Hudson.getInstance(); String existingJobName = name; if (hudson.isTeamManagementEnabled()) { existingJobName = hudson.getTeamManager().getTeamQualifiedJobName(name); } if (parent.getItem(existingJobName) != null) { throw new IllegalArgumentException("Job with name " + name + " already exists"); } TopLevelItem item; try { item = type.newInstance(parent, name); } catch (Exception e) { throw new IllegalArgumentException(e); } item.onCreatedFromScratch(); item.save(); add(item); if (notify) { ItemListener.fireOnCreated(item); } return item; } }
true
true
public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Job.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if (requestContentType == null) { throw new Failure("No Content-Type header set"); } boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if (name == null) { throw new Failure("Query parameter 'name' is required"); } Team requestedTeam = null; { // check if the name looks good Hudson hudson = Hudson.getInstance(); Hudson.checkGoodName(name); name = name.trim(); if (hudson.isTeamManagementEnabled() && (name.indexOf(TeamManager.TEAM_SEPARATOR) != -1)) { throw new Failure("The job name cannot contain" + TeamManager.TEAM_SEPARATOR + "when team management is enabled. "); } String existingJobName = name; if (hudson.isTeamManagementEnabled()){ existingJobName = hudson.getTeamManager().getTeamQualifiedJobName(name); } if (parent.getItem(existingJobName) != null) { throw new Failure(Messages.Hudson_JobAlreadyExists(existingJobName)); } // see if team requested if (hudson.isTeamManagementEnabled()) { String team = req.getParameter("team"); if (team != null){ String teamName = team.trim(); if (teamName.length() > 0) { try { requestedTeam = hudson.getTeamManager().findTeam(teamName); } catch (TeamManager.TeamNotFoundException ex) { logger.error("Requested team " + teamName + " not found"); } } } } } String mode = req.getParameter("mode"); if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = parent.getItem(from); if (src == null) { src = Hudson.getInstance().getItemByFullName(from); } if (src == null) { if (Util.fixEmpty(from) == null) { throw new Failure("Specify which job to copy"); } else { throw new Failure("No such job: " + from); } } if (!(src instanceof TopLevelItem)) { throw new Failure(from + " cannot be copied"); } result = copy((TopLevelItem) src, name); } else { if (isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if (mode == null) { throw new Failure("No mode given"); } // create empty job and redirect to the project config screen result = createProject(Items.getDescriptor(mode), name, true); } } if (Hudson.getInstance().isTeamManagementEnabled() && requestedTeam != null) { TeamManager teamManager = Hudson.getInstance().getTeamManager(); teamManager.ensureJobInTeam(result, requestedTeam); } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; }
public synchronized TopLevelItem createTopLevelItem(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { acl.checkPermission(Job.CREATE); TopLevelItem result; String requestContentType = req.getContentType(); if (requestContentType == null) { throw new Failure("No Content-Type header set"); } boolean isXmlSubmission = requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml"); String name = req.getParameter("name"); if (name == null) { throw new Failure("Query parameter 'name' is required"); } Team requestedTeam = null; { // check if the name looks good Hudson hudson = Hudson.getInstance(); Hudson.checkGoodName(name); name = name.trim(); if (hudson.isTeamManagementEnabled() && (name.indexOf(TeamManager.TEAM_SEPARATOR) != -1)) { throw new Failure("The job name cannot contain" + TeamManager.TEAM_SEPARATOR + "when team management is enabled. "); } String existingJobName = name; if (hudson.isTeamManagementEnabled()){ existingJobName = hudson.getTeamManager().getTeamQualifiedJobName(name); } if (parent.getItem(existingJobName) != null) { throw new Failure(Messages.Hudson_JobAlreadyExists(existingJobName)); } // see if team requested if (hudson.isTeamManagementEnabled()) { String team = req.getParameter("team"); if (team != null){ String teamName = team.trim(); if (teamName.length() > 0) { try { requestedTeam = hudson.getTeamManager().findTeam(teamName); } catch (TeamManager.TeamNotFoundException ex) { throw new Failure("Requested team " + teamName + " not found"); } } } } } String mode = req.getParameter("mode"); if (mode != null && mode.equals("copy")) { String from = req.getParameter("from"); // resolve a name to Item Item src = parent.getItem(from); if (src == null) { src = Hudson.getInstance().getItemByFullName(from); } if (src == null) { if (Util.fixEmpty(from) == null) { throw new Failure("Specify which job to copy"); } else { throw new Failure("No such job: " + from); } } if (!(src instanceof TopLevelItem)) { throw new Failure(from + " cannot be copied"); } result = copy((TopLevelItem) src, name); } else { if (isXmlSubmission) { result = createProjectFromXML(name, req.getInputStream()); rsp.setStatus(HttpServletResponse.SC_OK); return result; } else { if (mode == null) { throw new Failure("No mode given"); } // create empty job and redirect to the project config screen result = createProject(Items.getDescriptor(mode), name, true); } } if (Hudson.getInstance().isTeamManagementEnabled() && requestedTeam != null) { TeamManager teamManager = Hudson.getInstance().getTeamManager(); teamManager.ensureJobInTeam(result, requestedTeam); } rsp.sendRedirect2(redirectAfterCreateItem(req, result)); return result; }
diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index 46436bbea..b0cb3527b 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -1,1687 +1,1687 @@ package cgeo.geocaching.maps; import cgeo.geocaching.DirectionProvider; import cgeo.geocaching.IGeoData; import cgeo.geocaching.IWaypoint; import cgeo.geocaching.LiveMapInfo; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.StoredList; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.cgeocaches; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.gc.Login; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl; import cgeo.geocaching.maps.interfaces.GeoPointImpl; import cgeo.geocaching.maps.interfaces.MapActivityImpl; import cgeo.geocaching.maps.interfaces.MapControllerImpl; import cgeo.geocaching.maps.interfaces.MapItemFactory; import cgeo.geocaching.maps.interfaces.MapProvider; import cgeo.geocaching.maps.interfaces.MapSource; import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnMapDragListener; import cgeo.geocaching.utils.AngleUtils; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.GeoDirHandler; import cgeo.geocaching.utils.LeastRecentlyUsedSet; import cgeo.geocaching.utils.Log; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.HashCodeBuilder; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.SparseArray; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageSwitcher; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.TextView; import android.widget.ViewSwitcher.ViewFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Class representing the Map in c:geo */ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFactory { /** max. number of caches displayed in the Live Map */ public static final int MAX_CACHES = 500; /**Controls the behaviour of the map*/ public enum MapMode { /** Live Map where caches are loaded from online */ LIVE_ONLINE, /** Live Map where caches are loaded only from database */ LIVE_OFFLINE, /** Map around some coordinates */ COORDS, /** Map with a single cache (no reload on move) */ SINGLE, /** Map with a list of caches (no reload on move) */ LIST } /** Handler Messages */ private static final int HIDE_PROGRESS = 0; private static final int SHOW_PROGRESS = 1; private static final int UPDATE_TITLE = 0; private static final int INVALIDATE_MAP = 1; private static final int UPDATE_PROGRESS = 0; private static final int FINISHED_LOADING_DETAILS = 1; //Menu private static final String EXTRAS_GEOCODE = "geocode"; private static final String EXTRAS_COORDS = "coords"; private static final String EXTRAS_WPTTYPE = "wpttype"; private static final String EXTRAS_MAPSTATE = "mapstate"; private static final String EXTRAS_SEARCH = "search"; private static final String EXTRAS_MAP_MODE = "map_mode"; private static final int MENU_SELECT_MAPVIEW = 1; private static final int MENU_MAP_LIVE = 2; private static final int MENU_STORE_CACHES = 3; private static final int MENU_TRAIL_MODE = 4; private static final int SUBMENU_STRATEGY = 5; private static final int MENU_STRATEGY_FASTEST = 51; private static final int MENU_STRATEGY_FAST = 52; private static final int MENU_STRATEGY_AUTO = 53; private static final int MENU_STRATEGY_DETAILED = 74; private static final int MENU_CIRCLE_MODE = 6; private static final int MENU_AS_LIST = 7; private static final String EXTRAS_MAP_TITLE = "mapTitle"; private static final String BUNDLE_MAP_SOURCE = "mapSource"; private static final String BUNDLE_MAP_STATE = "mapState"; private static final String BUNDLE_MAP_MODE = "mapMode"; private Resources res = null; private MapItemFactory mapItemFactory = null; private Activity activity = null; private MapViewImpl mapView = null; private cgeoapplication app = null; final private GeoDirHandler geoDirUpdate = new UpdateLoc(); private SearchResult searchIntent = null; private String geocodeIntent = null; private Geopoint coordsIntent = null; private WaypointType waypointTypeIntent = null; private int[] mapStateIntent = null; // status data /** Last search result used for displaying header */ private SearchResult lastSearchResult = null; private String[] tokens = null; private boolean noMapTokenShowed = false; // map status data private boolean followMyLocation = false; private Viewport viewport = null; private int zoom = -100; // threads private LoadTimer loadTimer = null; private LoadDetails loadDetailsThread = null; /** Time of last {@link LoadRunnable} run */ private volatile long loadThreadRun = 0L; //Interthread communication flag private volatile boolean downloaded = false; // overlays private CachesOverlay overlayCaches = null; private ScaleOverlay overlayScale = null; private PositionOverlay overlayPosition = null; // data for overlays private static final int[][] INSET_RELIABLE = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; // center, 33x40 / 45x51 private static final int[][] INSET_TYPE = { { 5, 8, 6, 10 }, { 4, 4, 5, 11 } }; // center, 22x22 / 36x36 private static final int[][] INSET_OWN = { { 21, 0, 0, 26 }, { 25, 0, 0, 35 } }; // top right, 12x12 / 16x16 private static final int[][] INSET_FOUND = { { 0, 0, 21, 28 }, { 0, 0, 25, 35 } }; // top left, 12x12 / 16x16 private static final int[][] INSET_USERMODIFIEDCOORDS = { { 21, 28, 0, 0 }, { 19, 25, 0, 0 } }; // bottom right, 12x12 / 26x26 private static final int[][] INSET_PERSONALNOTE = { { 0, 28, 21, 0 }, { 0, 25, 19, 0 } }; // bottom left, 12x12 / 26x26 private SparseArray<LayerDrawable> overlaysCache = new SparseArray<LayerDrawable>(); /** Count of caches currently visible */ private int cachesCnt = 0; /** List of caches in the viewport */ private LeastRecentlyUsedSet<cgCache> caches = null; /** List of waypoints in the viewport */ private final LeastRecentlyUsedSet<cgWaypoint> waypoints = new LeastRecentlyUsedSet<cgWaypoint>(MAX_CACHES); // storing for offline private ProgressDialog waitDialog = null; private int detailTotal = 0; private int detailProgress = 0; private long detailProgressTime = 0L; // views private ImageSwitcher myLocSwitch = null; /**Controls the map behaviour*/ private MapMode mapMode = null; // other things private boolean liveChanged = false; // previous state for loadTimer private boolean centered = false; // if map is already centered private boolean alreadyCentered = false; // -""- for setting my location private static Set<String> dirtyCaches = null; // Thread pooling private static BlockingQueue<Runnable> displayQueue = new ArrayBlockingQueue<Runnable>(1); private static ThreadPoolExecutor displayExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, displayQueue, new ThreadPoolExecutor.DiscardOldestPolicy()); private static BlockingQueue<Runnable> downloadQueue = new ArrayBlockingQueue<Runnable>(1); private static ThreadPoolExecutor downloadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, downloadQueue, new ThreadPoolExecutor.DiscardOldestPolicy()); private static BlockingQueue<Runnable> loadQueue = new ArrayBlockingQueue<Runnable>(1); private static ThreadPoolExecutor loadExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, loadQueue, new ThreadPoolExecutor.DiscardOldestPolicy()); // handlers /** Updates the titles */ final private Handler displayHandler = new Handler() { @Override public void handleMessage(Message msg) { final int what = msg.what; switch (what) { case UPDATE_TITLE: // set title final StringBuilder title = new StringBuilder(); if (mapMode == MapMode.LIVE_ONLINE) { title.append(res.getString(R.string.map_live)); } else { title.append(mapTitle); } countVisibleCaches(); if (caches != null && caches.size() > 0 && !mapTitle.contains("[")) { title.append(" [").append(cachesCnt); if (cachesCnt != caches.size()) { title.append('/').append(caches.size()); } title.append(']'); } if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) { title.append('[').append(lastSearchResult.getUrl()).append(']'); } ActivityMixin.setTitle(activity, title.toString()); break; case INVALIDATE_MAP: mapView.repaintRequired(null); break; default: break; } } }; /** Updates the progress. */ final private Handler showProgressHandler = new Handler() { private int counter = 0; @Override public void handleMessage(Message msg) { final int what = msg.what; if (what == HIDE_PROGRESS) { if (--counter == 0) { ActivityMixin.showProgress(activity, false); } } else if (what == SHOW_PROGRESS) { ActivityMixin.showProgress(activity, true); counter++; } } }; final private class LoadDetailsHandler extends CancellableHandler { @Override public void handleRegularMessage(Message msg) { if (msg.what == UPDATE_PROGRESS) { if (waitDialog != null) { int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); int secondsRemaining; if (detailProgress > 0) { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress; } else { secondsRemaining = (detailTotal - detailProgress) * secondsElapsed; } waitDialog.setProgress(detailProgress); if (secondsRemaining < 40) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { int minsRemaining = secondsRemaining / 60; waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + minsRemaining + " " + res.getQuantityString(R.plurals.caches_eta_mins,minsRemaining)); } } } else if (msg.what == FINISHED_LOADING_DETAILS) { if (waitDialog != null) { waitDialog.dismiss(); waitDialog.setOnCancelListener(null); } geoDirUpdate.startDir(); } } @Override public void handleCancel(final Object extra) { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } geoDirUpdate.startDir(); } } final private Handler noMapTokenHandler = new Handler() { @Override public void handleMessage(Message msg) { if (!noMapTokenShowed) { ActivityMixin.showToast(activity, res.getString(R.string.map_token_err)); noMapTokenShowed = true; } } }; /** * calling activities can set the map title via extras */ private String mapTitle; /* Current source id */ private int currentSourceId; public CGeoMap(MapActivityImpl activity) { super(activity); } protected void countVisibleCaches() { final List<cgCache> protectedCaches = caches.getAsList(); int count = 0; if (protectedCaches.size() > 0) { final Viewport viewport = mapView.getViewport(); for (final cgCache cache : protectedCaches) { if (cache != null && cache.getCoords() != null) { if (viewport.contains(cache)) { count++; } } } } cachesCnt = count; } @Override public void onSaveInstanceState(final Bundle outState) { outState.putInt(BUNDLE_MAP_SOURCE, currentSourceId); outState.putIntArray(BUNDLE_MAP_STATE, currentMapState()); if (isLiveMode()) { outState.putString(BUNDLE_MAP_MODE, mapMode.name()); } else { outState.putString(BUNDLE_MAP_MODE, null); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // class init res = this.getResources(); activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL); caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt); final MapProvider mapProvider = Settings.getMapProvider(); mapItemFactory = mapProvider.getMapItemFactory(); // Get parameters from the intent final Bundle extras = activity.getIntent().getExtras(); if (extras != null) { mapMode = (MapMode) extras.get(EXTRAS_MAP_MODE); searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH); geocodeIntent = extras.getString(EXTRAS_GEOCODE); coordsIntent = (Geopoint) extras.getParcelable(EXTRAS_COORDS); waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE)); mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE; } if (StringUtils.isBlank(mapTitle)) { mapTitle = res.getString(R.string.map_map); } // Get fresh map information from the bundle if any if (savedInstanceState != null) { currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource()); mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE); - if (savedInstanceState.getString(BUNDLE_MAP_MODE) != null) - { - mapMode = Enum.valueOf(MapMode.class, savedInstanceState.getString(BUNDLE_MAP_MODE)); + String lastMapmode = savedInstanceState.getString(BUNDLE_MAP_MODE); + if (lastMapmode != null) { + mapMode = Enum.valueOf(MapMode.class, lastMapmode); } Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { currentSourceId = Settings.getMapSource(); } // If recreating from an obsolete map source, we may need a restart if (changeMapSource(Settings.getMapSource())) { return; } // reset status noMapTokenShowed = false; ActivityMixin.keepScreenOn(activity, true); // set layout ActivityMixin.setTheme(activity); activity.setContentView(mapProvider.getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); // initialize map mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId()); mapView.setMapSource(); mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); mapView.preLoad(); mapView.setOnDragListener(this); // initialize overlays mapView.clearOverlays(); if (overlayCaches == null) { overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker)); } if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (overlayScale == null) { overlayScale = mapView.createAddScaleOverlay(activity); } mapView.repaintRequired(null); mapView.getMapController().setZoom(Settings.getMapZoom()); mapView.getMapController().setCenter(Settings.getMapCenter()); if (null == mapStateIntent) { followMyLocation = mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE; } else { followMyLocation = 1 == mapStateIntent[3]; if ((overlayCaches.getCircles() ? 1 : 0) != mapStateIntent[4]) { overlayCaches.switchCircles(); } } if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) { centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent); } // prepare my location button myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position); myLocSwitch.setFactory(this); myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); myLocSwitch.setOnClickListener(new MyLocationListener()); switchMyLocationButton(); prepareFilterBar(); if (!app.isLiveMapHintShown() && !Settings.getHideLiveMapHint()) { Intent hintIntent = new Intent(activity, LiveMapInfo.class); activity.startActivity(hintIntent); app.setLiveMapHintShown(); } } private void prepareFilterBar() { // show the filter warning bar if the filter is set if (Settings.getCacheType() != CacheType.ALL) { String cacheType = Settings.getCacheType().getL10n(); ((TextView) activity.findViewById(R.id.filter_text)).setText(cacheType); activity.findViewById(R.id.filter_bar).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.filter_bar).setVisibility(View.GONE); } } @Override public void onResume() { super.onResume(); addGeoDirObservers(); if (!CollectionUtils.isEmpty(dirtyCaches)) { for (String geocode : dirtyCaches) { cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); // remove to update the cache caches.remove(cache); caches.add(cache); } dirtyCaches.clear(); // Update display displayExecutor.execute(new DisplayRunnable(mapView.getViewport())); } startTimer(); } private void addGeoDirObservers() { geoDirUpdate.startGeoAndDir(); } private void deleteGeoDirObservers() { geoDirUpdate.stopGeoAndDir(); } @Override public void onPause() { if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } deleteGeoDirObservers(); savePrefs(); if (mapView != null) { mapView.destroyDrawingCache(); } overlaysCache.clear(); super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(R.drawable.ic_menu_mapmode); addMapViewMenuItems(submenu); menu.add(0, MENU_MAP_LIVE, 0, res.getString(R.string.map_live_disable)).setIcon(R.drawable.ic_menu_refresh); menu.add(0, MENU_STORE_CACHES, 0, res.getString(R.string.caches_store_offline)).setIcon(R.drawable.ic_menu_set_as).setEnabled(false); menu.add(0, MENU_TRAIL_MODE, 0, res.getString(R.string.map_trail_hide)).setIcon(R.drawable.ic_menu_trail); Strategy strategy = Settings.getLiveMapStrategy(); SubMenu subMenuStrategy = menu.addSubMenu(0, SUBMENU_STRATEGY, 0, res.getString(R.string.map_strategy)).setIcon(R.drawable.ic_menu_preferences); subMenuStrategy.setHeaderTitle(res.getString(R.string.map_strategy_title)); subMenuStrategy.add(2, MENU_STRATEGY_FASTEST, 0, Strategy.FASTEST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FASTEST); subMenuStrategy.add(2, MENU_STRATEGY_FAST, 0, Strategy.FAST.getL10n()).setCheckable(true).setChecked(strategy == Strategy.FAST); subMenuStrategy.add(2, MENU_STRATEGY_AUTO, 0, Strategy.AUTO.getL10n()).setCheckable(true).setChecked(strategy == Strategy.AUTO); subMenuStrategy.add(2, MENU_STRATEGY_DETAILED, 0, Strategy.DETAILED.getL10n()).setCheckable(true).setChecked(strategy == Strategy.DETAILED); subMenuStrategy.setGroupCheckable(2, true, true); menu.add(0, MENU_CIRCLE_MODE, 0, res.getString(R.string.map_circles_hide)).setIcon(R.drawable.ic_menu_circle); menu.add(0, MENU_AS_LIST, 0, res.getString(R.string.map_as_list)).setIcon(R.drawable.ic_menu_agenda); return true; } private static void addMapViewMenuItems(final Menu menu) { MapProviderFactory.addMapviewMenuItems(menu, 1, Settings.getMapSource()); menu.setGroupCheckable(1, true, true); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); for (Integer mapSourceId : MapProviderFactory.getMapSources().keySet()) { final MenuItem menuItem = menu.findItem(mapSourceId); if (menuItem != null) { final MapSource mapSource = MapProviderFactory.getMapSource(mapSourceId); if (mapSource != null) { menuItem.setEnabled(mapSource.isAvailable()); } } } MenuItem item; try { item = menu.findItem(MENU_TRAIL_MODE); // show trail if (Settings.isMapTrail()) { item.setTitle(res.getString(R.string.map_trail_hide)); } else { item.setTitle(res.getString(R.string.map_trail_show)); } item = menu.findItem(MENU_MAP_LIVE); // live map if (mapMode == MapMode.LIVE_ONLINE) { item.setTitle(res.getString(R.string.map_live_disable)); } else { item.setTitle(res.getString(R.string.map_live_enable)); } final Set<String> geocodesInViewport = getGeocodesForCachesInViewport(); menu.findItem(MENU_STORE_CACHES).setEnabled(!isLoading() && CollectionUtils.isNotEmpty(geocodesInViewport) && app.hasUnsavedCaches(new SearchResult(geocodesInViewport))); item = menu.findItem(MENU_CIRCLE_MODE); // show circles if (overlayCaches != null && overlayCaches.getCircles()) { item.setTitle(res.getString(R.string.map_circles_hide)); } else { item.setTitle(res.getString(R.string.map_circles_show)); } menu.findItem(MENU_AS_LIST).setEnabled(isLiveMode() && !isLoading()); menu.findItem(SUBMENU_STRATEGY).setEnabled(isLiveMode()); } catch (Exception e) { Log.e("cgeomap.onPrepareOptionsMenu: " + e); } return true; } private boolean isLiveMode() { return mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE; } @Override public boolean onOptionsItemSelected(MenuItem item) { final int id = item.getItemId(); switch (id) { case MENU_TRAIL_MODE: Settings.setMapTrail(!Settings.isMapTrail()); ActivityMixin.invalidateOptionsMenu(activity); return true; case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE; liveChanged = true; lastSearchResult = null; searchIntent = null; ActivityMixin.invalidateOptionsMenu(activity); return true; case MENU_STORE_CACHES: if (!isLoading()) { final Set<String> geocodesInViewport = getGeocodesForCachesInViewport(); final List<String> geocodes = new ArrayList<String>(); for (final String geocode : geocodesInViewport) { if (!app.isOffline(geocode, null)) { geocodes.add(geocode); } } detailTotal = geocodes.size(); detailProgress = 0; if (detailTotal == 0) { ActivityMixin.showToast(activity, res.getString(R.string.warn_save_nothing)); return true; } final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(); waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage()); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { try { if (loadDetailsThread != null) { loadDetailsThread.stopIt(); } geoDirUpdate.startDir(); } catch (Exception e) { Log.e("cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); } } }); float etaTime = detailTotal * 7.0f / 60.0f; int roundedEta = Math.round(etaTime); if (etaTime < 0.4) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + roundedEta + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta)); } waitDialog.show(); detailProgressTime = System.currentTimeMillis(); loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes); loadDetailsThread.start(); } return true; case MENU_CIRCLE_MODE: if (overlayCaches == null) { return false; } overlayCaches.switchCircles(); mapView.repaintRequired(overlayCaches); ActivityMixin.invalidateOptionsMenu(activity); return true; case MENU_AS_LIST: { cgeocaches.startActivityMap(activity, new SearchResult(getGeocodesForCachesInViewport())); return true; } case MENU_STRATEGY_FASTEST: { item.setChecked(true); Settings.setLiveMapStrategy(Strategy.FASTEST); return true; } case MENU_STRATEGY_FAST: { item.setChecked(true); Settings.setLiveMapStrategy(Strategy.FAST); return true; } case MENU_STRATEGY_AUTO: { item.setChecked(true); Settings.setLiveMapStrategy(Strategy.AUTO); return true; } case MENU_STRATEGY_DETAILED: { item.setChecked(true); Settings.setLiveMapStrategy(Strategy.DETAILED); return true; } default: int mapSource = MapProviderFactory.getMapSourceFromMenuId(id); if (MapProviderFactory.isValidSourceId(mapSource)) { item.setChecked(true); changeMapSource(mapSource); return true; } } return false; } /** * @return a Set of geocodes corresponding to the caches that are shown on screen. */ private Set<String> getGeocodesForCachesInViewport() { final Set<String> geocodes = new HashSet<String>(); final List<cgCache> cachesProtected = caches.getAsList(); final Viewport viewport = mapView.getViewport(); for (final cgCache cache : cachesProtected) { if (viewport.contains(cache)) { geocodes.add(cache.getGeocode()); } } return geocodes; } /** * Restart the current activity if the map provider has changed, or change the map source if needed. * * @param mapSource * the new map source, which can be the same as the current one * @return true if a restart is needed, false otherwise */ private boolean changeMapSource(final int mapSource) { // If the current or the requested map source is invalid, request the first available map source instead // and restart the activity. if (!MapProviderFactory.isValidSourceId(mapSource)) { Log.e("CGeoMap.onCreate: invalid map source requested: " + mapSource); currentSourceId = MapProviderFactory.getSourceIdFromOrdinal(0); Settings.setMapSource(currentSourceId); mapRestart(); return true; } final boolean restartRequired = !MapProviderFactory.isSameActivity(currentSourceId, mapSource); Settings.setMapSource(mapSource); currentSourceId = mapSource; if (restartRequired) { mapRestart(); } else if (mapView != null) { mapView.setMapSource(); } return restartRequired; } /** * Restart the current activity with the default map source. */ private void mapRestart() { // close old mapview activity.finish(); // prepare information to restart a similar view Intent mapIntent = new Intent(activity, Settings.getMapProvider().getMapClass()); mapIntent.putExtra(EXTRAS_SEARCH, searchIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_COORDS, coordsIntent); } mapIntent.putExtra(EXTRAS_WPTTYPE, waypointTypeIntent != null ? waypointTypeIntent.id : null); mapIntent.putExtra(EXTRAS_MAP_TITLE, mapTitle); mapIntent.putExtra(EXTRAS_MAP_MODE, mapMode); final int[] mapState = currentMapState(); if (mapState != null) { mapIntent.putExtra(EXTRAS_MAPSTATE, mapState); } // start the new map activity.startActivity(mapIntent); } /** * Get the current map state from the map view if it exists or from the mapStateIntent field otherwise. * * @return the current map state as an array of int, or null if no map state is available */ private int[] currentMapState() { if (mapView == null) { return mapStateIntent; } final GeoPointImpl mapCenter = mapView.getMapViewCenter(); return new int[] { mapCenter.getLatitudeE6(), mapCenter.getLongitudeE6(), mapView.getMapZoomLevel(), followMyLocation ? 1 : 0, overlayCaches.getCircles() ? 1 : 0 }; } private void savePrefs() { if (mapView == null) { return; } Settings.setMapZoom(mapView.getMapZoomLevel()); Settings.setMapCenter(mapView.getMapViewCenter()); } // Set center of map to my location if appropriate. private void myLocationInMiddle(final IGeoData geo) { if (followMyLocation && !geo.isPseudoLocation()) { centerMap(geo.getCoords()); } } // class: update location private class UpdateLoc extends GeoDirHandler { // use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible // minimum time in milliseconds between position overlay updates private static final long MIN_UPDATE_INTERVAL = 500; // minimum change of heading in grad for position overlay update private static final float MIN_HEADING_DELTA = 15f; // minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update private static final float MIN_LOCATION_DELTA = 0.01f; Location currentLocation = new Location(""); boolean locationValid = false; float currentHeading; private long timeLastPositionOverlayCalculation = 0; @Override protected void updateGeoData(final IGeoData geo) { if (geo.isPseudoLocation()) { locationValid = false; } else { locationValid = true; currentLocation = geo.getLocation(); if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h currentHeading = geo.getBearing(); } repaintPositionOverlay(); } } @Override public void updateDirection(final float direction) { if (app.currentGeo().getSpeed() <= 5) { // use compass when speed is lower than 18 km/h currentHeading = DirectionProvider.getDirectionNow(activity, direction); repaintPositionOverlay(); } } /** * Repaint position overlay but only with a max frequency and if position or heading changes sufficiently. */ void repaintPositionOverlay() { final long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) { timeLastPositionOverlayCalculation = currentTimeMillis; try { if (mapView != null) { if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } boolean needsRepaintForDistance = needsRepaintForDistance(); boolean needsRepaintForHeading = needsRepaintForHeading(); if (needsRepaintForDistance) { if (followMyLocation) { centerMap(new Geopoint(currentLocation)); } } if (needsRepaintForDistance || needsRepaintForHeading) { overlayPosition.setCoordinates(currentLocation); overlayPosition.setHeading(currentHeading); mapView.repaintRequired(overlayPosition); } } } catch (Exception e) { Log.w("Failed to update location."); } } } boolean needsRepaintForHeading() { return Math.abs(AngleUtils.difference(currentHeading, overlayPosition.getHeading())) > MIN_HEADING_DELTA; } boolean needsRepaintForDistance() { if (!locationValid) { return false; } final Location lastLocation = overlayPosition.getCoordinates(); float dist = Float.MAX_VALUE; if (lastLocation != null) { dist = currentLocation.distanceTo(lastLocation); } final float[] mapDimension = new float[1]; if (mapView.getWidth() < mapView.getHeight()) { final double span = mapView.getLongitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension); } else { final double span = mapView.getLatitudeSpan() / 1e6; Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension); } return dist > (mapDimension[0] * MIN_LOCATION_DELTA); } } /** * Starts the {@link LoadTimer}. */ public synchronized void startTimer() { if (coordsIntent != null) { // display just one point (new DisplayPointThread()).start(); } else { // start timer if (loadTimer != null) { loadTimer.stopIt(); loadTimer = null; } loadTimer = new LoadTimer(); loadTimer.start(); } } /** * loading timer Triggers every 250ms and checks for viewport change and starts a {@link LoadRunnable}. */ private class LoadTimer extends Thread { public LoadTimer() { super("Load Timer"); } private volatile boolean stop = false; public void stopIt() { stop = true; } @Override public void run() { while (!stop) { try { sleep(250); if (mapView != null) { // get current viewport final Viewport viewportNow = mapView.getViewport(); // Since zoomNow is used only for local comparison purposes, // it is ok to use the Google Maps compatible zoom level of OSM Maps final int zoomNow = mapView.getMapZoomLevel(); // check if map moved or zoomed //TODO Portree Use Rectangle inside with bigger search window. That will stop reloading on every move boolean moved = false; if (liveChanged) { moved = true; } else if (mapMode == MapMode.LIVE_ONLINE && !downloaded) { moved = true; } else if (viewport == null) { moved = true; } else if (zoomNow != zoom) { moved = true; } else if (mapMoved(viewport, viewportNow) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !viewport.includes(viewportNow))) { moved = true; } // update title on any change if (moved || zoomNow != zoom || !viewportNow.equals(viewport)) { displayHandler.sendEmptyMessage(UPDATE_TITLE); } zoom = zoomNow; // save new values if (moved) { liveChanged = false; long currentTime = System.currentTimeMillis(); if (1000 < (currentTime - loadThreadRun)) { viewport = viewportNow; loadExecutor.execute(new LoadRunnable(viewport)); } } } yield(); } catch (Exception e) { Log.w("cgeomap.LoadTimer.run: " + e.toString()); } } } public boolean isLoading() { return loadExecutor.getActiveCount() > 0 || downloadExecutor.getActiveCount() > 0 || displayExecutor.getActiveCount() > 0; } } /** * Worker thread that loads caches and waypoints from the database and then spawns the {@link DownloadRunnable}. * started by {@link LoadTimer} */ private class LoadRunnable extends DoRunnable { public LoadRunnable(final Viewport viewport) { super(viewport); } @Override public void run() { try { showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); loadThreadRun = System.currentTimeMillis(); SearchResult searchResult; // stage 1 - pull and render from the DB only for live map if (mapMode == MapMode.LIVE_ONLINE) { searchResult = new SearchResult(app.getCachedInViewport(viewport, Settings.getCacheType())); } else if (mapMode == MapMode.LIVE_OFFLINE) { searchResult = new SearchResult(app.getStoredInViewport(viewport, Settings.getCacheType())); } else { // map started from another activity searchResult = new SearchResult(searchIntent); if (geocodeIntent != null) { searchResult.addGeocode(geocodeIntent); } } downloaded = true; Set<cgCache> cachesFromSearchResult = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_WAYPOINTS); // to update the caches they have to be removed first caches.removeAll(cachesFromSearchResult); caches.addAll(cachesFromSearchResult); if (isLiveMode()) { final boolean excludeMine = Settings.isExcludeMyCaches(); final boolean excludeDisabled = Settings.isExcludeDisabledCaches(); final List<cgCache> tempList = caches.getAsList(); for (cgCache cache : tempList) { if ((cache.isFound() && excludeMine) || (cache.isOwn() && excludeMine) || (cache.isDisabled() && excludeDisabled)) { caches.remove(cache); } } } countVisibleCaches(); if (cachesCnt < Settings.getWayPointsThreshold() || geocodeIntent != null) { waypoints.clear(); if (isLiveMode() || mapMode == MapMode.COORDS) { //All visible waypoints CacheType type = Settings.getCacheType(); Set<cgWaypoint> waypointsInViewport = app.getWaypointsInViewport(viewport, Settings.isExcludeMyCaches(), Settings.isExcludeDisabledCaches(), type); waypoints.addAll(waypointsInViewport); } else { //All waypoints from the viewed caches for (cgCache c : caches.getAsList()) { waypoints.addAll(c.getWaypoints()); } } } //render displayExecutor.execute(new DisplayRunnable(viewport)); if (mapMode == MapMode.LIVE_ONLINE) { downloadExecutor.execute(new DownloadRunnable(viewport)); } lastSearchResult = searchResult; } finally { showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress } } } /** * Worker thread downloading caches from the internet. * Started by {@link LoadRunnable}. */ private class DownloadRunnable extends DoRunnable { public DownloadRunnable(final Viewport viewport) { super(viewport); } @Override public void run() { try { showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); // show progress int count = 0; SearchResult searchResult; do { if (tokens == null) { tokens = Login.getMapTokens(); if (noMapTokenHandler != null && tokens == null) { noMapTokenHandler.sendEmptyMessage(0); } } searchResult = ConnectorFactory.searchByViewport(viewport.resize(0.8), tokens); if (searchResult != null) { downloaded = true; if (searchResult.getError() == StatusCode.NOT_LOGGED_IN) { Login.login(); tokens = null; } else { break; } } count++; } while (count < 2); if (searchResult != null) { Set<cgCache> result = searchResult.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB); // to update the caches they have to be removed first caches.removeAll(result); caches.addAll(result); lastSearchResult = searchResult; } //render displayExecutor.execute(new DisplayRunnable(viewport)); } catch (ThreadDeath e) { Log.d("DownloadThread stopped"); displayHandler.sendEmptyMessage(UPDATE_TITLE); } finally { showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); // hide progress } } } /** * Thread to Display (down)loaded caches. Started by {@link LoadRunnable} and {@link DownloadRunnable} */ private class DisplayRunnable extends DoRunnable { public DisplayRunnable(final Viewport viewport) { super(viewport); } @Override public void run() { try { showProgressHandler.sendEmptyMessage(SHOW_PROGRESS); if (mapView == null || caches == null) { throw new ThreadDeath(); } // display caches final List<cgCache> cachesToDisplay = caches.getAsList(); final List<cgWaypoint> waypointsToDisplay = new ArrayList<cgWaypoint>(waypoints); final List<CachesOverlayItemImpl> itemsToDisplay = new ArrayList<CachesOverlayItemImpl>(); if (!cachesToDisplay.isEmpty()) { // Only show waypoints for single view or setting // when less than showWaypointsthreshold Caches shown if (mapMode == MapMode.SINGLE || (cachesCnt < Settings.getWayPointsThreshold())) { for (cgWaypoint waypoint : waypointsToDisplay) { if (waypoint == null || waypoint.getCoords() == null) { continue; } itemsToDisplay.add(getItem(waypoint, null, waypoint)); } } for (cgCache cache : cachesToDisplay) { if (cache == null || cache.getCoords() == null) { continue; } itemsToDisplay.add(getItem(cache, cache, null)); } overlayCaches.updateItems(itemsToDisplay); displayHandler.sendEmptyMessage(INVALIDATE_MAP); } else { overlayCaches.updateItems(itemsToDisplay); displayHandler.sendEmptyMessage(INVALIDATE_MAP); } displayHandler.sendEmptyMessage(UPDATE_TITLE); } catch (ThreadDeath e) { Log.d("DisplayThread stopped"); displayHandler.sendEmptyMessage(UPDATE_TITLE); } finally { showProgressHandler.sendEmptyMessage(HIDE_PROGRESS); } } } /** * Thread to display one point. Started on opening if in single mode. */ private class DisplayPointThread extends Thread { @Override public void run() { if (mapView == null || caches == null) { return; } if (coordsIntent != null) { final cgWaypoint waypoint = new cgWaypoint("some place", waypointTypeIntent != null ? waypointTypeIntent : WaypointType.WAYPOINT, false); waypoint.setCoords(coordsIntent); final CachesOverlayItemImpl item = getItem(waypoint, null, waypoint); overlayCaches.updateItems(item); displayHandler.sendEmptyMessage(INVALIDATE_MAP); cachesCnt = 1; } else { cachesCnt = 0; } displayHandler.sendEmptyMessage(UPDATE_TITLE); } } private static abstract class DoRunnable implements Runnable { final protected Viewport viewport; public DoRunnable(final Viewport viewport) { this.viewport = viewport; } @Override public abstract void run(); } /** * get if map is loading something * * @return */ private synchronized boolean isLoading() { if (loadTimer != null) { return loadTimer.isLoading(); } return false; } /** * Thread to store the caches in the viewport. Started by Activity. */ private class LoadDetails extends Thread { final private CancellableHandler handler; final private List<String> geocodes; private long last = 0L; public LoadDetails(final CancellableHandler handler, final List<String> geocodes) { this.handler = handler; this.geocodes = geocodes; } public void stopIt() { handler.cancel(); } @Override public void run() { if (CollectionUtils.isEmpty(geocodes)) { return; } deleteGeoDirObservers(); for (final String geocode : geocodes) { try { if (handler.isCancelled()) { break; } if (!app.isOffline(geocode, null)) { if ((System.currentTimeMillis() - last) < 1500) { try { int delay = 1000 + (int) (Math.random() * 1000.0) - (int) (System.currentTimeMillis() - last); if (delay < 0) { delay = 500; } sleep(delay); } catch (Exception e) { // nothing } } if (handler.isCancelled()) { Log.i("Stopped storing process."); break; } cgCache.storeCache(null, geocode, StoredList.STANDARD_LIST_ID, false, handler); } } catch (Exception e) { Log.e("cgeocaches.LoadDetails.run: " + e.toString()); } finally { // one more cache over detailProgress++; handler.sendEmptyMessage(UPDATE_PROGRESS); } // FIXME: what does this yield() do here? yield(); last = System.currentTimeMillis(); } // we're done handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); addGeoDirObservers(); } } private static boolean mapMoved(final Viewport referenceViewport, final Viewport newViewport) { return Math.abs(newViewport.getLatitudeSpan() - referenceViewport.getLatitudeSpan()) > 50e-6 || Math.abs(newViewport.getLongitudeSpan() - referenceViewport.getLongitudeSpan()) > 50e-6 || Math.abs(newViewport.center.getLatitude() - referenceViewport.center.getLatitude()) > referenceViewport.getLatitudeSpan() / 4 || Math.abs(newViewport.center.getLongitude() - referenceViewport.center.getLongitude()) > referenceViewport.getLongitudeSpan() / 4; } // center map to desired location private void centerMap(final Geopoint coords) { if (coords == null) { return; } if (mapView == null) { return; } final MapControllerImpl mapController = mapView.getMapController(); final GeoPointImpl target = makeGeoPoint(coords); if (alreadyCentered) { mapController.animateTo(target); } else { mapController.setCenter(target); } alreadyCentered = true; } // move map to view results of searchIntent private void centerMap(String geocodeCenter, final SearchResult searchCenter, final Geopoint coordsCenter, int[] mapState) { final MapControllerImpl mapController = mapView.getMapController(); if (!centered && mapState != null) { try { mapController.setCenter(mapItemFactory.getGeoPointBase(new Geopoint(mapState[0] / 1.0e6, mapState[1] / 1.0e6))); mapController.setZoom(mapState[2]); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && (geocodeCenter != null || searchIntent != null)) { try { Viewport viewport = null; if (geocodeCenter != null) { viewport = app.getBounds(geocodeCenter); } else if (searchCenter != null) { viewport = app.getBounds(searchCenter.getGeocodes()); } if (viewport == null) { return; } mapController.setCenter(mapItemFactory.getGeoPointBase(viewport.center)); if (viewport.getLatitudeSpan() != 0 && viewport.getLongitudeSpan() != 0) { mapController.zoomToSpan((int) (viewport.getLatitudeSpan() * 1e6), (int) (viewport.getLongitudeSpan() * 1e6)); } } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } else if (!centered && coordsCenter != null) { try { mapController.setCenter(makeGeoPoint(coordsCenter)); } catch (Exception e) { // nothing at all } centered = true; alreadyCentered = true; } } // switch My Location button image private void switchMyLocationButton() { if (followMyLocation) { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on); myLocationInMiddle(app.currentGeo()); } else { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off); } } // set my location listener private class MyLocationListener implements View.OnClickListener { @Override public void onClick(View view) { followMyLocation = !followMyLocation; switchMyLocationButton(); } } @Override public void onDrag() { if (followMyLocation) { followMyLocation = false; switchMyLocationButton(); } } // make geopoint private GeoPointImpl makeGeoPoint(final Geopoint coords) { return mapItemFactory.getGeoPointBase(coords); } // close activity and open homescreen @Override public void goHome(View view) { ActivityMixin.goHome(activity); } // open manual entry @Override public void goManual(View view) { ActivityMixin.goManual(activity, "c:geo-live-map"); } @Override public View makeView() { ImageView imageView = new ImageView(activity); imageView.setScaleType(ScaleType.CENTER); imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); return imageView; } private static Intent newIntent(final Context context) { return new Intent(context, Settings.getMapProvider().getMapClass()); } public static void startActivitySearch(final Activity fromActivity, final SearchResult search, final String title) { final Intent mapIntent = newIntent(fromActivity); mapIntent.putExtra(EXTRAS_SEARCH, search); mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.LIST); if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title); } fromActivity.startActivity(mapIntent); } public static void startActivityLiveMap(final Activity fromActivity) { final Intent mapIntent = newIntent(fromActivity); mapIntent.putExtra(EXTRAS_MAP_MODE, Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE); fromActivity.startActivity(mapIntent); } public static void startActivityCoords(final Activity fromActivity, final Geopoint coords, final WaypointType type, final String title) { final Intent mapIntent = newIntent(fromActivity); mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.COORDS); mapIntent.putExtra(EXTRAS_COORDS, coords); if (type != null) { mapIntent.putExtra(EXTRAS_WPTTYPE, type.id); } if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(EXTRAS_MAP_TITLE, title); } fromActivity.startActivity(mapIntent); } public static void startActivityGeoCode(final Activity fromActivity, final String geocode) { final Intent mapIntent = newIntent(fromActivity); mapIntent.putExtra(EXTRAS_MAP_MODE, MapMode.SINGLE); mapIntent.putExtra(EXTRAS_GEOCODE, geocode); mapIntent.putExtra(EXTRAS_MAP_TITLE, geocode); fromActivity.startActivity(mapIntent); } public static void markCacheAsDirty(final String geocode) { if (dirtyCaches == null) { dirtyCaches = new HashSet<String>(); } dirtyCaches.add(geocode); } /** * Returns a OverlayItem represented by an icon * * @param coord * The coords * @param cache * Cache * @param waypoint * Waypoint. Mutally exclusive with cache * @return */ private CachesOverlayItemImpl getItem(final IWaypoint coord, final cgCache cache, final cgWaypoint waypoint) { if (cache != null) { final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, cache.getType()); final int hashcode = new HashCodeBuilder() .append(cache.isReliableLatLon()) .append(cache.getType().id) .append(cache.isDisabled() || cache.isArchived()) .append(cache.isOwn()) .append(cache.isFound()) .append(cache.hasUserModifiedCoords()) .append(cache.getPersonalNote()) .append(cache.isLogOffline()) .append(cache.getListId() > 0) .toHashCode(); final LayerDrawable ldFromCache = overlaysCache.get(hashcode); if (ldFromCache != null) { item.setMarker(ldFromCache); return item; } // Set initial capacities to the maximum of layers and insets to avoid dynamic reallocation final ArrayList<Drawable> layers = new ArrayList<Drawable>(9); final ArrayList<int[]> insets = new ArrayList<int[]>(8); // background: disabled or not final Drawable marker = getResources().getDrawable(cache.isDisabled() || cache.isArchived() ? R.drawable.marker_disabled : R.drawable.marker); layers.add(marker); final int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0; // reliable or not if (!cache.isReliableLatLon()) { insets.add(INSET_RELIABLE[resolution]); layers.add(getResources().getDrawable(R.drawable.marker_notreliable)); } // cache type layers.add(getResources().getDrawable(cache.getType().markerId)); insets.add(INSET_TYPE[resolution]); // own if (cache.isOwn()) { layers.add(getResources().getDrawable(R.drawable.marker_own)); insets.add(INSET_OWN[resolution]); // if not, checked if stored } else if (cache.getListId() > 0) { layers.add(getResources().getDrawable(R.drawable.marker_stored)); insets.add(INSET_OWN[resolution]); } // found if (cache.isFound()) { layers.add(getResources().getDrawable(R.drawable.marker_found)); insets.add(INSET_FOUND[resolution]); // if not, perhaps logged offline } else if (cache.isLogOffline()) { layers.add(getResources().getDrawable(R.drawable.marker_found_offline)); insets.add(INSET_FOUND[resolution]); } // user modified coords if (cache.hasUserModifiedCoords()) { layers.add(getResources().getDrawable(R.drawable.marker_usermodifiedcoords)); insets.add(INSET_USERMODIFIEDCOORDS[resolution]); } // personal note if (cache.getPersonalNote() != null) { layers.add(getResources().getDrawable(R.drawable.marker_personalnote)); insets.add(INSET_PERSONALNOTE[resolution]); } final LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()])); int index = 1; for (final int[] inset : insets) { ld.setLayerInset(index++, inset[0], inset[1], inset[2], inset[3]); } overlaysCache.put(hashcode, ld); item.setMarker(ld); return item; } if (waypoint != null) { final CachesOverlayItemImpl item = mapItemFactory.getCachesOverlayItem(coord, null); Drawable[] layers = new Drawable[2]; layers[0] = getResources().getDrawable(R.drawable.marker); layers[1] = getResources().getDrawable(waypoint.getWaypointType().markerId); LayerDrawable ld = new LayerDrawable(layers); if (layers[0].getIntrinsicWidth() > 40) { ld.setLayerInset(1, 9, 12, 10, 13); } else { ld.setLayerInset(1, 9, 12, 8, 12); } item.setMarker(ld); return item; } return null; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // class init res = this.getResources(); activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL); caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt); final MapProvider mapProvider = Settings.getMapProvider(); mapItemFactory = mapProvider.getMapItemFactory(); // Get parameters from the intent final Bundle extras = activity.getIntent().getExtras(); if (extras != null) { mapMode = (MapMode) extras.get(EXTRAS_MAP_MODE); searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH); geocodeIntent = extras.getString(EXTRAS_GEOCODE); coordsIntent = (Geopoint) extras.getParcelable(EXTRAS_COORDS); waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE)); mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE; } if (StringUtils.isBlank(mapTitle)) { mapTitle = res.getString(R.string.map_map); } // Get fresh map information from the bundle if any if (savedInstanceState != null) { currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource()); mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE); if (savedInstanceState.getString(BUNDLE_MAP_MODE) != null) { mapMode = Enum.valueOf(MapMode.class, savedInstanceState.getString(BUNDLE_MAP_MODE)); } Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { currentSourceId = Settings.getMapSource(); } // If recreating from an obsolete map source, we may need a restart if (changeMapSource(Settings.getMapSource())) { return; } // reset status noMapTokenShowed = false; ActivityMixin.keepScreenOn(activity, true); // set layout ActivityMixin.setTheme(activity); activity.setContentView(mapProvider.getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); // initialize map mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId()); mapView.setMapSource(); mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); mapView.preLoad(); mapView.setOnDragListener(this); // initialize overlays mapView.clearOverlays(); if (overlayCaches == null) { overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker)); } if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (overlayScale == null) { overlayScale = mapView.createAddScaleOverlay(activity); } mapView.repaintRequired(null); mapView.getMapController().setZoom(Settings.getMapZoom()); mapView.getMapController().setCenter(Settings.getMapCenter()); if (null == mapStateIntent) { followMyLocation = mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE; } else { followMyLocation = 1 == mapStateIntent[3]; if ((overlayCaches.getCircles() ? 1 : 0) != mapStateIntent[4]) { overlayCaches.switchCircles(); } } if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) { centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent); } // prepare my location button myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position); myLocSwitch.setFactory(this); myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); myLocSwitch.setOnClickListener(new MyLocationListener()); switchMyLocationButton(); prepareFilterBar(); if (!app.isLiveMapHintShown() && !Settings.getHideLiveMapHint()) { Intent hintIntent = new Intent(activity, LiveMapInfo.class); activity.startActivity(hintIntent); app.setLiveMapHintShown(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // class init res = this.getResources(); activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL); caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt); final MapProvider mapProvider = Settings.getMapProvider(); mapItemFactory = mapProvider.getMapItemFactory(); // Get parameters from the intent final Bundle extras = activity.getIntent().getExtras(); if (extras != null) { mapMode = (MapMode) extras.get(EXTRAS_MAP_MODE); searchIntent = (SearchResult) extras.getParcelable(EXTRAS_SEARCH); geocodeIntent = extras.getString(EXTRAS_GEOCODE); coordsIntent = (Geopoint) extras.getParcelable(EXTRAS_COORDS); waypointTypeIntent = WaypointType.findById(extras.getString(EXTRAS_WPTTYPE)); mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { mapMode = Settings.isLiveMap() ? MapMode.LIVE_ONLINE : MapMode.LIVE_OFFLINE; } if (StringUtils.isBlank(mapTitle)) { mapTitle = res.getString(R.string.map_map); } // Get fresh map information from the bundle if any if (savedInstanceState != null) { currentSourceId = savedInstanceState.getInt(BUNDLE_MAP_SOURCE, Settings.getMapSource()); mapStateIntent = savedInstanceState.getIntArray(BUNDLE_MAP_STATE); String lastMapmode = savedInstanceState.getString(BUNDLE_MAP_MODE); if (lastMapmode != null) { mapMode = Enum.valueOf(MapMode.class, lastMapmode); } Settings.setLiveMap(mapMode == MapMode.LIVE_ONLINE); } else { currentSourceId = Settings.getMapSource(); } // If recreating from an obsolete map source, we may need a restart if (changeMapSource(Settings.getMapSource())) { return; } // reset status noMapTokenShowed = false; ActivityMixin.keepScreenOn(activity, true); // set layout ActivityMixin.setTheme(activity); activity.setContentView(mapProvider.getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); // initialize map mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId()); mapView.setMapSource(); mapView.setBuiltInZoomControls(true); mapView.displayZoomControls(true); mapView.preLoad(); mapView.setOnDragListener(this); // initialize overlays mapView.clearOverlays(); if (overlayCaches == null) { overlayCaches = mapView.createAddMapOverlay(mapView.getContext(), getResources().getDrawable(R.drawable.marker)); } if (overlayPosition == null) { overlayPosition = mapView.createAddPositionOverlay(activity); } if (overlayScale == null) { overlayScale = mapView.createAddScaleOverlay(activity); } mapView.repaintRequired(null); mapView.getMapController().setZoom(Settings.getMapZoom()); mapView.getMapController().setCenter(Settings.getMapCenter()); if (null == mapStateIntent) { followMyLocation = mapMode == MapMode.LIVE_OFFLINE || mapMode == MapMode.LIVE_ONLINE; } else { followMyLocation = 1 == mapStateIntent[3]; if ((overlayCaches.getCircles() ? 1 : 0) != mapStateIntent[4]) { overlayCaches.switchCircles(); } } if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) { centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent); } // prepare my location button myLocSwitch = (ImageSwitcher) activity.findViewById(R.id.my_position); myLocSwitch.setFactory(this); myLocSwitch.setInAnimation(activity, android.R.anim.fade_in); myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out); myLocSwitch.setOnClickListener(new MyLocationListener()); switchMyLocationButton(); prepareFilterBar(); if (!app.isLiveMapHintShown() && !Settings.getHideLiveMapHint()) { Intent hintIntent = new Intent(activity, LiveMapInfo.class); activity.startActivity(hintIntent); app.setLiveMapHintShown(); } }
diff --git a/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java b/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java index 988f278..a1891ae 100644 --- a/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java +++ b/src/main/java/com/github/kpacha/jkata/anagram/Anagram.java @@ -1,13 +1,16 @@ package com.github.kpacha.jkata.anagram; import java.util.HashSet; import java.util.Set; public class Anagram { public static Set<String> generate(String source) { Set<String> result = new HashSet<String>(); + if (source.length() == 2) { + result.add(source.substring(1) + source.substring(0, 1)); + } result.add(source); return result; } }
true
true
public static Set<String> generate(String source) { Set<String> result = new HashSet<String>(); result.add(source); return result; }
public static Set<String> generate(String source) { Set<String> result = new HashSet<String>(); if (source.length() == 2) { result.add(source.substring(1) + source.substring(0, 1)); } result.add(source); return result; }
diff --git a/src/cc/hughes/droidchatty/SingleThreadView.java b/src/cc/hughes/droidchatty/SingleThreadView.java index 882fc98..1d1883c 100644 --- a/src/cc/hughes/droidchatty/SingleThreadView.java +++ b/src/cc/hughes/droidchatty/SingleThreadView.java @@ -1,22 +1,21 @@ package cc.hughes.droidchatty; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class SingleThreadView extends FragmentActivity { public static final String THREAD_ID = "threadId"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // create the fragment, and show it! ThreadViewFragment frag = new ThreadViewFragment(); frag.setArguments(getIntent().getExtras()); - getSupportFragmentManager().beginTransaction().add( - android.R.id.content, frag).commit(); + getSupportFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // create the fragment, and show it! ThreadViewFragment frag = new ThreadViewFragment(); frag.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().add( android.R.id.content, frag).commit(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // create the fragment, and show it! ThreadViewFragment frag = new ThreadViewFragment(); frag.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().replace(android.R.id.content, frag).commit(); }
diff --git a/Android/on.hovercraft.android/src/on/hovercraft/android/BtService.java b/Android/on.hovercraft.android/src/on/hovercraft/android/BtService.java index 4920b6c..ad11f66 100644 --- a/Android/on.hovercraft.android/src/on/hovercraft/android/BtService.java +++ b/Android/on.hovercraft.android/src/on/hovercraft/android/BtService.java @@ -1,551 +1,551 @@ package on.hovercraft.android; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import common.files.android.Constants; import common.files.android.Constants.ConnectionState; import android.annotation.SuppressLint; import android.app.IntentService; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.util.Log; public class BtService extends IntentService { private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final String NAME = "Bluetooth SPP"; public static ConnectionState connectionState = ConnectionState.DISCONNECTED; // BT connection state private boolean listenOnBtInputstream = false; /**< */ private BluetoothSocket bluetoothSocket; /**< */ private BluetoothServerSocket bluetoothServerSocket; /**< */ private BluetoothAdapter mBluetoothAdapter; /**< */ private InputStream btInputStream; /**< */ private OutputStream btOutStream; /**< */ private int bluetoothConnectionTimeout = 30000; /**< */ private boolean bluetoothServerUp = false; /**< */ private boolean bluetoothSocketUp = false; /**< */ private static String TAG = "JM"; /**< */ /** * \brief * * \author Johan Gustafsson * */ public BtService() { super("BtService"); } /** * \brief Update the Bluetooth connection state * * Description * * @param state * * \author Johan Gustafsson * */ private void updateBtConnectionState( ConnectionState state ) { if( connectionState != state ) { connectionState = state; Intent i = new Intent(Constants.Broadcast.BluetoothService.UPDATE_CONNECTION_STATE); i.putExtra("connectionState", state); sendBroadcast(i); } } /** * \brief * * Description * * * @param arg0 * * * \author Johan Gustafsson * */ @Override protected void onHandleIntent( Intent arg0 ) { Log.d(TAG, "BTService started"); registerReceiver(BtServiceReciever, new IntentFilter("callFunction")); while ( true ) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } if( listenOnBtInputstream ) { checkInput(); } } } /** * \brief * * * * * @param message * * * \author Johan Gustafsson * */ private void btConnectionLost( String message ) { listenOnBtInputstream = false; closeServerSocket(); if( btInputStream != null ) { try { btInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } broadcastMessage(message); updateBtConnectionState(ConnectionState.DISCONNECTED); } /** * \brief * * Desription * * \author Johan Gustafsson * */ private void closeServerSocket() { if( bluetoothServerUp ) { try { bluetoothServerSocket.close(); broadcastMessage("Server down..."); bluetoothServerUp = false; bluetoothSocketUp = false; } catch (IOException e) { broadcastMessage("Faild to close server..."); } } } /** * \brief * * Description * * * * @return bluetoothServerUp * * * \author Johan Gustafsson * */ private boolean setupServer() { // Use a temporary object that is later assigned to mmServerSocket, // because mmServerSocket is final mBluetoothAdapter = null; BluetoothServerSocket tmp = null; mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); try { // MY_UUID is the app's UUID string, also used by the client code tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID_INSECURE); broadcastMessage("Server up..."); bluetoothServerUp = true; updateBtConnectionState(ConnectionState.WAITING); } catch (IOException e) { btConnectionLost("Failed to create setup server..."); bluetoothServerUp = false; } bluetoothServerSocket = tmp; return bluetoothServerUp; } /** * \brief * * Description * * * * @return bluetoothSocketUp * * * \author Johan Gustafsson * */ private boolean waitToConnect() { if(bluetoothServerUp) { bluetoothSocket = null; try { bluetoothSocket = bluetoothServerSocket.accept(bluetoothConnectionTimeout); bluetoothSocketUp = true; broadcastMessage("Socket is up.."); updateBtConnectionState(ConnectionState.CONNECTED); listenOnBtInputStream(); } catch (IOException e) { btConnectionLost("Failed to connect..."); } } else { bluetoothSocketUp = false; } return bluetoothSocketUp; } /** * \brief * * Description * * * \author Johan Gustafsson * */ @SuppressLint("HandlerLeak") private void listenOnBtInputStream() { if( bluetoothSocketUp ) { try { btInputStream = bluetoothSocket.getInputStream(); broadcastMessage("Input stream open..."); listenOnBtInputstream = true; } catch (IOException e) { btConnectionLost("Failed to open input stream..."); listenOnBtInputstream = false; return; } } } /** * \brief Read the bluetooth input stream * * Description * * * * * \author Jens Moser * */ void checkInput() { byte[] bufferInfo = new byte[3]; try { bufferInfo[0] = (byte) btInputStream.read(); // Command bufferInfo[1] = (byte) btInputStream.read(); // Target bufferInfo[2] = (byte) btInputStream.read(); // Message length } catch (IOException e1) { btConnectionLost("Lost connection..."); Log.d(TAG,"BtService: BufferInfo read failed"); return; } byte[] bufferMessage = new byte[(int) bufferInfo[2]]; try { btInputStream.read(bufferMessage, 0, (int) bufferInfo[2]); } catch (IOException e1) { btConnectionLost("Lost connection..."); Log.d(TAG,"BtService: BufferMessage read failed"); return; } Log.d(TAG, "bufferInfo[0]"+bufferInfo[0]); Log.d(TAG, "bufferInfo[1]"+bufferInfo[1]); Log.d(TAG, "bufferInfo[2]"+bufferInfo[2]); // commands from ADK to this device if(Constants.TARGET_BRAIN == bufferInfo[1]) { handleBrainCommands(bufferInfo, bufferMessage); } // commands from remote to remote. Never used? else if(Constants.TARGET_REMOTE == bufferInfo[1]) { sendCommand(bufferInfo[0], bufferInfo[1], bufferMessage); } // commands from remote to ADK. else if(Constants.TARGET_ADK == bufferInfo[1]) { broadcastBufferToUSBService(bufferInfo, bufferMessage); } } /** * \brief * * * * * @param bufferInfo * * @param bufferMessage * * @return Description * * * \author Johan Gustafsson * */ private void broadcastBufferToUSBService( byte[] bufferInfo, byte[] bufferMessage ) { Log.d(TAG,"BtService: broadcast command to USB Service"); Intent intent = new Intent("handleBTCommands"); intent.putExtra("bufferInfo", bufferInfo); intent.putExtra("bufferMessage", bufferMessage); sendBroadcast(intent); } /** * \brief * * * * * @param bufferInfo * * @param bufferMessage * * * \author Johan Gustafsson * */ private void handleBrainCommands( byte[] bufferInfo, byte[] bufferMessage ) { Log.d(TAG,"BtService: handleBrainCommand"); switch (bufferInfo[0]) { case Constants.MOTOR_SIGNAL_COMMAND: Intent intent = new Intent(Constants.Broadcast.MotorSignals.REMOTE); intent.putExtra(Constants.Broadcast.BluetoothService.Actions.SendCommand.Intent.COMMAND, bufferInfo[0]); intent.putExtra(Constants.Broadcast.BluetoothService.Actions.SendCommand.Intent.BYTES, bufferMessage); intent.putExtra(Constants.Broadcast.BluetoothService.Actions.SendCommand.Intent.TARGET, bufferInfo[1]); sendBroadcast(intent); break; case Constants.ACC_BRAIN_SENSOR_REQ_COMMAND: Log.d(TAG, "READY TO GET ACC BRAIN DATA"); Intent accBrainIntent = new Intent("accBrainReq"); accBrainIntent.putExtra("send", true); sendBroadcast(accBrainIntent); break; case Constants.ACC_BRAIN_SENSOR_STOP_REQ_COMMAND: Log.d(TAG, "READY TO STOP ACC BRAIN DATA"); Intent accBrainStopIntent = new Intent("accBrainReq"); accBrainStopIntent.putExtra("send", false); sendBroadcast(accBrainStopIntent); break; default: Log.d(TAG, "unknown command: " + bufferInfo[0]); break; } } /** * \brief * * Description * * * @param command * * @param target * * @param message * * * \author Jens Moser * */ private void sendCommand(byte command, byte target, byte[] message) { Log.d(TAG,"BtService: SendCommand:" + (int) command); int byteLength = message.length; byte[] buffer = new byte[3+byteLength]; buffer[0] = command; // command buffer[1] = target; // target buffer[2] = (byte) byteLength; // length for (int x = 0; x < byteLength; x++) { buffer[3 + x] = message[x]; // message } Log.d(TAG,"byteLength:"+byteLength); try { btOutStream = bluetoothSocket.getOutputStream(); } catch (IOException e) { btConnectionLost("Lost connection..."); } if ( btOutStream != null ) { try { btOutStream.write(buffer); } catch (IOException e) { btConnectionLost("Lost connection..."); Log.e(TAG, "write failed", e); } } } /** * \brief * * * * * @param message * * * \author Johan Gustafsson * */ private void broadcastMessage(String message) { Intent i = new Intent("printMessage"); i.putExtra("message", message); sendBroadcast(i); } /** * \brief BtService BroadcastReceiver * * * * * @param context * * @param intent * * \author Johan Gustafsson * */ private final BroadcastReceiver BtServiceReciever = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //function called if(action.equalsIgnoreCase("callFunction")) { //witch function if(intent.hasExtra("setupServer")) { Log.d(TAG, "BtService: setupServer"); if( !bluetoothServerUp ) setupServer(); } if(intent.hasExtra("waitToConnect")) { if( !bluetoothSocketUp ) waitToConnect(); } if(intent.hasExtra("sendToRemote")) { if(intent.hasExtra("combinedInfoAndPB")) { byte[] infoAndPB = intent.getByteArrayExtra("combinedInfoAndPB"); byte command = infoAndPB[0]; byte target = infoAndPB[1]; int messageLength = (int)infoAndPB[2]; byte[] message = new byte[messageLength]; - for(int i = 0; i < messageLength - 3; i++) + for(int i = 0; i < messageLength; i++) { message[i] = infoAndPB[3 + i]; } if( bluetoothSocketUp ) sendCommand(command, target, message); } else if(intent.hasExtra("onlyMessage")) { byte[] message = intent.getByteArrayExtra("onlyMessage"); byte command = Constants.LOG_ACC_BRAIN_SENSOR_COMMAND; byte target = Constants.TARGET_REMOTE; if( bluetoothSocketUp ) sendCommand(command, target, message); } } } } }; }
true
true
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //function called if(action.equalsIgnoreCase("callFunction")) { //witch function if(intent.hasExtra("setupServer")) { Log.d(TAG, "BtService: setupServer"); if( !bluetoothServerUp ) setupServer(); } if(intent.hasExtra("waitToConnect")) { if( !bluetoothSocketUp ) waitToConnect(); } if(intent.hasExtra("sendToRemote")) { if(intent.hasExtra("combinedInfoAndPB")) { byte[] infoAndPB = intent.getByteArrayExtra("combinedInfoAndPB"); byte command = infoAndPB[0]; byte target = infoAndPB[1]; int messageLength = (int)infoAndPB[2]; byte[] message = new byte[messageLength]; for(int i = 0; i < messageLength - 3; i++) { message[i] = infoAndPB[3 + i]; } if( bluetoothSocketUp ) sendCommand(command, target, message); } else if(intent.hasExtra("onlyMessage")) { byte[] message = intent.getByteArrayExtra("onlyMessage"); byte command = Constants.LOG_ACC_BRAIN_SENSOR_COMMAND; byte target = Constants.TARGET_REMOTE; if( bluetoothSocketUp ) sendCommand(command, target, message); } } } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //function called if(action.equalsIgnoreCase("callFunction")) { //witch function if(intent.hasExtra("setupServer")) { Log.d(TAG, "BtService: setupServer"); if( !bluetoothServerUp ) setupServer(); } if(intent.hasExtra("waitToConnect")) { if( !bluetoothSocketUp ) waitToConnect(); } if(intent.hasExtra("sendToRemote")) { if(intent.hasExtra("combinedInfoAndPB")) { byte[] infoAndPB = intent.getByteArrayExtra("combinedInfoAndPB"); byte command = infoAndPB[0]; byte target = infoAndPB[1]; int messageLength = (int)infoAndPB[2]; byte[] message = new byte[messageLength]; for(int i = 0; i < messageLength; i++) { message[i] = infoAndPB[3 + i]; } if( bluetoothSocketUp ) sendCommand(command, target, message); } else if(intent.hasExtra("onlyMessage")) { byte[] message = intent.getByteArrayExtra("onlyMessage"); byte command = Constants.LOG_ACC_BRAIN_SENSOR_COMMAND; byte target = Constants.TARGET_REMOTE; if( bluetoothSocketUp ) sendCommand(command, target, message); } } } }
diff --git a/src/fresco/Main.java b/src/fresco/Main.java index 540ae4e..4db8389 100644 --- a/src/fresco/Main.java +++ b/src/fresco/Main.java @@ -1,22 +1,23 @@ /* * Part of Fresco software under GPL licence * http://www.gnu.org/licenses/gpl-3.0.txt */ package fresco; import fresco.swing.CAppWindow; /** * * @author gimli */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { + System.setProperty("apple.laf.useScreenMenuBar", "true"); CData.mainFrame = new CAppWindow("Fresco"); CData.mainFrame.setVisible(true); } }
true
true
public static void main(String[] args) { CData.mainFrame = new CAppWindow("Fresco"); CData.mainFrame.setVisible(true); }
public static void main(String[] args) { System.setProperty("apple.laf.useScreenMenuBar", "true"); CData.mainFrame = new CAppWindow("Fresco"); CData.mainFrame.setVisible(true); }
diff --git a/code/src/java/edu/stanford/cs224u/disentanglement/features/TFIDFFeatureFactory.java b/code/src/java/edu/stanford/cs224u/disentanglement/features/TFIDFFeatureFactory.java index 8437c13..96700c4 100644 --- a/code/src/java/edu/stanford/cs224u/disentanglement/features/TFIDFFeatureFactory.java +++ b/code/src/java/edu/stanford/cs224u/disentanglement/features/TFIDFFeatureFactory.java @@ -1,81 +1,81 @@ package edu.stanford.cs224u.disentanglement.features; import com.google.common.collect.*; import edu.stanford.cs224u.disentanglement.structures.Message; import edu.stanford.cs224u.disentanglement.structures.MessagePair; import edu.stanford.cs224u.disentanglement.util.WordTokenizer; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class TFIDFFeatureFactory extends AbstractFeatureFactory { @Override public Feature createFeature(List<Message> messages) { final ImmutableMap.Builder<String, Multiset<String>> tfCounterBuilder = ImmutableMap.builder(); final ImmutableMultiset.Builder<String> dfCounterBuilder = ImmutableMultiset.builder(); final int numMessages = messages.size(); for (Message s : messages) { Iterable<String> tokens = WordTokenizer.tokenizeWhitespace(s.getBody()); Multiset<String> counter = ImmutableMultiset.copyOf(tokens); tfCounterBuilder.put(s.getId(), counter); dfCounterBuilder.addAll(tokens); } return new Feature() { private final ImmutableMap<String, Multiset<String>> tfCounters = tfCounterBuilder.build(); private final ImmutableMultiset<String> dfCounter = dfCounterBuilder.build(); @Override public Map<Integer, Double> processExample(MessagePair example) { double totalTfIdf = 0.0; double tfIdf1Norm = 0.0; double tfIdf2Norm = 0.0; Set<String> commonWords = example.getWordIntersection(); for (String word : commonWords) { // Message 1 Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); - double tfIdf1 = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); + double tfIdf1 = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); // Message 2 counter = tfCounters.get(example.getSecond().getId()); it = Multisets.copyHighestCountFirst(counter).iterator(); maxFreq = counter.count(it.next()); freq = counter.count(word); - double tfIdf2 = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); + double tfIdf2 = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); totalTfIdf += tfIdf1 * tfIdf2; } for (String word : WordTokenizer.tokenizeWhitespace(example.getFirst().getBody())) { Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); - double tfIdf = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); + double tfIdf = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); tfIdf1Norm += tfIdf * tfIdf; } for (String word : WordTokenizer.tokenizeWhitespace(example.getSecond().getBody())) { Multiset<String> counter = tfCounters.get(example.getSecond().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); - double tfIdf = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); + double tfIdf = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); tfIdf2Norm += tfIdf * tfIdf; } return ImmutableMap.of(0, totalTfIdf / (Math.sqrt(tfIdf1Norm) * Math.sqrt(tfIdf2Norm))); } @Override public int getMaxLength() { return 1; } }; } }
false
true
public Feature createFeature(List<Message> messages) { final ImmutableMap.Builder<String, Multiset<String>> tfCounterBuilder = ImmutableMap.builder(); final ImmutableMultiset.Builder<String> dfCounterBuilder = ImmutableMultiset.builder(); final int numMessages = messages.size(); for (Message s : messages) { Iterable<String> tokens = WordTokenizer.tokenizeWhitespace(s.getBody()); Multiset<String> counter = ImmutableMultiset.copyOf(tokens); tfCounterBuilder.put(s.getId(), counter); dfCounterBuilder.addAll(tokens); } return new Feature() { private final ImmutableMap<String, Multiset<String>> tfCounters = tfCounterBuilder.build(); private final ImmutableMultiset<String> dfCounter = dfCounterBuilder.build(); @Override public Map<Integer, Double> processExample(MessagePair example) { double totalTfIdf = 0.0; double tfIdf1Norm = 0.0; double tfIdf2Norm = 0.0; Set<String> commonWords = example.getWordIntersection(); for (String word : commonWords) { // Message 1 Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf1 = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); // Message 2 counter = tfCounters.get(example.getSecond().getId()); it = Multisets.copyHighestCountFirst(counter).iterator(); maxFreq = counter.count(it.next()); freq = counter.count(word); double tfIdf2 = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); totalTfIdf += tfIdf1 * tfIdf2; } for (String word : WordTokenizer.tokenizeWhitespace(example.getFirst().getBody())) { Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); tfIdf1Norm += tfIdf * tfIdf; } for (String word : WordTokenizer.tokenizeWhitespace(example.getSecond().getBody())) { Multiset<String> counter = tfCounters.get(example.getSecond().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf = (freq / maxFreq) * Math.log(numMessages / dfCounter.count(word)); tfIdf2Norm += tfIdf * tfIdf; } return ImmutableMap.of(0, totalTfIdf / (Math.sqrt(tfIdf1Norm) * Math.sqrt(tfIdf2Norm))); } @Override public int getMaxLength() { return 1; } }; }
public Feature createFeature(List<Message> messages) { final ImmutableMap.Builder<String, Multiset<String>> tfCounterBuilder = ImmutableMap.builder(); final ImmutableMultiset.Builder<String> dfCounterBuilder = ImmutableMultiset.builder(); final int numMessages = messages.size(); for (Message s : messages) { Iterable<String> tokens = WordTokenizer.tokenizeWhitespace(s.getBody()); Multiset<String> counter = ImmutableMultiset.copyOf(tokens); tfCounterBuilder.put(s.getId(), counter); dfCounterBuilder.addAll(tokens); } return new Feature() { private final ImmutableMap<String, Multiset<String>> tfCounters = tfCounterBuilder.build(); private final ImmutableMultiset<String> dfCounter = dfCounterBuilder.build(); @Override public Map<Integer, Double> processExample(MessagePair example) { double totalTfIdf = 0.0; double tfIdf1Norm = 0.0; double tfIdf2Norm = 0.0; Set<String> commonWords = example.getWordIntersection(); for (String word : commonWords) { // Message 1 Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf1 = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); // Message 2 counter = tfCounters.get(example.getSecond().getId()); it = Multisets.copyHighestCountFirst(counter).iterator(); maxFreq = counter.count(it.next()); freq = counter.count(word); double tfIdf2 = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); totalTfIdf += tfIdf1 * tfIdf2; } for (String word : WordTokenizer.tokenizeWhitespace(example.getFirst().getBody())) { Multiset<String> counter = tfCounters.get(example.getFirst().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); tfIdf1Norm += tfIdf * tfIdf; } for (String word : WordTokenizer.tokenizeWhitespace(example.getSecond().getBody())) { Multiset<String> counter = tfCounters.get(example.getSecond().getId()); Iterator<String> it = Multisets.copyHighestCountFirst(counter).iterator(); double maxFreq = counter.count(it.next()); double freq = counter.count(word); double tfIdf = (freq / maxFreq) * Math.log((numMessages + 1) / dfCounter.count(word)); tfIdf2Norm += tfIdf * tfIdf; } return ImmutableMap.of(0, totalTfIdf / (Math.sqrt(tfIdf1Norm) * Math.sqrt(tfIdf2Norm))); } @Override public int getMaxLength() { return 1; } }; }
diff --git a/crescent_core_web/src/test/java/com/tistory/devyongsik/index/CrescentIndexerExecutorTest.java b/crescent_core_web/src/test/java/com/tistory/devyongsik/index/CrescentIndexerExecutorTest.java index 8db96b6..c35091d 100644 --- a/crescent_core_web/src/test/java/com/tistory/devyongsik/index/CrescentIndexerExecutorTest.java +++ b/crescent_core_web/src/test/java/com/tistory/devyongsik/index/CrescentIndexerExecutorTest.java @@ -1,28 +1,28 @@ package com.tistory.devyongsik.index; import java.util.Map; import org.junit.Test; import com.tistory.devyongsik.config.CrescentCollectionHandler; import com.tistory.devyongsik.domain.CrescentCollection; import com.tistory.devyongsik.domain.CrescentCollections; import com.tistory.devyongsik.handler.Handler; import com.tistory.devyongsik.handler.JsonDataHandler; public class CrescentIndexerExecutorTest { @Test public void execute() { CrescentCollections crescentCollections = CrescentCollectionHandler.getInstance().getCrescentCollections(); Map<String, CrescentCollection> collections = crescentCollections.getCrescentCollectionsMap(); CrescentCollection sampleCollection = collections.get("sample_wiki"); Handler handler = new JsonDataHandler(); String jsonFormStr = "[{\"space_idx\":\"0\",\"wiki_title\":\"제목 입니다0\",\"wiki_idx\":\"0\",\"wiki_text\":\"본문 입니다.0\",\"ins_date\":\"20120819\"" + ",\"ins_user\":\"need4spd\"}]"; CrescentIndexerExecutor executor = new CrescentIndexerExecutor(sampleCollection, handler); - executor.execute(jsonFormStr); + executor.bulkIndexing(jsonFormStr); } }
true
true
public void execute() { CrescentCollections crescentCollections = CrescentCollectionHandler.getInstance().getCrescentCollections(); Map<String, CrescentCollection> collections = crescentCollections.getCrescentCollectionsMap(); CrescentCollection sampleCollection = collections.get("sample_wiki"); Handler handler = new JsonDataHandler(); String jsonFormStr = "[{\"space_idx\":\"0\",\"wiki_title\":\"제목 입니다0\",\"wiki_idx\":\"0\",\"wiki_text\":\"본문 입니다.0\",\"ins_date\":\"20120819\"" + ",\"ins_user\":\"need4spd\"}]"; CrescentIndexerExecutor executor = new CrescentIndexerExecutor(sampleCollection, handler); executor.execute(jsonFormStr); }
public void execute() { CrescentCollections crescentCollections = CrescentCollectionHandler.getInstance().getCrescentCollections(); Map<String, CrescentCollection> collections = crescentCollections.getCrescentCollectionsMap(); CrescentCollection sampleCollection = collections.get("sample_wiki"); Handler handler = new JsonDataHandler(); String jsonFormStr = "[{\"space_idx\":\"0\",\"wiki_title\":\"제목 입니다0\",\"wiki_idx\":\"0\",\"wiki_text\":\"본문 입니다.0\",\"ins_date\":\"20120819\"" + ",\"ins_user\":\"need4spd\"}]"; CrescentIndexerExecutor executor = new CrescentIndexerExecutor(sampleCollection, handler); executor.bulkIndexing(jsonFormStr); }
diff --git a/winstone/src/main/java/net/winstone/core/HostConfiguration.java b/winstone/src/main/java/net/winstone/core/HostConfiguration.java index 6232511..373cac5 100644 --- a/winstone/src/main/java/net/winstone/core/HostConfiguration.java +++ b/winstone/src/main/java/net/winstone/core/HostConfiguration.java @@ -1,350 +1,350 @@ /* * Copyright 2003-2006 Rick Knowles <winstone-devel at lists sourceforge net> * Distributed under the terms of either: * - the common development and distribution license (CDDL), v1.0; or * - the GNU Lesser General Public License, v2.1 or later */ package net.winstone.core; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; import net.winstone.WinstoneException; import net.winstone.cluster.Cluster; import net.winstone.jndi.JndiManager; import net.winstone.util.StringUtils; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * Manages the references to individual webapps within the container. This * object handles the mapping of url-prefixes to webapps, and init and shutdown * of any webapps it manages. * * @author <a href="mailto:[email protected]">Rick Knowles</a> * @version $Id: HostConfiguration.java,v 1.8 2007/08/02 06:16:00 rickknowles * Exp $ */ public class HostConfiguration implements Runnable { protected static org.slf4j.Logger logger = LoggerFactory.getLogger(HostConfiguration.class); private static final long FLUSH_PERIOD = 60000L; private static final String WEB_INF = "WEB-INF"; private static final String WEB_XML = "web.xml"; private final String hostname; private final Map<String, String> args; private final Map<String, WebAppConfiguration> webapps; private final Cluster cluster; private final ObjectPool objectPool; private final ClassLoader commonLibCL; private final JndiManager jndiManager; private Thread thread; public HostConfiguration(final String hostname, final Cluster cluster, final ObjectPool objectPool, final JndiManager jndiManager, final ClassLoader commonLibCL, final Map<String, String> args, final String webappsDirName) throws IOException { this.hostname = hostname; this.args = args; webapps = new HashMap<String, WebAppConfiguration>(); this.cluster = cluster; this.objectPool = objectPool; this.commonLibCL = commonLibCL; this.jndiManager = jndiManager; // Is this the single or multiple configuration ? Check args final String warfile = args.get("warfile"); final String webroot = args.get("webroot"); // If single-webapp mode if ((webappsDirName == null) && ((warfile != null) || (webroot != null))) { String prefix = args.get("prefix"); if (prefix == null) { prefix = ""; } try { final WebAppConfiguration webAppConfiguration = initWebApp(prefix, getWebRoot(webroot, warfile), "webapp"); webapps.put(webAppConfiguration.getContextPath(), webAppConfiguration); } catch (final Throwable err) { HostConfiguration.logger.error("Error initializing web application: prefix [" + prefix + "]", err); } } // Otherwise multi-webapp mode else { initMultiWebappDir(webappsDirName); } HostConfiguration.logger.debug("Initialized {} webapps: prefixes - {}", webapps.size() + "", webapps.keySet() + ""); thread = new Thread(this, "WinstoneHostConfigurationMgmt:" + this.hostname); thread.setDaemon(true); thread.start(); } public WebAppConfiguration getWebAppByURI(final String uri) { if (uri == null) { return null; } else if (uri.equals("/") || uri.equals("")) { return webapps.get(""); } else if (uri.startsWith("/")) { final String decoded = WinstoneRequest.decodeURLToken(uri); final String noLeadingSlash = decoded.substring(1); final int slashPos = noLeadingSlash.indexOf("/"); if (slashPos == -1) { return webapps.get(decoded); } else { return webapps.get(decoded.substring(0, slashPos + 1)); } } else { return null; } } protected final WebAppConfiguration initWebApp(final String prefix, final File webRoot, final String contextName) throws IOException { Node webXMLParentNode = null; final File webInfFolder = new File(webRoot, HostConfiguration.WEB_INF); if (webInfFolder.exists()) { final File webXmlFile = new File(webInfFolder, HostConfiguration.WEB_XML); if (webXmlFile.exists()) { HostConfiguration.logger.debug("Parsing web.xml"); final Document webXMLDoc = new WebXmlParser(commonLibCL).parseStreamToXML(webXmlFile); if (webXMLDoc != null) { webXMLParentNode = webXMLDoc.getDocumentElement(); HostConfiguration.logger.debug("Finished parsing web.xml"); } else { HostConfiguration.logger.debug("Failure parsing the web.xml file. Ignoring and continuing as if no web.xml was found."); } } } // Instantiate the webAppConfig return new WebAppConfiguration(this, cluster, jndiManager, webRoot.getCanonicalPath(), prefix, objectPool, args, webXMLParentNode, commonLibCL, contextName); } public String getHostname() { return hostname; } /** * Destroy this webapp instance. Kills the webapps, plus any servlets, * attributes, etc * * @param webApp * The webapp to destroy */ private void destroyWebApp(final String prefix) { final WebAppConfiguration webAppConfig = webapps.get(prefix); if (webAppConfig != null) { webAppConfig.destroy(); webapps.remove(prefix); } } public void destroy() { final Set<String> prefixes = new HashSet<String>(webapps.keySet()); for (final Iterator<String> i = prefixes.iterator(); i.hasNext();) { destroyWebApp(i.next()); } if (thread != null) { thread.interrupt(); } } public void invalidateExpiredSessions() { final Set<WebAppConfiguration> webappConfiguration = new HashSet<WebAppConfiguration>(webapps.values()); for (final Iterator<WebAppConfiguration> i = webappConfiguration.iterator(); i.hasNext();) { i.next().invalidateExpiredSessions(); } } @Override public void run() { boolean interrupted = false; while (!interrupted) { try { Thread.sleep(HostConfiguration.FLUSH_PERIOD); invalidateExpiredSessions(); } catch (final InterruptedException err) { interrupted = true; } } thread = null; } public void reloadWebApp(final String prefix) throws IOException { final WebAppConfiguration webAppConfig = webapps.get(prefix); if (webAppConfig != null) { final String webRoot = webAppConfig.getWebroot(); final String contextName = webAppConfig.getContextName(); destroyWebApp(prefix); try { final WebAppConfiguration webAppConfiguration = initWebApp(prefix, new File(webRoot), contextName); webapps.put(webAppConfiguration.getContextPath(), webAppConfiguration); } catch (final Throwable err) { HostConfiguration.logger.error("Error initializing web application: prefix [" + prefix + "]", err); } } else { throw new WinstoneException("Unknown webapp prefix: " + prefix); } } /** * Setup the webroot. If a warfile is supplied, extract any files that the * war file is newer than. If none is supplied, use the default temp * directory. */ protected final File getWebRoot(final String requestedWebroot, final String warfileName) throws IOException { if (warfileName != null) { HostConfiguration.logger.info("Beginning extraction from war file"); // open the war file final File warfileRef = new File(warfileName); if (!warfileRef.exists() || !warfileRef.isFile()) { throw new WinstoneException("The warfile supplied is unavailable or invalid (" + warfileName + ")"); } // Get the webroot folder (or a temp dir if none supplied) File unzippedDir = null; if (requestedWebroot != null) { unzippedDir = new File(requestedWebroot); } else { // compute which temp directory to use String tempDirectory = StringUtils.stringArg(args, "tempDirectory", null); - String child = "winstone" + File.pathSeparator; + String child = "winstone" + File.separator; if (tempDirectory == null) { // find default temp directory // System.getProperty(""); final File tempFile = File.createTempFile("dummy", "dummy"); tempDirectory = tempFile.getParent(); tempFile.delete(); final String userName = System.getProperty("user.name"); if (userName != null) { - child += StringUtils.replace(userName, new String[][] { { "/", "" }, { "\\", "" }, { ",", "" } }) + File.pathSeparator; + child += StringUtils.replace(userName, new String[][] { { "/", "" }, { "\\", "" }, { ",", "" } }) + File.separator; } } if (hostname != null) { - child += hostname + File.pathSeparator; + child += hostname + File.separator; } child += warfileRef.getName(); unzippedDir = new File(tempDirectory, child); } if (unzippedDir.exists()) { if (!unzippedDir.isDirectory()) { throw new WinstoneException("The webroot supplied is not a valid directory (" + unzippedDir.getPath() + ")"); } else { HostConfiguration.logger.debug("The webroot supplied already exists - overwriting where newer ({})", unzippedDir.getCanonicalPath()); } } else { unzippedDir.mkdirs(); } // Iterate through the files final JarFile warArchive = new JarFile(warfileRef); for (final Enumeration<JarEntry> e = warArchive.entries(); e.hasMoreElements();) { final JarEntry element = e.nextElement(); if (element.isDirectory()) { continue; } final String elemName = element.getName(); // If archive date is newer than unzipped file, overwrite final File outFile = new File(unzippedDir, elemName); if (outFile.exists() && (outFile.lastModified() > warfileRef.lastModified())) { continue; } outFile.getParentFile().mkdirs(); final byte buffer[] = new byte[8192]; // Copy out the extracted file final InputStream inContent = warArchive.getInputStream(element); final OutputStream outStream = new FileOutputStream(outFile); int readBytes = inContent.read(buffer); while (readBytes != -1) { outStream.write(buffer, 0, readBytes); readBytes = inContent.read(buffer); } inContent.close(); outStream.close(); } // Return webroot return unzippedDir; } else { return new File(requestedWebroot); } } protected final void initMultiWebappDir(String webappsDirName) throws IOException { if (webappsDirName == null) { webappsDirName = "webapps"; } final File webappsDir = new File(webappsDirName); if (!webappsDir.exists()) { throw new WinstoneException("Webapps dir " + webappsDirName + " not found"); } else if (!webappsDir.isDirectory()) { throw new WinstoneException("Webapps dir " + webappsDirName + " is not a directory"); } else { final File children[] = webappsDir.listFiles(); for (int n = 0; n < children.length; n++) { final String childName = children[n].getName(); // Check any directories for warfiles that match, and skip: only // deploy the war file if (children[n].isDirectory()) { final File matchingWarFile = new File(webappsDir, children[n].getName() + ".war"); if (matchingWarFile.exists() && matchingWarFile.isFile()) { HostConfiguration.logger.debug("Webapp dir deployment {} skipped, since there is a war file of the same name to check for re-extraction", childName); } else { final String prefix = childName.equalsIgnoreCase("ROOT") ? "" : "/" + childName; if (!webapps.containsKey(prefix)) { try { final WebAppConfiguration webAppConfig = initWebApp(prefix, children[n], childName); webapps.put(webAppConfig.getContextPath(), webAppConfig); HostConfiguration.logger.info("Deployed web application found at {}", childName); } catch (final Throwable err) { HostConfiguration.logger.error("Error initializing web application: prefix [" + prefix + "]", err); } } } } else if (childName.endsWith(".war")) { final String outputName = childName.substring(0, childName.lastIndexOf(".war")); final String prefix = outputName.equalsIgnoreCase("ROOT") ? "" : "/" + outputName; if (!webapps.containsKey(prefix)) { final File outputDir = new File(webappsDir, outputName); outputDir.mkdirs(); try { final WebAppConfiguration webAppConfig = initWebApp(prefix, getWebRoot(new File(webappsDir, outputName).getCanonicalPath(), children[n].getCanonicalPath()), outputName); webapps.put(webAppConfig.getContextPath(), webAppConfig); HostConfiguration.logger.info("Deployed web application found at {}", childName); } catch (final Throwable err) { HostConfiguration.logger.error("Error initializing web application: prefix [" + prefix + "]", err); } } } } } } public WebAppConfiguration getWebAppBySessionKey(final String sessionKey) { final List<WebAppConfiguration> allwebapps = new ArrayList<WebAppConfiguration>(webapps.values()); for (final Iterator<WebAppConfiguration> i = allwebapps.iterator(); i.hasNext();) { final WebAppConfiguration webapp = i.next(); final WinstoneSession session = webapp.getSessionById(sessionKey, false); if (session != null) { return webapp; } } return null; } }
false
true
protected final File getWebRoot(final String requestedWebroot, final String warfileName) throws IOException { if (warfileName != null) { HostConfiguration.logger.info("Beginning extraction from war file"); // open the war file final File warfileRef = new File(warfileName); if (!warfileRef.exists() || !warfileRef.isFile()) { throw new WinstoneException("The warfile supplied is unavailable or invalid (" + warfileName + ")"); } // Get the webroot folder (or a temp dir if none supplied) File unzippedDir = null; if (requestedWebroot != null) { unzippedDir = new File(requestedWebroot); } else { // compute which temp directory to use String tempDirectory = StringUtils.stringArg(args, "tempDirectory", null); String child = "winstone" + File.pathSeparator; if (tempDirectory == null) { // find default temp directory // System.getProperty(""); final File tempFile = File.createTempFile("dummy", "dummy"); tempDirectory = tempFile.getParent(); tempFile.delete(); final String userName = System.getProperty("user.name"); if (userName != null) { child += StringUtils.replace(userName, new String[][] { { "/", "" }, { "\\", "" }, { ",", "" } }) + File.pathSeparator; } } if (hostname != null) { child += hostname + File.pathSeparator; } child += warfileRef.getName(); unzippedDir = new File(tempDirectory, child); } if (unzippedDir.exists()) { if (!unzippedDir.isDirectory()) { throw new WinstoneException("The webroot supplied is not a valid directory (" + unzippedDir.getPath() + ")"); } else { HostConfiguration.logger.debug("The webroot supplied already exists - overwriting where newer ({})", unzippedDir.getCanonicalPath()); } } else { unzippedDir.mkdirs(); } // Iterate through the files final JarFile warArchive = new JarFile(warfileRef); for (final Enumeration<JarEntry> e = warArchive.entries(); e.hasMoreElements();) { final JarEntry element = e.nextElement(); if (element.isDirectory()) { continue; } final String elemName = element.getName(); // If archive date is newer than unzipped file, overwrite final File outFile = new File(unzippedDir, elemName); if (outFile.exists() && (outFile.lastModified() > warfileRef.lastModified())) { continue; } outFile.getParentFile().mkdirs(); final byte buffer[] = new byte[8192]; // Copy out the extracted file final InputStream inContent = warArchive.getInputStream(element); final OutputStream outStream = new FileOutputStream(outFile); int readBytes = inContent.read(buffer); while (readBytes != -1) { outStream.write(buffer, 0, readBytes); readBytes = inContent.read(buffer); } inContent.close(); outStream.close(); } // Return webroot return unzippedDir; } else { return new File(requestedWebroot); } }
protected final File getWebRoot(final String requestedWebroot, final String warfileName) throws IOException { if (warfileName != null) { HostConfiguration.logger.info("Beginning extraction from war file"); // open the war file final File warfileRef = new File(warfileName); if (!warfileRef.exists() || !warfileRef.isFile()) { throw new WinstoneException("The warfile supplied is unavailable or invalid (" + warfileName + ")"); } // Get the webroot folder (or a temp dir if none supplied) File unzippedDir = null; if (requestedWebroot != null) { unzippedDir = new File(requestedWebroot); } else { // compute which temp directory to use String tempDirectory = StringUtils.stringArg(args, "tempDirectory", null); String child = "winstone" + File.separator; if (tempDirectory == null) { // find default temp directory // System.getProperty(""); final File tempFile = File.createTempFile("dummy", "dummy"); tempDirectory = tempFile.getParent(); tempFile.delete(); final String userName = System.getProperty("user.name"); if (userName != null) { child += StringUtils.replace(userName, new String[][] { { "/", "" }, { "\\", "" }, { ",", "" } }) + File.separator; } } if (hostname != null) { child += hostname + File.separator; } child += warfileRef.getName(); unzippedDir = new File(tempDirectory, child); } if (unzippedDir.exists()) { if (!unzippedDir.isDirectory()) { throw new WinstoneException("The webroot supplied is not a valid directory (" + unzippedDir.getPath() + ")"); } else { HostConfiguration.logger.debug("The webroot supplied already exists - overwriting where newer ({})", unzippedDir.getCanonicalPath()); } } else { unzippedDir.mkdirs(); } // Iterate through the files final JarFile warArchive = new JarFile(warfileRef); for (final Enumeration<JarEntry> e = warArchive.entries(); e.hasMoreElements();) { final JarEntry element = e.nextElement(); if (element.isDirectory()) { continue; } final String elemName = element.getName(); // If archive date is newer than unzipped file, overwrite final File outFile = new File(unzippedDir, elemName); if (outFile.exists() && (outFile.lastModified() > warfileRef.lastModified())) { continue; } outFile.getParentFile().mkdirs(); final byte buffer[] = new byte[8192]; // Copy out the extracted file final InputStream inContent = warArchive.getInputStream(element); final OutputStream outStream = new FileOutputStream(outFile); int readBytes = inContent.read(buffer); while (readBytes != -1) { outStream.write(buffer, 0, readBytes); readBytes = inContent.read(buffer); } inContent.close(); outStream.close(); } // Return webroot return unzippedDir; } else { return new File(requestedWebroot); } }
diff --git a/src/com/oreilly/common/text/Translater.java b/src/com/oreilly/common/text/Translater.java index bc7369f..216e35f 100644 --- a/src/com/oreilly/common/text/Translater.java +++ b/src/com/oreilly/common/text/Translater.java @@ -1,120 +1,122 @@ package com.oreilly.common.text; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import com.oreilly.common.io.Yaml; public class Translater { // raw translation data - [name], [value map] HashMap< String, TranslationRecord > translations = new HashMap< String, TranslationRecord >(); public Translater( File translationDirectory, Logger errorLog ) { // load the contents of the translation files.. List< YamlConfiguration > files = Yaml.loadYamlDirectory( translationDirectory, errorLog ); for ( YamlConfiguration config : files ) { String name = config.getString( TranslationFileConstants.name ); List< String > inheritsFrom = config.getStringList( TranslationFileConstants.inherits ); ConfigurationSection content = config.getConfigurationSection( TranslationFileConstants.content ); if ( ( name != null ) & ( content != null ) ) { TranslationRecord record = new TranslationRecord( name ); + translations.put( name, record ); if ( inheritsFrom != null ) record.inheritsFrom.addAll( inheritsFrom ); for ( String key : content.getKeys( true ) ) { Object item = content.get( key ); if (( item instanceof String ) | ( item instanceof Double ) | ( item instanceof Integer )) record.rawTranslations.put( key, item.toString()); } } } // Compile translations... LinkedList< TranslationRecord > toCompile = new LinkedList< TranslationRecord >(); + toCompile.addAll( translations.values() ); boolean progress = true; TranslationRecord parent = null; while ( progress ) { progress = false; LinkedList< TranslationRecord > toRemove = new LinkedList< TranslationRecord >(); for ( TranslationRecord record : toCompile ) { // if all the parent records are compiled (or if there are no parent records).. // .. then we can compile this one. boolean parentsCompiled = true; if ( record.inheritsFrom != null ) if ( record.inheritsFrom.size() > 0 ) for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); if ( parent == null ) { // TODO: Some form of error based on "parent doesn't exist!" parentsCompiled = false; break; } if ( parent.compiled == false ) { parentsCompiled = false; break; } } if ( parentsCompiled ) { progress = true; // 'import' the data from the parent records for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); record.compiledTranslations.putAll( parent.compiledTranslations ); } // apply the data in the this record record.compiledTranslations.putAll( record.rawTranslations ); // mark as compiled record.compiled = true; // put this record in the remove queue toRemove.add( record ); } } // now we are outside the loop, remove any records that have been compiled this round for ( TranslationRecord record : toRemove ) toCompile.remove( record ); } // if no changes have happened this round, then we have unresolvable dependencies - throw up an error. // TODO: } public HashMap< String, String > getTranslation( String name ) { TranslationRecord record = translations.get( name ); if ( record == null ) return null; //TODO: Throw an error return record.compiledTranslations; } } class TranslationRecord { public String name; public ArrayList< String > inheritsFrom = new ArrayList< String >(); public HashMap< String, String > rawTranslations = new HashMap< String, String >(); public HashMap< String, String > compiledTranslations = new HashMap< String, String >(); boolean compiled = false; public TranslationRecord( String name ) { this.name = name; } } class TranslationFileConstants { public static final String name = "header.name"; public static final String inherits = "header.inheritsFrom"; public static final String content = "translations"; }
false
true
public Translater( File translationDirectory, Logger errorLog ) { // load the contents of the translation files.. List< YamlConfiguration > files = Yaml.loadYamlDirectory( translationDirectory, errorLog ); for ( YamlConfiguration config : files ) { String name = config.getString( TranslationFileConstants.name ); List< String > inheritsFrom = config.getStringList( TranslationFileConstants.inherits ); ConfigurationSection content = config.getConfigurationSection( TranslationFileConstants.content ); if ( ( name != null ) & ( content != null ) ) { TranslationRecord record = new TranslationRecord( name ); if ( inheritsFrom != null ) record.inheritsFrom.addAll( inheritsFrom ); for ( String key : content.getKeys( true ) ) { Object item = content.get( key ); if (( item instanceof String ) | ( item instanceof Double ) | ( item instanceof Integer )) record.rawTranslations.put( key, item.toString()); } } } // Compile translations... LinkedList< TranslationRecord > toCompile = new LinkedList< TranslationRecord >(); boolean progress = true; TranslationRecord parent = null; while ( progress ) { progress = false; LinkedList< TranslationRecord > toRemove = new LinkedList< TranslationRecord >(); for ( TranslationRecord record : toCompile ) { // if all the parent records are compiled (or if there are no parent records).. // .. then we can compile this one. boolean parentsCompiled = true; if ( record.inheritsFrom != null ) if ( record.inheritsFrom.size() > 0 ) for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); if ( parent == null ) { // TODO: Some form of error based on "parent doesn't exist!" parentsCompiled = false; break; } if ( parent.compiled == false ) { parentsCompiled = false; break; } } if ( parentsCompiled ) { progress = true; // 'import' the data from the parent records for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); record.compiledTranslations.putAll( parent.compiledTranslations ); } // apply the data in the this record record.compiledTranslations.putAll( record.rawTranslations ); // mark as compiled record.compiled = true; // put this record in the remove queue toRemove.add( record ); } } // now we are outside the loop, remove any records that have been compiled this round for ( TranslationRecord record : toRemove ) toCompile.remove( record ); } // if no changes have happened this round, then we have unresolvable dependencies - throw up an error. // TODO: }
public Translater( File translationDirectory, Logger errorLog ) { // load the contents of the translation files.. List< YamlConfiguration > files = Yaml.loadYamlDirectory( translationDirectory, errorLog ); for ( YamlConfiguration config : files ) { String name = config.getString( TranslationFileConstants.name ); List< String > inheritsFrom = config.getStringList( TranslationFileConstants.inherits ); ConfigurationSection content = config.getConfigurationSection( TranslationFileConstants.content ); if ( ( name != null ) & ( content != null ) ) { TranslationRecord record = new TranslationRecord( name ); translations.put( name, record ); if ( inheritsFrom != null ) record.inheritsFrom.addAll( inheritsFrom ); for ( String key : content.getKeys( true ) ) { Object item = content.get( key ); if (( item instanceof String ) | ( item instanceof Double ) | ( item instanceof Integer )) record.rawTranslations.put( key, item.toString()); } } } // Compile translations... LinkedList< TranslationRecord > toCompile = new LinkedList< TranslationRecord >(); toCompile.addAll( translations.values() ); boolean progress = true; TranslationRecord parent = null; while ( progress ) { progress = false; LinkedList< TranslationRecord > toRemove = new LinkedList< TranslationRecord >(); for ( TranslationRecord record : toCompile ) { // if all the parent records are compiled (or if there are no parent records).. // .. then we can compile this one. boolean parentsCompiled = true; if ( record.inheritsFrom != null ) if ( record.inheritsFrom.size() > 0 ) for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); if ( parent == null ) { // TODO: Some form of error based on "parent doesn't exist!" parentsCompiled = false; break; } if ( parent.compiled == false ) { parentsCompiled = false; break; } } if ( parentsCompiled ) { progress = true; // 'import' the data from the parent records for ( String parentName : record.inheritsFrom ) { parent = translations.get( parentName ); record.compiledTranslations.putAll( parent.compiledTranslations ); } // apply the data in the this record record.compiledTranslations.putAll( record.rawTranslations ); // mark as compiled record.compiled = true; // put this record in the remove queue toRemove.add( record ); } } // now we are outside the loop, remove any records that have been compiled this round for ( TranslationRecord record : toRemove ) toCompile.remove( record ); } // if no changes have happened this round, then we have unresolvable dependencies - throw up an error. // TODO: }
diff --git a/qa/app/controllers/Application.java b/qa/app/controllers/Application.java index 923ece9..1fbeb4c 100644 --- a/qa/app/controllers/Application.java +++ b/qa/app/controllers/Application.java @@ -1,108 +1,109 @@ package controllers; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.Set; import models.DbManager; import models.Question; import models.SearchManager; import models.SearchResult; import models.User; import play.mvc.Controller; /** * This Controller manages some general actions. */ public class Application extends Controller { private static Calendar calendar = Calendar.getInstance(); private static DbManager manager = DbManager.getInstance(); public static void index() { String userName = session.get("username"); int score = 0; boolean isChanged = true; if (userName != null) { User user = manager.getUserByName(userName); isChanged = user.isChanged(); } if (manager.getQuestions().isEmpty()) { String message = "no questions"; render(message, userName, score); } else { ArrayList<Question> questions = manager.getQuestionsSortedByScore(); render(questions, userName, isChanged); } } /** * Renders some general informations about the application */ public static void showState() { int userCount = manager.countOfUsers(); int questionCount = manager.countOfQuestions(); int answerCount = manager.countOfAnswers(); int commentCount = manager.countOfComments(); int tagCount = manager.countOfTags(); render(userCount, questionCount, answerCount, commentCount, tagCount); } /** Renders Search Results */ public static void search(String text, String menu) { // When site is first time loaded if (text == null) { render(); } boolean isQuestion = menu.equals("search"); boolean isUserByTag = menu.equals("similarUserByTag"); boolean isUserByContent = menu.equals("similarUserByContent"); User currentUser = manager.getUserByName(session.get("username")); // If no query is typed in if (text != null && text.equals("")) { String message = "Nothing to search"; render(message); } // If a query is typed in differentiate between searchtypes if (!text.equals("")) { SearchManager searchManager; if (isUserByContent) { searchManager = new SearchManager(text, "similarUserByContent"); } else { if (isUserByTag) { searchManager = new SearchManager(text, "similarUserByTag"); } else { searchManager = new SearchManager(text, "search"); } } ArrayList<SearchResult> results = searchManager.getSearchResults(); if (isUserByTag || isUserByContent) { // returns list of users without duplicates or user logged // into // session ArrayList<SearchResult> newList = new ArrayList(); Set set = new HashSet(); for (SearchResult result : results) { if (set.add(result.getOwner()) && !result.getOwner().equals(currentUser)) newList.add(result); } results.clear(); results.addAll(newList); } // If query has no results if (results.size() == 0) { String message = "No Results"; - render(message); + render(message, menu, text); } else { - render(results, isQuestion, isUserByTag, isUserByContent, menu); + render(results, isQuestion, isUserByTag, isUserByContent, menu, + text); } } } }
false
true
public static void search(String text, String menu) { // When site is first time loaded if (text == null) { render(); } boolean isQuestion = menu.equals("search"); boolean isUserByTag = menu.equals("similarUserByTag"); boolean isUserByContent = menu.equals("similarUserByContent"); User currentUser = manager.getUserByName(session.get("username")); // If no query is typed in if (text != null && text.equals("")) { String message = "Nothing to search"; render(message); } // If a query is typed in differentiate between searchtypes if (!text.equals("")) { SearchManager searchManager; if (isUserByContent) { searchManager = new SearchManager(text, "similarUserByContent"); } else { if (isUserByTag) { searchManager = new SearchManager(text, "similarUserByTag"); } else { searchManager = new SearchManager(text, "search"); } } ArrayList<SearchResult> results = searchManager.getSearchResults(); if (isUserByTag || isUserByContent) { // returns list of users without duplicates or user logged // into // session ArrayList<SearchResult> newList = new ArrayList(); Set set = new HashSet(); for (SearchResult result : results) { if (set.add(result.getOwner()) && !result.getOwner().equals(currentUser)) newList.add(result); } results.clear(); results.addAll(newList); } // If query has no results if (results.size() == 0) { String message = "No Results"; render(message); } else { render(results, isQuestion, isUserByTag, isUserByContent, menu); } } }
public static void search(String text, String menu) { // When site is first time loaded if (text == null) { render(); } boolean isQuestion = menu.equals("search"); boolean isUserByTag = menu.equals("similarUserByTag"); boolean isUserByContent = menu.equals("similarUserByContent"); User currentUser = manager.getUserByName(session.get("username")); // If no query is typed in if (text != null && text.equals("")) { String message = "Nothing to search"; render(message); } // If a query is typed in differentiate between searchtypes if (!text.equals("")) { SearchManager searchManager; if (isUserByContent) { searchManager = new SearchManager(text, "similarUserByContent"); } else { if (isUserByTag) { searchManager = new SearchManager(text, "similarUserByTag"); } else { searchManager = new SearchManager(text, "search"); } } ArrayList<SearchResult> results = searchManager.getSearchResults(); if (isUserByTag || isUserByContent) { // returns list of users without duplicates or user logged // into // session ArrayList<SearchResult> newList = new ArrayList(); Set set = new HashSet(); for (SearchResult result : results) { if (set.add(result.getOwner()) && !result.getOwner().equals(currentUser)) newList.add(result); } results.clear(); results.addAll(newList); } // If query has no results if (results.size() == 0) { String message = "No Results"; render(message, menu, text); } else { render(results, isQuestion, isUserByTag, isUserByContent, menu, text); } } }
diff --git a/bpel-el-xpath20/src/main/java/org/apache/ode/bpel/elang/xpath20/runtime/XPath20ExpressionRuntime.java b/bpel-el-xpath20/src/main/java/org/apache/ode/bpel/elang/xpath20/runtime/XPath20ExpressionRuntime.java index d5678ceea..3f00c7d44 100644 --- a/bpel-el-xpath20/src/main/java/org/apache/ode/bpel/elang/xpath20/runtime/XPath20ExpressionRuntime.java +++ b/bpel-el-xpath20/src/main/java/org/apache/ode/bpel/elang/xpath20/runtime/XPath20ExpressionRuntime.java @@ -1,192 +1,195 @@ /* * 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.ode.bpel.elang.xpath20.runtime; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import net.sf.saxon.xpath.XPathEvaluator; import net.sf.saxon.trans.DynamicError; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.ode.bpel.common.FaultException; import org.apache.ode.bpel.elang.xpath10.o.OXPath10Expression; import org.apache.ode.bpel.elang.xpath20.Constants; import org.apache.ode.bpel.elang.xpath20.WrappedResolverException; import org.apache.ode.bpel.elang.xpath20.o.OXPath20ExpressionBPEL20; import org.apache.ode.bpel.explang.ConfigurationException; import org.apache.ode.bpel.explang.EvaluationContext; import org.apache.ode.bpel.explang.EvaluationException; import org.apache.ode.bpel.explang.ExpressionLanguageRuntime; import org.apache.ode.bpel.o.OExpression; import org.apache.ode.utils.DOMUtils; import org.apache.ode.utils.xsd.Duration; import org.apache.ode.utils.xsd.XMLCalendar; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; /** * XPath 2.0 Expression Language run-time subsytem. * Saxon implementation. */ public class XPath20ExpressionRuntime implements ExpressionLanguageRuntime { static final short NODE_TYPE = 1; static final short NODESET_TYPE = 2; static final short STRING_TYPE = 3; static final short BOOLEAN_TYPE = 4; static final short NUMBER_TYPE = 5; /** Class-level logger. */ private static final Log __log = LogFactory.getLog(XPath20ExpressionRuntime.class); public XPath20ExpressionRuntime(){ } public void initialize(Map properties) throws ConfigurationException { } /** * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluateAsString(org.apache.ode.bpel.o.OExpression, org.apache.ode.bpel.explang.EvaluationContext) */ public String evaluateAsString(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException { return (String)evaluate(cexp, ctx, XPathConstants.STRING); } /** * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluateAsBoolean(org.apache.ode.bpel.o.OExpression, org.apache.ode.bpel.explang.EvaluationContext) */ public boolean evaluateAsBoolean(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException { return (Boolean) evaluate(cexp, ctx, XPathConstants.BOOLEAN); } public Number evaluateAsNumber(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException { return (Number) evaluate(cexp, ctx, XPathConstants.NUMBER); } /** * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluate(org.apache.ode.bpel.o.OExpression, org.apache.ode.bpel.explang.EvaluationContext) */ public List evaluate(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException { List result = null; Object someRes = evaluate(cexp, ctx, XPathConstants.NODESET); if (someRes instanceof List) { result = (List) someRes; if ((result.size() == 1) && !(result.get(0) instanceof Node)) { Document d = DOMUtils.newDocument(); // Giving our node a parent just in case it's an LValue expression Element wrapper = d.createElement("wrapper"); Text text = d.createTextNode(result.get(0).toString()); wrapper.appendChild(text); d.appendChild(wrapper); result = Collections.singletonList(text); } } if (someRes instanceof NodeList) { NodeList retVal = (NodeList) someRes; result = new ArrayList(retVal.getLength()); for(int m = 0; m < retVal.getLength(); m++) { Node val = retVal.item(m); if (val.getNodeType() == Node.DOCUMENT_NODE) val = ((Document)val).getDocumentElement(); result.add(val); } } return result; } public Node evaluateNode(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException { List retVal = evaluate(cexp, ctx); if (retVal.size() == 0) throw new FaultException(cexp.getOwner().constants.qnSelectionFailure, "No results for expression: " + cexp); if (retVal.size() > 1) throw new FaultException(cexp.getOwner().constants.qnSelectionFailure, "Multiple results for expression: " + cexp); return (Node) retVal.get(0); } public Calendar evaluateAsDate(OExpression cexp, EvaluationContext context) throws FaultException, EvaluationException { String literal = evaluateAsString(cexp, context); try { return new XMLCalendar(literal); } catch (Exception ex) { __log.error("Date conversion error." ,ex); throw new EvaluationException("Date conversion errror.", ex); } } public Duration evaluateAsDuration(OExpression cexp, EvaluationContext context) throws FaultException, EvaluationException { String literal = this.evaluateAsString(cexp, context); try { return new Duration(literal); } catch (Exception ex) { __log.error("Date conversion error.", ex); throw new EvaluationException("Duration conversion error." ,ex); } } private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException, EvaluationException { try { net.sf.saxon.xpath.XPathFactoryImpl xpf = new net.sf.saxon.xpath.XPathFactoryImpl(); OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp); xpf.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath20, Constants.BPEL20_NS)); xpf.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath20)); XPathEvaluator xpe = (XPathEvaluator) xpf.newXPath(); xpe.setNamespaceContext(oxpath20.namespaceCtx); // Just checking that the expression is valid XPathExpression expr = xpe.compile(((OXPath10Expression)cexp).xpath); Object evalResult = expr.evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type); if (evalResult != null && __log.isDebugEnabled()) __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type=" + evalResult.getClass().getName()); return evalResult; } catch (XPathExpressionException e) { // Extracting the real cause from all this wrapping isn't a simple task Throwable cause = e.getCause() != null ? e.getCause() : e; if (cause instanceof DynamicError) { - cause = ((DynamicError)cause).getException(); - if (cause.getCause() != null) cause = cause.getCause(); + Throwable th = ((DynamicError)cause).getException(); + if (th != null) { + cause = th; + if (cause.getCause() != null) cause = cause.getCause(); + } } throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause); } catch (WrappedResolverException wre) { wre.printStackTrace(); throw (FaultException)wre.getCause(); } catch (Throwable t) { t.printStackTrace(); throw new EvaluationException("Error while executing an XPath expression: ", t); } } }
true
true
private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException, EvaluationException { try { net.sf.saxon.xpath.XPathFactoryImpl xpf = new net.sf.saxon.xpath.XPathFactoryImpl(); OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp); xpf.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath20, Constants.BPEL20_NS)); xpf.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath20)); XPathEvaluator xpe = (XPathEvaluator) xpf.newXPath(); xpe.setNamespaceContext(oxpath20.namespaceCtx); // Just checking that the expression is valid XPathExpression expr = xpe.compile(((OXPath10Expression)cexp).xpath); Object evalResult = expr.evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type); if (evalResult != null && __log.isDebugEnabled()) __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type=" + evalResult.getClass().getName()); return evalResult; } catch (XPathExpressionException e) { // Extracting the real cause from all this wrapping isn't a simple task Throwable cause = e.getCause() != null ? e.getCause() : e; if (cause instanceof DynamicError) { cause = ((DynamicError)cause).getException(); if (cause.getCause() != null) cause = cause.getCause(); } throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause); } catch (WrappedResolverException wre) { wre.printStackTrace(); throw (FaultException)wre.getCause(); } catch (Throwable t) { t.printStackTrace(); throw new EvaluationException("Error while executing an XPath expression: ", t); } }
private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException, EvaluationException { try { net.sf.saxon.xpath.XPathFactoryImpl xpf = new net.sf.saxon.xpath.XPathFactoryImpl(); OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp); xpf.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath20, Constants.BPEL20_NS)); xpf.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath20)); XPathEvaluator xpe = (XPathEvaluator) xpf.newXPath(); xpe.setNamespaceContext(oxpath20.namespaceCtx); // Just checking that the expression is valid XPathExpression expr = xpe.compile(((OXPath10Expression)cexp).xpath); Object evalResult = expr.evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type); if (evalResult != null && __log.isDebugEnabled()) __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type=" + evalResult.getClass().getName()); return evalResult; } catch (XPathExpressionException e) { // Extracting the real cause from all this wrapping isn't a simple task Throwable cause = e.getCause() != null ? e.getCause() : e; if (cause instanceof DynamicError) { Throwable th = ((DynamicError)cause).getException(); if (th != null) { cause = th; if (cause.getCause() != null) cause = cause.getCause(); } } throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause); } catch (WrappedResolverException wre) { wre.printStackTrace(); throw (FaultException)wre.getCause(); } catch (Throwable t) { t.printStackTrace(); throw new EvaluationException("Error while executing an XPath expression: ", t); } }
diff --git a/src/widgets/Graphical_Boolean.java b/src/widgets/Graphical_Boolean.java index 69b28c6b..2ed48a78 100644 --- a/src/widgets/Graphical_Boolean.java +++ b/src/widgets/Graphical_Boolean.java @@ -1,275 +1,275 @@ /* * This file is part of Domodroid. * * Domodroid is Copyright (C) 2011 Pierre LAINE, Maxime CHOFARDET * * Domodroid 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. * * Domodroid 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 * Domodroid. If not, see <http://www.gnu.org/licenses/>. */ package widgets; import java.util.Timer; import java.util.TimerTask; import org.json.JSONException; import org.json.JSONObject; import activities.Gradients_Manager; import activities.Graphics_Manager; import org.domogik.domodroid.R; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import misc.tracerengine; import android.view.Gravity; import android.view.View; import android.view.View.OnLongClickListener; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class Graphical_Boolean extends FrameLayout implements OnLongClickListener{ private FrameLayout imgPan; private LinearLayout background; private LinearLayout featurePan; private LinearLayout infoPan; private ImageView img; private TextView nameDevices; private TextView state; private String value0; private String value1; private String Value_0; private String Value_1; private ImageView bool; private int dev_id; private int id; private Handler handler; private String state_key; private int update; private String mytag; private Message msg; private String wname; private String stateS = ""; public FrameLayout container = null; public FrameLayout myself = null; private tracerengine Tracer = null; private Entity_client session = null; private Boolean realtime = false; public Graphical_Boolean(tracerengine Trac, Activity context, String address, String name, int id,int dev_id, String state_key, final String usage, String parameters, String model_id, int update, int widgetSize) throws JSONException { super(context); this.Tracer = Trac; this.state_key = state_key; this.dev_id = dev_id; this.id = id; this.update = update; this.wname = name; this.myself=this; this.setPadding(5, 5, 5, 5); this.stateS = getResources().getText(R.string.State).toString(); try { JSONObject jparam = new JSONObject(parameters.replaceAll("&quot;", "\"")); value0 = jparam.getString("value0"); value1 = jparam.getString("value1"); } catch (Exception e) { value0 = "0"; value1 = "1"; } if (usage.equals("light")){ this.Value_0 = getResources().getText(R.string.light_stat_0).toString(); this.Value_1 = getResources().getText(R.string.light_stat_1).toString(); }else if (usage.equals("shutter")){ this.Value_0 = getResources().getText(R.string.shutter_stat_0).toString(); this.Value_1 = getResources().getText(R.string.shutter_stat_1).toString(); }else{ this.Value_0 = value0; this.Value_1 = value1; } mytag="Graphical_Boolean("+dev_id+")"; //panel with border background = new LinearLayout(context); if(widgetSize==0)background.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); else background.setLayoutParams(new LayoutParams(widgetSize,LayoutParams.WRAP_CONTENT)); background.setBackgroundDrawable(Gradients_Manager.LoadDrawable("white",background.getHeight())); //panel to set img with padding left imgPan = new FrameLayout(context); imgPan.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT)); imgPan.setPadding(5, 10, 5, 10); //img img = new ImageView(context); img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,Gravity.CENTER)); //set default color to (usage,0) off.png img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); // info panel infoPan = new LinearLayout(context); infoPan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); infoPan.setOrientation(LinearLayout.VERTICAL); infoPan.setGravity(Gravity.CENTER_VERTICAL); //name of devices nameDevices=new TextView(context); nameDevices.setText(name); nameDevices.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); nameDevices.setTextColor(Color.BLACK); nameDevices.setTextSize(16); nameDevices.setOnLongClickListener(this); //state state=new TextView(context); state.setTextColor(Color.BLACK); - state.setText("State : Low"); + state.setText("State :"+this.Value_0); //feature panel featurePan=new LinearLayout(context); featurePan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); featurePan.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); featurePan.setPadding(0, 0, 20, 0); //boolean on/off bool = new ImageView(context); bool.setImageResource(R.drawable.boolean_off); featurePan.addView(bool); infoPan.addView(nameDevices); infoPan.addView(state); imgPan.addView(img); background.addView(imgPan); background.addView(infoPan); background.addView(featurePan); this.addView(background); handler = new Handler() { @Override public void handleMessage(Message msg) { String status; if(msg.what == 9999) { status = session.getValue(); if(status != null) { Tracer.d(mytag,"Handler receives a new status <"+status+">" ); try { - if(status.equals("value0")){ + if(status.equals(value0)){ bool.setImageResource(R.drawable.boolean_off); //change color if statue=low to (usage, o) means off //note sure if it must be kept as set previously as default color. img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); state.setText(stateS+Value_0); - }else if(status.equals("value1")){ + }else if(status.equals(value1)){ bool.setImageResource(R.drawable.boolean_on); //change color if statue=high to (usage, 2) means on img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2)); state.setText(stateS+Value_1); } } catch (Exception e) { Tracer.e(mytag, "handler error device "+wname); e.printStackTrace(); } } } else if(msg.what == 9998) { // state_engine send us a signal to notify it'll die ! Tracer.d(mytag,"state engine disappeared ===> Harakiri !" ); session = null; realtime = false; removeView(background); myself.setVisibility(GONE); if(container != null) { container.removeView(myself); container.recomputeViewAttributes(myself); } try { finalize(); } catch (Throwable t) {} //kill the handler thread itself } } }; //================================================================================ /* * New mechanism to be notified by widgetupdate engine when our value is changed * */ if(Tracer != null) { //state_engine = Tracer.get_engine(); if(Tracer.get_engine() != null) { session = new Entity_client(dev_id, state_key, mytag, handler); if(Tracer.get_engine().subscribe(session)) { realtime = true; //we're connected to engine //each time our value change, the engine will call handler handler.sendEmptyMessage(9999); //Force to consider current value in session } } } //================================================================================ } @Override protected void onWindowVisibilityChanged(int visibility) { } public boolean onLongClick(View arg0) { AlertDialog.Builder alert = new AlertDialog.Builder(getContext()); alert.setTitle(R.string.Rename_title); alert.setMessage(R.string.Rename_message); // Set an EditText view to get user input final EditText input = new EditText(getContext()); alert.setView(input); alert.setPositiveButton(R.string.reloadOK, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog_customname, int whichButton) { String result= input.getText().toString(); Tracer.e("Graphical_Boolean", "Description set to: "+result); Tracer.get_engine().descUpdate(id,result); } }); alert.setNegativeButton(R.string.reloadNO, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog_customname, int whichButton) { Tracer.e("Graphical_Boolean", "Customname Canceled."); } }); alert.show(); return false; } }
false
true
public Graphical_Boolean(tracerengine Trac, Activity context, String address, String name, int id,int dev_id, String state_key, final String usage, String parameters, String model_id, int update, int widgetSize) throws JSONException { super(context); this.Tracer = Trac; this.state_key = state_key; this.dev_id = dev_id; this.id = id; this.update = update; this.wname = name; this.myself=this; this.setPadding(5, 5, 5, 5); this.stateS = getResources().getText(R.string.State).toString(); try { JSONObject jparam = new JSONObject(parameters.replaceAll("&quot;", "\"")); value0 = jparam.getString("value0"); value1 = jparam.getString("value1"); } catch (Exception e) { value0 = "0"; value1 = "1"; } if (usage.equals("light")){ this.Value_0 = getResources().getText(R.string.light_stat_0).toString(); this.Value_1 = getResources().getText(R.string.light_stat_1).toString(); }else if (usage.equals("shutter")){ this.Value_0 = getResources().getText(R.string.shutter_stat_0).toString(); this.Value_1 = getResources().getText(R.string.shutter_stat_1).toString(); }else{ this.Value_0 = value0; this.Value_1 = value1; } mytag="Graphical_Boolean("+dev_id+")"; //panel with border background = new LinearLayout(context); if(widgetSize==0)background.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); else background.setLayoutParams(new LayoutParams(widgetSize,LayoutParams.WRAP_CONTENT)); background.setBackgroundDrawable(Gradients_Manager.LoadDrawable("white",background.getHeight())); //panel to set img with padding left imgPan = new FrameLayout(context); imgPan.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT)); imgPan.setPadding(5, 10, 5, 10); //img img = new ImageView(context); img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,Gravity.CENTER)); //set default color to (usage,0) off.png img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); // info panel infoPan = new LinearLayout(context); infoPan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); infoPan.setOrientation(LinearLayout.VERTICAL); infoPan.setGravity(Gravity.CENTER_VERTICAL); //name of devices nameDevices=new TextView(context); nameDevices.setText(name); nameDevices.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); nameDevices.setTextColor(Color.BLACK); nameDevices.setTextSize(16); nameDevices.setOnLongClickListener(this); //state state=new TextView(context); state.setTextColor(Color.BLACK); state.setText("State : Low"); //feature panel featurePan=new LinearLayout(context); featurePan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); featurePan.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); featurePan.setPadding(0, 0, 20, 0); //boolean on/off bool = new ImageView(context); bool.setImageResource(R.drawable.boolean_off); featurePan.addView(bool); infoPan.addView(nameDevices); infoPan.addView(state); imgPan.addView(img); background.addView(imgPan); background.addView(infoPan); background.addView(featurePan); this.addView(background); handler = new Handler() { @Override public void handleMessage(Message msg) { String status; if(msg.what == 9999) { status = session.getValue(); if(status != null) { Tracer.d(mytag,"Handler receives a new status <"+status+">" ); try { if(status.equals("value0")){ bool.setImageResource(R.drawable.boolean_off); //change color if statue=low to (usage, o) means off //note sure if it must be kept as set previously as default color. img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); state.setText(stateS+Value_0); }else if(status.equals("value1")){ bool.setImageResource(R.drawable.boolean_on); //change color if statue=high to (usage, 2) means on img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2)); state.setText(stateS+Value_1); } } catch (Exception e) { Tracer.e(mytag, "handler error device "+wname); e.printStackTrace(); } } } else if(msg.what == 9998) { // state_engine send us a signal to notify it'll die ! Tracer.d(mytag,"state engine disappeared ===> Harakiri !" ); session = null; realtime = false; removeView(background); myself.setVisibility(GONE); if(container != null) { container.removeView(myself); container.recomputeViewAttributes(myself); } try { finalize(); } catch (Throwable t) {} //kill the handler thread itself } } }; //================================================================================ /* * New mechanism to be notified by widgetupdate engine when our value is changed * */ if(Tracer != null) { //state_engine = Tracer.get_engine(); if(Tracer.get_engine() != null) { session = new Entity_client(dev_id, state_key, mytag, handler); if(Tracer.get_engine().subscribe(session)) { realtime = true; //we're connected to engine //each time our value change, the engine will call handler handler.sendEmptyMessage(9999); //Force to consider current value in session } } } //================================================================================ }
public Graphical_Boolean(tracerengine Trac, Activity context, String address, String name, int id,int dev_id, String state_key, final String usage, String parameters, String model_id, int update, int widgetSize) throws JSONException { super(context); this.Tracer = Trac; this.state_key = state_key; this.dev_id = dev_id; this.id = id; this.update = update; this.wname = name; this.myself=this; this.setPadding(5, 5, 5, 5); this.stateS = getResources().getText(R.string.State).toString(); try { JSONObject jparam = new JSONObject(parameters.replaceAll("&quot;", "\"")); value0 = jparam.getString("value0"); value1 = jparam.getString("value1"); } catch (Exception e) { value0 = "0"; value1 = "1"; } if (usage.equals("light")){ this.Value_0 = getResources().getText(R.string.light_stat_0).toString(); this.Value_1 = getResources().getText(R.string.light_stat_1).toString(); }else if (usage.equals("shutter")){ this.Value_0 = getResources().getText(R.string.shutter_stat_0).toString(); this.Value_1 = getResources().getText(R.string.shutter_stat_1).toString(); }else{ this.Value_0 = value0; this.Value_1 = value1; } mytag="Graphical_Boolean("+dev_id+")"; //panel with border background = new LinearLayout(context); if(widgetSize==0)background.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); else background.setLayoutParams(new LayoutParams(widgetSize,LayoutParams.WRAP_CONTENT)); background.setBackgroundDrawable(Gradients_Manager.LoadDrawable("white",background.getHeight())); //panel to set img with padding left imgPan = new FrameLayout(context); imgPan.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT)); imgPan.setPadding(5, 10, 5, 10); //img img = new ImageView(context); img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,Gravity.CENTER)); //set default color to (usage,0) off.png img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); // info panel infoPan = new LinearLayout(context); infoPan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); infoPan.setOrientation(LinearLayout.VERTICAL); infoPan.setGravity(Gravity.CENTER_VERTICAL); //name of devices nameDevices=new TextView(context); nameDevices.setText(name); nameDevices.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); nameDevices.setTextColor(Color.BLACK); nameDevices.setTextSize(16); nameDevices.setOnLongClickListener(this); //state state=new TextView(context); state.setTextColor(Color.BLACK); state.setText("State :"+this.Value_0); //feature panel featurePan=new LinearLayout(context); featurePan.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT,1)); featurePan.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); featurePan.setPadding(0, 0, 20, 0); //boolean on/off bool = new ImageView(context); bool.setImageResource(R.drawable.boolean_off); featurePan.addView(bool); infoPan.addView(nameDevices); infoPan.addView(state); imgPan.addView(img); background.addView(imgPan); background.addView(infoPan); background.addView(featurePan); this.addView(background); handler = new Handler() { @Override public void handleMessage(Message msg) { String status; if(msg.what == 9999) { status = session.getValue(); if(status != null) { Tracer.d(mytag,"Handler receives a new status <"+status+">" ); try { if(status.equals(value0)){ bool.setImageResource(R.drawable.boolean_off); //change color if statue=low to (usage, o) means off //note sure if it must be kept as set previously as default color. img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 0)); state.setText(stateS+Value_0); }else if(status.equals(value1)){ bool.setImageResource(R.drawable.boolean_on); //change color if statue=high to (usage, 2) means on img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2)); state.setText(stateS+Value_1); } } catch (Exception e) { Tracer.e(mytag, "handler error device "+wname); e.printStackTrace(); } } } else if(msg.what == 9998) { // state_engine send us a signal to notify it'll die ! Tracer.d(mytag,"state engine disappeared ===> Harakiri !" ); session = null; realtime = false; removeView(background); myself.setVisibility(GONE); if(container != null) { container.removeView(myself); container.recomputeViewAttributes(myself); } try { finalize(); } catch (Throwable t) {} //kill the handler thread itself } } }; //================================================================================ /* * New mechanism to be notified by widgetupdate engine when our value is changed * */ if(Tracer != null) { //state_engine = Tracer.get_engine(); if(Tracer.get_engine() != null) { session = new Entity_client(dev_id, state_key, mytag, handler); if(Tracer.get_engine().subscribe(session)) { realtime = true; //we're connected to engine //each time our value change, the engine will call handler handler.sendEmptyMessage(9999); //Force to consider current value in session } } } //================================================================================ }
diff --git a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java index 3bcd15b80..72c03e1e7 100644 --- a/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java +++ b/modules/activiti-engine/src/test/java/org/activiti/engine/test/bpmn/mail/EmailTestCase.java @@ -1,47 +1,45 @@ /* 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.activiti.engine.test.bpmn.mail; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.subethamail.wiser.Wiser; /** * @author Joram Barrez */ public class EmailTestCase extends PluggableActivitiTestCase { protected Wiser wiser; @Override protected void setUp() throws Exception { super.setUp(); wiser = new Wiser(); wiser.setPort(5025); wiser.start(); } @Override protected void tearDown() throws Exception { wiser.stop(); // Fix for slow Jenkins - while (wiser.getServer().isRunning()) { - Thread.sleep(100L); - } + Thread.sleep(250L); super.tearDown(); } }
true
true
protected void tearDown() throws Exception { wiser.stop(); // Fix for slow Jenkins while (wiser.getServer().isRunning()) { Thread.sleep(100L); } super.tearDown(); }
protected void tearDown() throws Exception { wiser.stop(); // Fix for slow Jenkins Thread.sleep(250L); super.tearDown(); }
diff --git a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java index 52714cdb..bc8b003f 100644 --- a/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java +++ b/src/edu/cornell/mannlib/vitro/webapp/visualization/utilities/UtilitiesRequestHandler.java @@ -1,490 +1,490 @@ /* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.visualization.utilities; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import com.google.gson.Gson; import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRIFactory; import com.hp.hpl.jena.iri.Violation; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.RDFNode; import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.Actions; import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap; import edu.cornell.mannlib.vitro.webapp.controller.freemarker.responsevalues.ResponseValues; import edu.cornell.mannlib.vitro.webapp.controller.visualization.VisualizationFrameworkConstants; import edu.cornell.mannlib.vitro.webapp.filestorage.FileServingHelper; import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels; import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException; import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.GenericQueryMap; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.AllPropertiesQueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.GenericQueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions; import edu.cornell.mannlib.vitro.webapp.visualization.visutils.VisualizationRequestHandler; /** * This request handler is used when you need helpful information to add more context * to the visualization. It does not have any code for generating the visualization, * just fires sparql queries to get info for specific cases like, * 1. thumbnail/image location for a particular individual * 2. profile information for a particular individual like label, moniker etc * 3. person level vis url for a particular individual * etc. * @author cdtank */ public class UtilitiesRequestHandler implements VisualizationRequestHandler { public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " - + "|| ?predicate = vitro:moniker " + + "|| ?predicate = core:preferredTitle " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:authorInAuthorship ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:linkedInformationResource ?document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasCo-PrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasPrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n" + "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } } private String getHighestLevelOrganizationTemporalGraphVisURL(ResultSet resultSet, Map<String, String> fieldLabelToOutputFieldLabel, VitroRequest vitroRequest) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode organizationNode = solution.get( fieldLabelToOutputFieldLabel .get("organization")); if (organizationNode != null) { queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organization"), organizationNode.toString()); String individualLocalName = UtilityFunctions.getIndividualLocalName( organizationNode.toString(), vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.PUBLICATION_TEMPORAL_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, organizationNode.toString(), VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } RDFNode organizationLabelNode = solution.get( fieldLabelToOutputFieldLabel .get("organizationLabel")); if (organizationLabelNode != null) { queryResult.addEntry(fieldLabelToOutputFieldLabel.get("organizationLabel"), organizationLabelNode.toString()); } RDFNode numberOfChildrenNode = solution.getLiteral("numOfChildren"); if (numberOfChildrenNode != null) { queryResult.addEntry("numOfChildren", String.valueOf(numberOfChildrenNode.asLiteral().getInt())); } } return ""; } private GenericQueryMap getNumberOfGrantsForIndividual(ResultSet resultSet) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode numberOfGrantsNode = solution.getLiteral("numOfGrants"); if (numberOfGrantsNode != null) { queryResult.addEntry("numOfGrants", String.valueOf(numberOfGrantsNode.asLiteral().getInt())); } } return queryResult; } private GenericQueryMap getNumberOfPublicationsForIndividual(ResultSet resultSet) { GenericQueryMap queryResult = new GenericQueryMap(); while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode numberOfPublicationsNode = solution.getLiteral("numOfPublications"); if (numberOfPublicationsNode != null) { queryResult.addEntry( "numOfPublications", String.valueOf(numberOfPublicationsNode.asLiteral().getInt())); } } return queryResult; } private String getThumbnailInformation(ResultSet resultSet, Map<String, String> fieldLabelToOutputFieldLabel, VitroRequest vitroRequest) { String finalThumbNailLocation = ""; while (resultSet.hasNext()) { QuerySolution solution = resultSet.nextSolution(); RDFNode downloadLocationNode = solution.get( fieldLabelToOutputFieldLabel .get("downloadLocation")); RDFNode fileNameNode = solution.get(fieldLabelToOutputFieldLabel.get("fileName")); if (downloadLocationNode != null && fileNameNode != null) { finalThumbNailLocation = FileServingHelper .getBytestreamAliasUrl(downloadLocationNode.toString(), fileNameNode.toString(), vitroRequest.getSession().getServletContext()); } } return finalThumbNailLocation; } @Override public Map<String, String> generateDataVisualization( VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities does not provide Data Response."); } @Override public ResponseValues generateStandardVisualization( VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities does not provide Standard Response."); } @Override public ResponseValues generateVisualizationForShortURLRequests( Map<String, String> parameters, VitroRequest vitroRequest, Log log, Dataset dataSource) throws MalformedQueryParametersException { throw new UnsupportedOperationException("Utilities Visualization does not provide " + "Short URL Response."); } @Override public Actions getRequiredPrivileges() { // TODO Auto-generated method stub return null; } }
true
true
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " + "|| ?predicate = vitro:moniker " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:authorInAuthorship ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:linkedInformationResource ?document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasCo-PrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasPrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n" + "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } }
public Object generateAjaxVisualization(VitroRequest vitroRequest, Log log, Dataset dataset) throws MalformedQueryParametersException { String individualURI = vitroRequest.getParameter( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY); String visMode = vitroRequest.getParameter( VisualizationFrameworkConstants.VIS_MODE_KEY); /* * If the info being requested is about a profile which includes the name, moniker * & image url. * */ if (VisualizationFrameworkConstants.PROFILE_INFO_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String filterRule = "?predicate = j.2:mainImage " + "|| ?predicate = core:preferredTitle " + "|| ?predicate = rdfs:label"; QueryRunner<GenericQueryMap> profileQueryHandler = new AllPropertiesQueryRunner(individualURI, filterRule, dataset, log); GenericQueryMap profilePropertiesToValues = profileQueryHandler.getQueryResult(); Gson profileInformation = new Gson(); return profileInformation.toJson(profilePropertiesToValues); } else if (VisualizationFrameworkConstants.IMAGE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * If the url being requested is about a standalone image, which is used when we * want to render an image & other info for a co-author OR ego for that matter. * */ Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("downloadLocation", QueryFieldLabels.THUMBNAIL_LOCATION_URL); fieldLabelToOutputFieldLabel.put("fileName", QueryFieldLabels.THUMBNAIL_FILENAME); String whereClause = "<" + individualURI + "> j.2:thumbnailImage ?thumbnailImage . " + "?thumbnailImage j.2:downloadLocation " + "?downloadLocation ; j.2:filename ?fileName ."; QueryRunner<ResultSet> imageQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, "", whereClause, "", dataset); return getThumbnailInformation(imageQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else if (VisualizationFrameworkConstants.ARE_PUBLICATIONS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?document) AS ?numOfPublications)"; String whereClause = "<" + individualURI + "> rdf:type foaf:Person ;" + " core:authorInAuthorship ?authorshipNode . \n" + "?authorshipNode rdf:type core:Authorship ;" + " core:linkedInformationResource ?document ."; String groupOrderClause = "GROUP BY ?" + QueryFieldLabels.AUTHOR_URL + " \n"; QueryRunner<ResultSet> numberOfPublicationsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); Gson publicationsInformation = new Gson(); return publicationsInformation.toJson(getNumberOfPublicationsForIndividual( numberOfPublicationsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.ARE_GRANTS_AVAILABLE_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); String aggregationRules = "(count(DISTINCT ?Grant) AS ?numOfGrants)"; String whereClause = "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasCo-PrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasPrincipalInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }" + "UNION \n" + "{ <" + individualURI + "> rdf:type foaf:Person ;" + " core:hasInvestigatorRole ?Role . \n" + "?Role core:roleIn ?Grant . }"; QueryRunner<ResultSet> numberOfGrantsQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, "", dataset); Gson grantsInformation = new Gson(); return grantsInformation.toJson(getNumberOfGrantsForIndividual( numberOfGrantsQueryHandler.getQueryResult())); } else if (VisualizationFrameworkConstants.COAUTHOR_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COAUTHORSHIP_VIS_SHORT_URL + "/" + individualLocalName; } ParamMap coAuthorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COAUTHOR_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coAuthorProfileURLParams); } else if (VisualizationFrameworkConstants.COPI_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { String individualLocalName = UtilityFunctions.getIndividualLocalName( individualURI, vitroRequest); if (StringUtils.isNotBlank(individualLocalName)) { return UrlBuilder.getUrl(VisualizationFrameworkConstants.SHORT_URL_VISUALIZATION_REQUEST_PREFIX) + "/" + VisualizationFrameworkConstants.COINVESTIGATOR_VIS_SHORT_URL + "/" + individualLocalName; } /* * By default we will be generating profile url else some specific url like * coPI vis url for that individual. * */ ParamMap coInvestigatorProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.VIS_MODE_KEY, VisualizationFrameworkConstants.COPI_VIS_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, coInvestigatorProfileURLParams); } else if (VisualizationFrameworkConstants.PERSON_LEVEL_UTILS_VIS_MODE .equalsIgnoreCase(visMode)) { /* * By default we will be generating profile url else some specific url like * coAuthorShip vis url for that individual. * */ ParamMap personLevelURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.PERSON_LEVEL_VIS, VisualizationFrameworkConstants.RENDER_MODE_KEY, VisualizationFrameworkConstants.STANDALONE_RENDER_MODE); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, personLevelURLParams); } else if (VisualizationFrameworkConstants.HIGHEST_LEVEL_ORGANIZATION_VIS_MODE .equalsIgnoreCase(visMode)) { String staffProvidedHighestLevelOrganization = ConfigurationProperties .getBean(vitroRequest).getProperty("visualization.topLevelOrg"); /* * First checking if the staff has provided highest level organization in * deploy.properties if so use to temporal graph vis. * */ if (StringUtils.isNotBlank(staffProvidedHighestLevelOrganization)) { /* * To test for the validity of the URI submitted. * */ IRIFactory iRIFactory = IRIFactory.jenaImplementation(); IRI iri = iRIFactory.create(staffProvidedHighestLevelOrganization); if (iri.hasViolation(false)) { String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage(); log.error("Highest Level Organization URI provided is invalid " + errorMsg); } else { ParamMap highestLevelOrganizationTemporalGraphVisURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, staffProvidedHighestLevelOrganization, VisualizationFrameworkConstants.VIS_TYPE_KEY, VisualizationFrameworkConstants.ENTITY_COMPARISON_VIS); return UrlBuilder.getUrl( VisualizationFrameworkConstants.FREEMARKERIZED_VISUALIZATION_URL_PREFIX, highestLevelOrganizationTemporalGraphVisURLParams); } } Map<String, String> fieldLabelToOutputFieldLabel = new HashMap<String, String>(); fieldLabelToOutputFieldLabel.put("organization", QueryFieldLabels.ORGANIZATION_URL); fieldLabelToOutputFieldLabel.put("organizationLabel", QueryFieldLabels.ORGANIZATION_LABEL); String aggregationRules = "(count(?organization) AS ?numOfChildren)"; String whereClause = "?organization rdf:type foaf:Organization ;" + " rdfs:label ?organizationLabel . \n" + "OPTIONAL { ?organization core:hasSubOrganization ?subOrg } . \n" + "OPTIONAL { ?organization core:subOrganizationWithin ?parent } . \n" + "FILTER ( !bound(?parent) ). \n"; String groupOrderClause = "GROUP BY ?organization ?organizationLabel \n" + "ORDER BY DESC(?numOfChildren)\n" + "LIMIT 1\n"; QueryRunner<ResultSet> highestLevelOrganizationQueryHandler = new GenericQueryRunner(fieldLabelToOutputFieldLabel, aggregationRules, whereClause, groupOrderClause, dataset); return getHighestLevelOrganizationTemporalGraphVisURL( highestLevelOrganizationQueryHandler.getQueryResult(), fieldLabelToOutputFieldLabel, vitroRequest); } else { ParamMap individualProfileURLParams = new ParamMap( VisualizationFrameworkConstants.INDIVIDUAL_URI_KEY, individualURI); return UrlBuilder.getUrl(VisualizationFrameworkConstants.INDIVIDUAL_URL_PREFIX, individualProfileURLParams); } }
diff --git a/src/main/java/net/frontlinesms/ui/handler/email/EmailAccountDialogHandler.java b/src/main/java/net/frontlinesms/ui/handler/email/EmailAccountDialogHandler.java index 78afebe..484f315 100644 --- a/src/main/java/net/frontlinesms/ui/handler/email/EmailAccountDialogHandler.java +++ b/src/main/java/net/frontlinesms/ui/handler/email/EmailAccountDialogHandler.java @@ -1,344 +1,345 @@ /** * */ package net.frontlinesms.ui.handler.email; import org.apache.log4j.Logger; import net.frontlinesms.EmailSender; import net.frontlinesms.EmailServerHandler; import net.frontlinesms.FrontlineSMS; import net.frontlinesms.Utils; import net.frontlinesms.data.DuplicateKeyException; import net.frontlinesms.data.domain.EmailAccount; import net.frontlinesms.data.repository.EmailAccountDao; import net.frontlinesms.ui.Icon; import net.frontlinesms.ui.ThinletUiEventHandler; import net.frontlinesms.ui.UiGeneratorController; import net.frontlinesms.ui.handler.keyword.EmailActionDialog; import net.frontlinesms.ui.i18n.InternationalisationUtils; import net.frontlinesms.ui.i18n.TextResourceKeyOwner; /** * @author aga * */ @TextResourceKeyOwner public class EmailAccountDialogHandler implements ThinletUiEventHandler { //> UI LAYOUT FILES public static final String UI_FILE_EMAIL_ACCOUNTS_SETTINGS_FORM = "/ui/core/email/dgServerConfig.xml"; public static final String UI_FILE_CONNECTION_WARNING_FORM = "/ui/core/email/dgConnectionWarning.xml"; public static final String UI_FILE_EMAIL_ACCOUNT_FORM = "/ui/core/email/dgAccountSettings.xml"; //> UI COMPONENT NAMES public static final String COMPONENT_ACCOUNTS_LIST = "accountsList"; public static final String COMPONENT_TF_ACCOUNT = "tfAccount"; public static final String COMPONENT_TF_ACCOUNT_PASS = "tfAccountPass"; public static final String COMPONENT_TF_ACCOUNT_SERVER_PORT = "tfPort"; public static final String COMPONENT_TF_MAIL_SERVER = "tfMailServer"; public static final String COMPONENT_CB_USE_SSL = "cbUseSSL"; //> I18N TEXT KEYS public static final String I18N_EDITING_EMAIL_ACCOUNT = "common.editing.email.account"; public static final String I18N_ACCOUNT_NAME_BLANK = "message.account.name.blank"; public static final String I18N_ACCOUNT_NAME_ALREADY_EXISTS = "message.account.already.exists"; //> INSTANCE PROPERTIES /** Logger */ private Logger LOG = Utils.getLogger(this.getClass()); private UiGeneratorController ui; private EmailAccountDao emailAccountDao; /** Manager of {@link EmailAccount}s and {@link EmailSender}s */ private EmailServerHandler emailManager; private Object dialogComponent; public EmailAccountDialogHandler(UiGeneratorController ui) { this.ui = ui; FrontlineSMS frontlineController = ui.getFrontlineController(); this.emailAccountDao = frontlineController.getEmailAccountFactory(); this.emailManager = frontlineController.getEmailServerHandler(); } public Object getDialog() { initDialog(); return this.dialogComponent; } private void initDialog() { this.dialogComponent = ui.loadComponentFromFile(UI_FILE_EMAIL_ACCOUNTS_SETTINGS_FORM, this); this.refreshAccountsList(); } private void refreshAccountsList() { Object table = find(COMPONENT_ACCOUNTS_LIST); this.ui.removeAll(table); for (EmailAccount acc : emailAccountDao.getAllEmailAccounts()) { this.ui.add(table, ui.getRow(acc)); } } //> UI EVENT METHODS /** * Shows the email accounts settings dialog. */ public void showEmailAccountsSettings(Object dialog) { ui.setAttachedObject(this.dialogComponent, dialog); ui.add(this.dialogComponent); } public void finishEmailManagement(Object dialog) { Object att = ui.getAttachedObject(dialog); if (att != null) { Object list = ui.find(att, COMPONENT_ACCOUNTS_LIST); ui.removeAll(list); for (EmailAccount acc : emailAccountDao.getAllEmailAccounts()) { Object item = ui.createListItem(acc.getAccountName(), acc); ui.setIcon(item, Icon.SERVER); ui.add(list, item); } } ui.removeDialog(dialog); } /** * After failing to connect to the email server, the user has an option to * create the account anyway. This method handles this action. * * @param currentDialog */ public void createAccount(Object currentDialog) { LOG.trace("ENTER"); ui.removeDialog(currentDialog); LOG.debug("Creating account anyway!"); Object accountDialog = ui.getAttachedObject(currentDialog); String server = ui.getText(ui.find(accountDialog, COMPONENT_TF_MAIL_SERVER)); String accountName = ui.getText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT)); String password = ui.getText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT_PASS)); boolean useSSL = ui.isSelected(ui.find(accountDialog, COMPONENT_CB_USE_SSL)); String portAsString = ui.getText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT_SERVER_PORT)); int serverPort; try { serverPort = Integer.parseInt(portAsString); } catch (NumberFormatException e1) { if (useSSL) serverPort = EmailAccount.DEFAULT_SMTPS_PORT; else serverPort = EmailAccount.DEFAULT_SMTP_PORT; } Object table = ui.find(accountDialog, COMPONENT_ACCOUNTS_LIST); LOG.debug("Server Name [" + server + "]"); LOG.debug("Account Name [" + accountName + "]"); LOG.debug("Account Server Port [" + serverPort + "]"); LOG.debug("SSL [" + useSSL + "]"); EmailAccount acc; try { acc = new EmailAccount(accountName, server, serverPort, password, useSSL); emailAccountDao.saveEmailAccount(acc); } catch (DuplicateKeyException e) { LOG.debug("Account already exists", e); ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS)); LOG.trace("EXIT"); return; } LOG.debug("Account [" + acc.getAccountName() + "] created!"); //ui.add(table, ui.getRow(acc)); this.refreshAccountsList(); cleanEmailAccountFields(accountDialog); LOG.trace("EXIT"); } /** * This method is called when the save button is pressed in the new mail account dialog. * @param dialog */ public void saveEmailAccount(Object dialog) { LOG.trace("ENTER"); String server = ui.getText(ui.find(dialog, COMPONENT_TF_MAIL_SERVER)); String accountName = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT)); String password = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_PASS)); boolean useSSL = ui.isSelected(ui.find(dialog, COMPONENT_CB_USE_SSL)); String portAsString = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_SERVER_PORT)); int serverPort; try { serverPort = Integer.parseInt(portAsString); } catch (NumberFormatException e1) { if (useSSL) serverPort = EmailAccount.DEFAULT_SMTPS_PORT; else serverPort = EmailAccount.DEFAULT_SMTP_PORT; } Object table = ui.find(dialog, COMPONENT_ACCOUNTS_LIST); LOG.debug("Server [" + server + "]"); LOG.debug("Account [" + accountName + "]"); LOG.debug("Account Server Port [" + serverPort + "]"); LOG.debug("SSL [" + useSSL + "]"); if (accountName.equals("")) { ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_BLANK)); LOG.trace("EXIT"); return; } try { Object att = ui.getAttachedObject(dialog); if (att == null || !(att instanceof EmailAccount)) { LOG.debug("Testing connection to [" + server + "]"); if (EmailSender.testConnection(server, accountName, serverPort, password, useSSL)) { LOG.debug("Connection was successful, creating account [" + accountName + "]"); EmailAccount account = new EmailAccount(accountName, server, serverPort, password, useSSL); emailAccountDao.saveEmailAccount(account); ui.add(table, ui.getRow(account)); cleanEmailAccountFields(dialog); } else { LOG.debug("Connection failed."); Object connectWarning = ui.loadComponentFromFile(UI_FILE_CONNECTION_WARNING_FORM, this); ui.setAttachedObject(connectWarning, dialog); ui.add(connectWarning); } } else if (att instanceof EmailAccount) { EmailAccount acc = (EmailAccount) att; acc.setAccountName(accountName); acc.setAccountPassword(password); acc.setAccountServer(server); acc.setUseSSL(useSSL); acc.setAccountServerPort(serverPort); + emailAccountDao.updateEmailAccount(acc); Object tableToAdd = ui.find(ui.find("emailConfigDialog"), COMPONENT_ACCOUNTS_LIST); int index = ui.getSelectedIndex(tableToAdd); ui.remove(ui.getSelectedItem(tableToAdd)); ui.add(tableToAdd, ui.getRow(acc), index); ui.setSelectedIndex(tableToAdd, index); ui.removeDialog(dialog); } } catch (DuplicateKeyException e) { LOG.debug(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS), e); ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS)); } LOG.trace("EXIT"); } public void showEmailAccountDialog(Object list) { Object selected = ui.getSelectedItem(list); if (selected != null) { EmailAccount acc = (EmailAccount) ui.getAttachedObject(selected); showEmailAccountDialog(acc); } } /** * Enables or disables menu options in a List Component's popup list * and toolbar. These enablements are based on whether any items in * the list are selected, and if they are, on the nature of these * items. * @param list * @param popup * @param toolbar * * TODO check where this is used, and make sure there is no dead code */ public void enableOptions(Object list, Object popup, Object toolbar) { Object[] selectedItems = ui.getSelectedItems(list); boolean hasSelection = selectedItems.length > 0; if(popup!= null && !hasSelection && "emailServerListPopup".equals(ui.getName(popup))) { ui.setVisible(popup, false); return; } if (hasSelection && popup != null) { // If nothing is selected, hide the popup menu ui.setVisible(popup, hasSelection); } if (toolbar != null && !toolbar.equals(popup)) { for (Object o : ui.getItems(toolbar)) { ui.setEnabled(o, hasSelection); } } } /** * Removes the selected accounts. */ public void removeSelectedFromAccountList() { LOG.trace("ENTER"); ui.removeConfirmationDialog(); Object list = find(COMPONENT_ACCOUNTS_LIST); Object[] selected = ui.getSelectedItems(list); for (Object o : selected) { EmailAccount acc = ui.getAttachedObject(o, EmailAccount.class); LOG.debug("Removing Account [" + acc.getAccountName() + "]"); emailManager.serverRemoved(acc); emailAccountDao.deleteEmailAccount(acc); } this.refreshAccountsList(); LOG.trace("EXIT"); } //> UI PASSTHROUGH METHODS /** @see UiGeneratorController#showConfirmationDialog(String, Object) */ public void showConfirmationDialog(String methodToBeCalled) { this.ui.showConfirmationDialog(methodToBeCalled, this); } /** * @param page page to show * @see UiGeneratorController#showHelpPage(String) */ public void showHelpPage(String page) { this.ui.showHelpPage(page); } /** @see UiGeneratorController#removeDialog(Object) */ public void removeDialog(Object dialog) { this.ui.removeDialog(dialog); } //> UI HELPER METHODS /** * Find a UI component within the {@link #dialogComponent}. * @param componentName the name of the UI component * @return the ui component, or <code>null</code> if it could not be found */ private Object find(String componentName) { return ui.find(this.dialogComponent, componentName); } private void cleanEmailAccountFields(Object accountDialog) { ui.setText(ui.find(accountDialog, COMPONENT_TF_MAIL_SERVER), ""); ui.setText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT), ""); ui.setText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT_PASS), ""); ui.setText(ui.find(accountDialog, COMPONENT_TF_ACCOUNT_SERVER_PORT), ""); ui.setSelected(ui.find(accountDialog, COMPONENT_CB_USE_SSL), true); } /** * Event fired when the view phone details action is chosen. */ private void showEmailAccountDialog(EmailAccount acc) { Object settingsDialog = ui.loadComponentFromFile(UI_FILE_EMAIL_ACCOUNT_FORM, this); ui.setText(settingsDialog, InternationalisationUtils.getI18NString(I18N_EDITING_EMAIL_ACCOUNT, acc.getAccountName())); Object tfServer = ui.find(settingsDialog, COMPONENT_TF_MAIL_SERVER); Object tfAccountName = ui.find(settingsDialog, COMPONENT_TF_ACCOUNT); Object tfPassword = ui.find(settingsDialog, COMPONENT_TF_ACCOUNT_PASS); Object cbUseSSL = ui.find(settingsDialog, COMPONENT_CB_USE_SSL); Object tfPort = ui.find(settingsDialog, COMPONENT_TF_ACCOUNT_SERVER_PORT); ui.setText(tfServer, acc.getAccountServer()); ui.setText(tfAccountName, acc.getAccountName()); ui.setText(tfPassword, acc.getAccountPassword()); ui.setSelected(cbUseSSL, acc.useSsl()); ui.setText(tfPort, String.valueOf(acc.getAccountServerPort())); ui.setAttachedObject(settingsDialog, acc); ui.add(settingsDialog); } }
true
true
public void saveEmailAccount(Object dialog) { LOG.trace("ENTER"); String server = ui.getText(ui.find(dialog, COMPONENT_TF_MAIL_SERVER)); String accountName = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT)); String password = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_PASS)); boolean useSSL = ui.isSelected(ui.find(dialog, COMPONENT_CB_USE_SSL)); String portAsString = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_SERVER_PORT)); int serverPort; try { serverPort = Integer.parseInt(portAsString); } catch (NumberFormatException e1) { if (useSSL) serverPort = EmailAccount.DEFAULT_SMTPS_PORT; else serverPort = EmailAccount.DEFAULT_SMTP_PORT; } Object table = ui.find(dialog, COMPONENT_ACCOUNTS_LIST); LOG.debug("Server [" + server + "]"); LOG.debug("Account [" + accountName + "]"); LOG.debug("Account Server Port [" + serverPort + "]"); LOG.debug("SSL [" + useSSL + "]"); if (accountName.equals("")) { ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_BLANK)); LOG.trace("EXIT"); return; } try { Object att = ui.getAttachedObject(dialog); if (att == null || !(att instanceof EmailAccount)) { LOG.debug("Testing connection to [" + server + "]"); if (EmailSender.testConnection(server, accountName, serverPort, password, useSSL)) { LOG.debug("Connection was successful, creating account [" + accountName + "]"); EmailAccount account = new EmailAccount(accountName, server, serverPort, password, useSSL); emailAccountDao.saveEmailAccount(account); ui.add(table, ui.getRow(account)); cleanEmailAccountFields(dialog); } else { LOG.debug("Connection failed."); Object connectWarning = ui.loadComponentFromFile(UI_FILE_CONNECTION_WARNING_FORM, this); ui.setAttachedObject(connectWarning, dialog); ui.add(connectWarning); } } else if (att instanceof EmailAccount) { EmailAccount acc = (EmailAccount) att; acc.setAccountName(accountName); acc.setAccountPassword(password); acc.setAccountServer(server); acc.setUseSSL(useSSL); acc.setAccountServerPort(serverPort); Object tableToAdd = ui.find(ui.find("emailConfigDialog"), COMPONENT_ACCOUNTS_LIST); int index = ui.getSelectedIndex(tableToAdd); ui.remove(ui.getSelectedItem(tableToAdd)); ui.add(tableToAdd, ui.getRow(acc), index); ui.setSelectedIndex(tableToAdd, index); ui.removeDialog(dialog); } } catch (DuplicateKeyException e) { LOG.debug(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS), e); ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS)); } LOG.trace("EXIT"); }
public void saveEmailAccount(Object dialog) { LOG.trace("ENTER"); String server = ui.getText(ui.find(dialog, COMPONENT_TF_MAIL_SERVER)); String accountName = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT)); String password = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_PASS)); boolean useSSL = ui.isSelected(ui.find(dialog, COMPONENT_CB_USE_SSL)); String portAsString = ui.getText(ui.find(dialog, COMPONENT_TF_ACCOUNT_SERVER_PORT)); int serverPort; try { serverPort = Integer.parseInt(portAsString); } catch (NumberFormatException e1) { if (useSSL) serverPort = EmailAccount.DEFAULT_SMTPS_PORT; else serverPort = EmailAccount.DEFAULT_SMTP_PORT; } Object table = ui.find(dialog, COMPONENT_ACCOUNTS_LIST); LOG.debug("Server [" + server + "]"); LOG.debug("Account [" + accountName + "]"); LOG.debug("Account Server Port [" + serverPort + "]"); LOG.debug("SSL [" + useSSL + "]"); if (accountName.equals("")) { ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_BLANK)); LOG.trace("EXIT"); return; } try { Object att = ui.getAttachedObject(dialog); if (att == null || !(att instanceof EmailAccount)) { LOG.debug("Testing connection to [" + server + "]"); if (EmailSender.testConnection(server, accountName, serverPort, password, useSSL)) { LOG.debug("Connection was successful, creating account [" + accountName + "]"); EmailAccount account = new EmailAccount(accountName, server, serverPort, password, useSSL); emailAccountDao.saveEmailAccount(account); ui.add(table, ui.getRow(account)); cleanEmailAccountFields(dialog); } else { LOG.debug("Connection failed."); Object connectWarning = ui.loadComponentFromFile(UI_FILE_CONNECTION_WARNING_FORM, this); ui.setAttachedObject(connectWarning, dialog); ui.add(connectWarning); } } else if (att instanceof EmailAccount) { EmailAccount acc = (EmailAccount) att; acc.setAccountName(accountName); acc.setAccountPassword(password); acc.setAccountServer(server); acc.setUseSSL(useSSL); acc.setAccountServerPort(serverPort); emailAccountDao.updateEmailAccount(acc); Object tableToAdd = ui.find(ui.find("emailConfigDialog"), COMPONENT_ACCOUNTS_LIST); int index = ui.getSelectedIndex(tableToAdd); ui.remove(ui.getSelectedItem(tableToAdd)); ui.add(tableToAdd, ui.getRow(acc), index); ui.setSelectedIndex(tableToAdd, index); ui.removeDialog(dialog); } } catch (DuplicateKeyException e) { LOG.debug(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS), e); ui.alert(InternationalisationUtils.getI18NString(I18N_ACCOUNT_NAME_ALREADY_EXISTS)); } LOG.trace("EXIT"); }
diff --git a/plugins/cloud/src/main/java/org/elasticsearch/discovery/cloud/CloudDiscovery.java b/plugins/cloud/src/main/java/org/elasticsearch/discovery/cloud/CloudDiscovery.java index efce1dbc466..a85dd1f538a 100644 --- a/plugins/cloud/src/main/java/org/elasticsearch/discovery/cloud/CloudDiscovery.java +++ b/plugins/cloud/src/main/java/org/elasticsearch/discovery/cloud/CloudDiscovery.java @@ -1,45 +1,47 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.discovery.cloud; import org.elasticsearch.cloud.compute.CloudComputeService; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.discovery.zen.ZenDiscovery; import org.elasticsearch.discovery.zen.ping.ZenPingService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.elasticsearch.util.collect.ImmutableList; import org.elasticsearch.util.guice.inject.Inject; import org.elasticsearch.util.settings.Settings; /** * @author kimchy (shay.banon) */ public class CloudDiscovery extends ZenDiscovery { @Inject public CloudDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, ZenPingService pingService, CloudComputeService computeService) { super(settings, clusterName, threadPool, transportService, clusterService, pingService); if (settings.getAsBoolean("cloud.enabled", true)) { - pingService.zenPings(ImmutableList.of(new CloudZenPing(settings, threadPool, transportService, clusterName, computeService))); + CloudZenPing cloudPing = new CloudZenPing(settings, threadPool, transportService, clusterName, computeService); + cloudPing.setNodesProvider(this); + pingService.zenPings(ImmutableList.of(cloudPing)); } } }
true
true
@Inject public CloudDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, ZenPingService pingService, CloudComputeService computeService) { super(settings, clusterName, threadPool, transportService, clusterService, pingService); if (settings.getAsBoolean("cloud.enabled", true)) { pingService.zenPings(ImmutableList.of(new CloudZenPing(settings, threadPool, transportService, clusterName, computeService))); } }
@Inject public CloudDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool, TransportService transportService, ClusterService clusterService, ZenPingService pingService, CloudComputeService computeService) { super(settings, clusterName, threadPool, transportService, clusterService, pingService); if (settings.getAsBoolean("cloud.enabled", true)) { CloudZenPing cloudPing = new CloudZenPing(settings, threadPool, transportService, clusterName, computeService); cloudPing.setNodesProvider(this); pingService.zenPings(ImmutableList.of(cloudPing)); } }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java index 38d2397f2..16dad906e 100644 --- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java +++ b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java @@ -1,1608 +1,1611 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/org/documents/epl-v10.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.eclipse.adt.internal.launch; import com.android.ddmlib.AndroidDebugBridge; import com.android.ddmlib.Client; import com.android.ddmlib.ClientData; import com.android.ddmlib.IDevice; import com.android.ddmlib.Log; import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener; import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener; import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener; import com.android.ddmlib.ClientData.DebuggerStatus; import com.android.ide.eclipse.adt.AdtPlugin; import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration.TargetMode; import com.android.ide.eclipse.adt.internal.launch.DelayedLaunchInfo.InstallRetryMode; import com.android.ide.eclipse.adt.internal.launch.DeviceChooserDialog.DeviceChooserResponse; import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs; import com.android.ide.eclipse.adt.internal.project.AndroidManifestParser; import com.android.ide.eclipse.adt.internal.project.ApkInstallManager; import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper; import com.android.ide.eclipse.adt.internal.project.ProjectHelper; import com.android.ide.eclipse.adt.internal.sdk.Sdk; import com.android.ide.eclipse.adt.internal.wizards.actions.AvdManagerAction; import com.android.prefs.AndroidLocation.AndroidLocationException; import com.android.sdklib.AndroidVersion; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.NullSdkLog; import com.android.sdklib.internal.avd.AvdManager; import com.android.sdklib.internal.avd.AvdManager.AvdInfo; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jdt.launching.IVMConnector; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; /** * Controls the launch of Android application either on a device or on the * emulator. If an emulator is already running, this class will attempt to reuse * it. */ public final class AndroidLaunchController implements IDebugBridgeChangeListener, IDeviceChangeListener, IClientChangeListener, ILaunchController { private static final String FLAG_AVD = "-avd"; //$NON-NLS-1$ private static final String FLAG_NETDELAY = "-netdelay"; //$NON-NLS-1$ private static final String FLAG_NETSPEED = "-netspeed"; //$NON-NLS-1$ private static final String FLAG_WIPE_DATA = "-wipe-data"; //$NON-NLS-1$ private static final String FLAG_NO_BOOT_ANIM = "-no-boot-anim"; //$NON-NLS-1$ /** * Map to store {@link ILaunchConfiguration} objects that must be launched as simple connection * to running application. The integer is the port on which to connect. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private static final HashMap<ILaunchConfiguration, Integer> sRunningAppMap = new HashMap<ILaunchConfiguration, Integer>(); private static final Object sListLock = sRunningAppMap; /** * List of {@link DelayedLaunchInfo} waiting for an emulator to connect. * <p>Once an emulator has connected, {@link DelayedLaunchInfo#getDevice()} is set and the * DelayedLaunchInfo object is moved to * {@link AndroidLaunchController#mWaitingForReadyEmulatorList}. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<DelayedLaunchInfo> mWaitingForEmulatorLaunches = new ArrayList<DelayedLaunchInfo>(); /** * List of application waiting to be launched on a device/emulator.<br> * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> * */ private final ArrayList<DelayedLaunchInfo> mWaitingForReadyEmulatorList = new ArrayList<DelayedLaunchInfo>(); /** * Application waiting to show up as waiting for debugger. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<DelayedLaunchInfo> mWaitingForDebuggerApplications = new ArrayList<DelayedLaunchInfo>(); /** * List of clients that have appeared as waiting for debugger before their name was available. * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b> */ private final ArrayList<Client> mUnknownClientsWaitingForDebugger = new ArrayList<Client>(); /** static instance for singleton */ private static AndroidLaunchController sThis = new AndroidLaunchController(); /** private constructor to enforce singleton */ private AndroidLaunchController() { AndroidDebugBridge.addDebugBridgeChangeListener(this); AndroidDebugBridge.addDeviceChangeListener(this); AndroidDebugBridge.addClientChangeListener(this); } /** * Returns the singleton reference. */ public static AndroidLaunchController getInstance() { return sThis; } /** * Launches a remote java debugging session on an already running application * @param project The project of the application to debug. * @param debugPort The port to connect the debugger to. */ public static void debugRunningApp(IProject project, int debugPort) { // get an existing or new launch configuration ILaunchConfiguration config = AndroidLaunchController.getLaunchConfig(project); if (config != null) { setPortLaunchConfigAssociation(config, debugPort); // and launch DebugUITools.launch(config, ILaunchManager.DEBUG_MODE); } } /** * Returns an {@link ILaunchConfiguration} for the specified {@link IProject}. * @param project the project * @return a new or already existing <code>ILaunchConfiguration</code> or null if there was * an error when creating a new one. */ public static ILaunchConfiguration getLaunchConfig(IProject project) { // get the launch manager ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager(); // now get the config type for our particular android type. ILaunchConfigurationType configType = manager.getLaunchConfigurationType( LaunchConfigDelegate.ANDROID_LAUNCH_TYPE_ID); String name = project.getName(); // search for an existing launch configuration ILaunchConfiguration config = findConfig(manager, configType, name); // test if we found one or not if (config == null) { // Didn't find a matching config, so we make one. // It'll be made in the "working copy" object first. ILaunchConfigurationWorkingCopy wc = null; try { // make the working copy object wc = configType.newInstance(null, manager.generateUniqueLaunchConfigurationNameFrom(name)); // set the project name wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, name); // set the launch mode to default. wc.setAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION, LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION); // set default target mode wc.setAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE, LaunchConfigDelegate.DEFAULT_TARGET_MODE.getValue()); // default AVD: None wc.setAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, (String) null); // set the default network speed wc.setAttribute(LaunchConfigDelegate.ATTR_SPEED, LaunchConfigDelegate.DEFAULT_SPEED); // and delay wc.setAttribute(LaunchConfigDelegate.ATTR_DELAY, LaunchConfigDelegate.DEFAULT_DELAY); // default wipe data mode wc.setAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA, LaunchConfigDelegate.DEFAULT_WIPE_DATA); // default disable boot animation option wc.setAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM, LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM); // set default emulator options IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore(); String emuOptions = store.getString(AdtPrefs.PREFS_EMU_OPTIONS); wc.setAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE, emuOptions); // map the config and the project wc.setMappedResources(getResourcesToMap(project)); // save the working copy to get the launch config object which we return. return wc.doSave(); } catch (CoreException e) { String msg = String.format( "Failed to create a Launch config for project '%1$s': %2$s", project.getName(), e.getMessage()); AdtPlugin.printErrorToConsole(project, msg); // no launch! return null; } } return config; } /** * Returns the list of resources to map to a Launch Configuration. * @param project the project associated to the launch configuration. */ public static IResource[] getResourcesToMap(IProject project) { ArrayList<IResource> array = new ArrayList<IResource>(2); array.add(project); IFile manifest = AndroidManifestParser.getManifest(project); if (manifest != null) { array.add(manifest); } return array.toArray(new IResource[array.size()]); } /** * Launches an android app on the device or emulator * * @param project The project we're launching * @param mode the mode in which to launch, one of the mode constants * defined by <code>ILaunchManager</code> - <code>RUN_MODE</code> or * <code>DEBUG_MODE</code>. * @param apk the resource to the apk to launch. * @param packageName the Android package name of the app * @param debugPackageName the Android package name to debug * @param debuggable the debuggable value of the app, or null if not set. * @param requiredApiVersionNumber the api version required by the app, or null if none. * @param launchAction the action to perform after app sync * @param config the launch configuration * @param launch the launch object */ public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); - if (deviceVersion.canRun(projectTarget.getVersion())) { + // the deviceVersion may be null if it wasn't yet queried (device just + // plugged in or emulator just booting up. + if (deviceVersion != null && + deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); } /** * Find a matching AVD. */ private AvdInfo findMatchingAvd(AvdManager avdManager, final IAndroidTarget projectTarget) { AvdInfo[] avds = avdManager.getValidAvds(); AvdInfo defaultAvd = null; for (AvdInfo avd : avds) { if (projectTarget.isCompatibleBaseFor(avd.getTarget())) { // at this point we can ignore the code name issue since // IAndroidTarget.isCompatibleBaseFor() will already have filtered the non // compatible AVDs. if (defaultAvd == null || avd.getTarget().getVersion().getApiLevel() < defaultAvd.getTarget().getVersion().getApiLevel()) { defaultAvd = avd; } } } return defaultAvd; } /** * Continues the launch based on the DeviceChooser response. * @param response the device chooser response * @param project The project being launched * @param launch The eclipse launch info * @param launchInfo The {@link DelayedLaunchInfo} * @param config The config needed to start a new emulator. */ void continueLaunch(final DeviceChooserResponse response, final IProject project, final AndroidLaunch launch, final DelayedLaunchInfo launchInfo, final AndroidLaunchConfiguration config) { // Since this is called from the UI thread we spawn a new thread // to finish the launch. new Thread() { @Override public void run() { if (response.getAvdToLaunch() != null) { // there was no selected device, we start a new emulator. synchronized (sListLock) { AvdInfo info = response.getAvdToLaunch(); mWaitingForEmulatorLaunches.add(launchInfo); AdtPlugin.printToConsole(project, String.format( "Launching a new emulator with Virtual Device '%1$s'", info.getName())); boolean status = launchEmulator(config, info); if (status == false) { // launching the emulator failed! AdtPlugin.displayError("Emulator Launch", "Couldn't launch the emulator! Make sure the SDK directory is properly setup and the emulator is not missing."); // stop the launch and return mWaitingForEmulatorLaunches.remove(launchInfo); AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } return; } } else if (response.getDeviceToUse() != null) { launchInfo.setDevice(response.getDeviceToUse()); simpleLaunch(launchInfo, launchInfo.getDevice()); } } }.start(); } /** * Queries for a debugger port for a specific {@link ILaunchConfiguration}. * <p/> * If the configuration and a debugger port where added through * {@link #setPortLaunchConfigAssociation(ILaunchConfiguration, int)}, then this method * will return the debugger port, and remove the configuration from the list. * @param launchConfig the {@link ILaunchConfiguration} * @return the debugger port or {@link LaunchConfigDelegate#INVALID_DEBUG_PORT} if the * configuration was not setup. */ static int getPortForConfig(ILaunchConfiguration launchConfig) { synchronized (sListLock) { Integer port = sRunningAppMap.get(launchConfig); if (port != null) { sRunningAppMap.remove(launchConfig); return port; } } return LaunchConfigDelegate.INVALID_DEBUG_PORT; } /** * Set a {@link ILaunchConfiguration} and its associated debug port, in the list of * launch config to connect directly to a running app instead of doing full launch (sync, * launch, and connect to). * @param launchConfig the {@link ILaunchConfiguration} object. * @param port The debugger port to connect to. */ private static void setPortLaunchConfigAssociation(ILaunchConfiguration launchConfig, int port) { synchronized (sListLock) { sRunningAppMap.put(launchConfig, port); } } /** * Checks the build information, and returns whether the launch should continue. * <p/>The value tested are: * <ul> * <li>Minimum API version requested by the application. If the target device does not match, * the launch is canceled.</li> * <li>Debuggable attribute of the application and whether or not the device requires it. If * the device requires it and it is not set in the manifest, the launch will be forced to * "release" mode instead of "debug"</li> * <ul> */ private boolean checkBuildInfo(DelayedLaunchInfo launchInfo, IDevice device) { if (device != null) { // check the app required API level versus the target device API level String deviceVersion = device.getProperty(IDevice.PROP_BUILD_VERSION); String deviceApiLevelString = device.getProperty(IDevice.PROP_BUILD_API_LEVEL); String deviceCodeName = device.getProperty(IDevice.PROP_BUILD_CODENAME); int deviceApiLevel = -1; try { deviceApiLevel = Integer.parseInt(deviceApiLevelString); } catch (NumberFormatException e) { // pass, we'll keep the apiLevel value at -1. } String requiredApiString = launchInfo.getRequiredApiVersionNumber(); if (requiredApiString != null) { int requiredApi = -1; try { requiredApi = Integer.parseInt(requiredApiString); } catch (NumberFormatException e) { // pass, we'll keep requiredApi value at -1. } if (requiredApi == -1) { // this means the manifest uses a codename for minSdkVersion // check that the device is using the same codename if (requiredApiString.equals(deviceCodeName) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format( "ERROR: Application requires a device running '%1$s'!", requiredApiString)); return false; } } else { // app requires a specific API level if (deviceApiLevel == -1) { AdtPlugin.printToConsole(launchInfo.getProject(), "WARNING: Unknown device API version!"); } else if (deviceApiLevel < requiredApi) { String msg = String.format( "ERROR: Application requires API version %1$d. Device API version is %2$d (Android %3$s).", requiredApi, deviceApiLevel, deviceVersion); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg); // abort the launch return false; } } } else { // warn the application API level requirement is not set. AdtPlugin.printErrorToConsole(launchInfo.getProject(), "WARNING: Application does not specify an API level requirement!"); // and display the target device API level (if known) if (deviceApiLevel == -1) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "WARNING: Unknown device API version!"); } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format( "Device API version is %1$d (Android %2$s)", deviceApiLevel, deviceVersion)); } } // now checks that the device/app can be debugged (if needed) if (device.isEmulator() == false && launchInfo.isDebugMode()) { String debuggableDevice = device.getProperty(IDevice.PROP_DEBUGGABLE); if (debuggableDevice != null && debuggableDevice.equals("0")) { //$NON-NLS-1$ // the device is "secure" and requires apps to declare themselves as debuggable! if (launchInfo.getDebuggable() == null) { String message1 = String.format( "Device '%1$s' requires that applications explicitely declare themselves as debuggable in their manifest.", device.getSerialNumber()); String message2 = String.format("Application '%1$s' does not have the attribute 'debuggable' set to TRUE in its manifest and cannot be debugged.", launchInfo.getPackageName()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), message1, message2); // because am -D does not check for ro.debuggable and the // 'debuggable' attribute, it is important we do not use the -D option // in this case or the app will wait for a debugger forever and never // really launch. launchInfo.setDebugMode(false); } else if (launchInfo.getDebuggable() == Boolean.FALSE) { String message = String.format("Application '%1$s' has its 'debuggable' attribute set to FALSE and cannot be debugged.", launchInfo.getPackageName()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), message); // because am -D does not check for ro.debuggable and the // 'debuggable' attribute, it is important we do not use the -D option // in this case or the app will wait for a debugger forever and never // really launch. launchInfo.setDebugMode(false); } } } } return true; } /** * Do a simple launch on the specified device, attempting to sync the new * package, and then launching the application. Failed sync/launch will * stop the current AndroidLaunch and return false; * @param launchInfo * @param device * @return true if succeed */ private boolean simpleLaunch(DelayedLaunchInfo launchInfo, IDevice device) { // API level check if (checkBuildInfo(launchInfo, device) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return false; } // sync the app if (syncApp(launchInfo, device) == false) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return false; } // launch the app launchApp(launchInfo, device); return true; } /** * If needed, syncs the application and all its dependencies on the device/emulator. * * @param launchInfo The Launch information object. * @param device the device on which to sync the application * @return true if the install succeeded. */ private boolean syncApp(DelayedLaunchInfo launchInfo, IDevice device) { boolean alreadyInstalled = ApkInstallManager.getInstance().isApplicationInstalled( launchInfo.getProject(), launchInfo.getPackageName(), device); if (alreadyInstalled) { AdtPlugin.printToConsole(launchInfo.getProject(), "Application already deployed. No need to reinstall."); } else { if (doSyncApp(launchInfo, device) == false) { return false; } } // The app is now installed, now try the dependent projects for (DelayedLaunchInfo dependentLaunchInfo : getDependenciesLaunchInfo(launchInfo)) { String msg = String.format("Project dependency found, installing: %s", dependentLaunchInfo.getProject().getName()); AdtPlugin.printToConsole(launchInfo.getProject(), msg); if (syncApp(dependentLaunchInfo, device) == false) { return false; } } return true; } /** * Syncs the application on the device/emulator. * * @param launchInfo The Launch information object. * @param device the device on which to sync the application * @return true if the install succeeded. */ private boolean doSyncApp(DelayedLaunchInfo launchInfo, IDevice device) { IPath path = launchInfo.getPackageFile().getLocation(); String fileName = path.lastSegment(); try { String message = String.format("Uploading %1$s onto device '%2$s'", fileName, device.getSerialNumber()); AdtPlugin.printToConsole(launchInfo.getProject(), message); String remotePackagePath = device.syncPackageToDevice(path.toOSString()); boolean installResult = installPackage(launchInfo, remotePackagePath, device); device.removeRemotePackage(remotePackagePath); // if the installation succeeded, we register it. if (installResult) { ApkInstallManager.getInstance().registerInstallation( launchInfo.getProject(), launchInfo.getPackageName(), device); } return installResult; } catch (IOException e) { String msg = String.format("Failed to upload %1$s on device '%2$s'", fileName, device.getSerialNumber()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e); } return false; } /** * For the current launchInfo, create additional DelayedLaunchInfo that should be used to * sync APKs that we are dependent on to the device. * * @param launchInfo the original launch info that we want to find the * @return a list of DelayedLaunchInfo (may be empty if no dependencies were found or error) */ public List<DelayedLaunchInfo> getDependenciesLaunchInfo(DelayedLaunchInfo launchInfo) { List<DelayedLaunchInfo> dependencies = new ArrayList<DelayedLaunchInfo>(); // Convert to equivalent JavaProject IJavaProject javaProject; try { //assuming this is an Android (and Java) project since it is attached to the launchInfo. javaProject = BaseProjectHelper.getJavaProject(launchInfo.getProject()); } catch (CoreException e) { // return empty dependencies AdtPlugin.printErrorToConsole(launchInfo.getProject(), e); return dependencies; } // Get all projects that this depends on List<IJavaProject> androidProjectList; try { androidProjectList = ProjectHelper.getAndroidProjectDependencies(javaProject); } catch (JavaModelException e) { // return empty dependencies AdtPlugin.printErrorToConsole(launchInfo.getProject(), e); return dependencies; } // for each project, parse manifest and create launch information for (IJavaProject androidProject : androidProjectList) { // Parse the Manifest to get various required information // copied from LaunchConfigDelegate AndroidManifestParser manifestParser; try { manifestParser = AndroidManifestParser.parse( androidProject, null /* errorListener */, true /* gatherData */, false /* markErrors */); } catch (CoreException e) { AdtPlugin.printErrorToConsole( launchInfo.getProject(), String.format("Error parsing manifest of %s", androidProject.getElementName())); continue; } // Get the APK location (can return null) IFile apk = ProjectHelper.getApplicationPackage(androidProject.getProject()); if (apk == null) { // getApplicationPackage will have logged an error message continue; } // Create new launchInfo as an hybrid between parent and dependency information DelayedLaunchInfo delayedLaunchInfo = new DelayedLaunchInfo( androidProject.getProject(), manifestParser.getPackage(), manifestParser.getPackage(), launchInfo.getLaunchAction(), apk, manifestParser.getDebuggable(), manifestParser.getApiLevelRequirement(), launchInfo.getLaunch(), launchInfo.getMonitor()); // Add to the list dependencies.add(delayedLaunchInfo); } return dependencies; } /** * Installs the application package on the device, and handles return result * @param launchInfo The launch information * @param remotePath The remote path of the package. * @param device The device on which the launch is done. */ private boolean installPackage(DelayedLaunchInfo launchInfo, final String remotePath, final IDevice device) { String message = String.format("Installing %1$s...", launchInfo.getPackageFile().getName()); AdtPlugin.printToConsole(launchInfo.getProject(), message); try { // try a reinstall first, because the most common case is the app is already installed String result = doInstall(launchInfo, remotePath, device, true /* reinstall */); /* For now we force to retry the install (after uninstalling) because there's no * other way around it: adb install does not want to update a package w/o uninstalling * the old one first! */ return checkInstallResult(result, device, launchInfo, remotePath, InstallRetryMode.ALWAYS); } catch (IOException e) { String msg = String.format( "Failed to install %1$s on device '%2$s!", launchInfo.getPackageFile().getName(), device.getSerialNumber()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e.getMessage()); } return false; } /** * Checks the result of an installation, and takes optional actions based on it. * @param result the result string from the installation * @param device the device on which the installation occured. * @param launchInfo the {@link DelayedLaunchInfo} * @param remotePath the temporary path of the package on the device * @param retryMode indicates what to do in case, a package already exists. * @return <code>true<code> if success, <code>false</code> otherwise. * @throws IOException */ private boolean checkInstallResult(String result, IDevice device, DelayedLaunchInfo launchInfo, String remotePath, InstallRetryMode retryMode) throws IOException { if (result == null) { AdtPlugin.printToConsole(launchInfo.getProject(), "Success!"); return true; } else if (result.equals("INSTALL_FAILED_ALREADY_EXISTS")) { //$NON-NLS-1$ // this should never happen, since reinstall mode is used on the first attempt if (retryMode == InstallRetryMode.PROMPT) { boolean prompt = AdtPlugin.displayPrompt("Application Install", "A previous installation needs to be uninstalled before the new package can be installed.\nDo you want to uninstall?"); if (prompt) { retryMode = InstallRetryMode.ALWAYS; } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation error! The package already exists."); return false; } } if (retryMode == InstallRetryMode.ALWAYS) { /* * TODO: create a UI that gives the dev the choice to: * - clean uninstall on launch * - full uninstall if application exists. * - soft uninstall if application exists (keeps the app data around). * - always ask (choice of soft-reinstall, full reinstall) AdtPlugin.printErrorToConsole(launchInfo.mProject, "Application already exists, uninstalling..."); String res = doUninstall(device, launchInfo); if (res == null) { AdtPlugin.printToConsole(launchInfo.mProject, "Success!"); } else { AdtPlugin.printErrorToConsole(launchInfo.mProject, String.format("Failed to uninstall: %1$s", res)); return false; } */ AdtPlugin.printToConsole(launchInfo.getProject(), "Application already exists. Attempting to re-install instead..."); String res = doInstall(launchInfo, remotePath, device, true /* reinstall */ ); return checkInstallResult(res, device, launchInfo, remotePath, InstallRetryMode.NEVER); } AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation error! The package already exists."); } else if (result.equals("INSTALL_FAILED_INVALID_APK")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation failed due to invalid APK file!", "Please check logcat output for more details."); } else if (result.equals("INSTALL_FAILED_INVALID_URI")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Installation failed due to invalid URI!", "Please check logcat output for more details."); } else if (result.equals("INSTALL_FAILED_COULDNT_COPY")) { //$NON-NLS-1$ AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Installation failed: Could not copy %1$s to its final location!", launchInfo.getPackageFile().getName()), "Please check logcat output for more details."); } else if (result.equals("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Re-installation failed due to different application signatures.", "You must perform a full uninstall of the application. WARNING: This will remove the application data!", String.format("Please execute 'adb uninstall %1$s' in a shell.", launchInfo.getPackageName())); } else { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Installation error: %1$s", result), "Please check logcat output for more details."); } return false; } /** * Performs the uninstallation of an application. * @param device the device on which to install the application. * @param launchInfo the {@link DelayedLaunchInfo}. * @return a {@link String} with an error code, or <code>null</code> if success. * @throws IOException */ @SuppressWarnings("unused") private String doUninstall(IDevice device, DelayedLaunchInfo launchInfo) throws IOException { try { return device.uninstallPackage(launchInfo.getPackageName()); } catch (IOException e) { String msg = String.format( "Failed to uninstall %1$s: %2$s", launchInfo.getPackageName(), e.getMessage()); AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg); throw e; } } /** * Performs the installation of an application whose package has been uploaded on the device. * * @param launchInfo the {@link DelayedLaunchInfo}. * @param remotePath the path of the application package in the device tmp folder. * @param device the device on which to install the application. * @param reinstall * @return a {@link String} with an error code, or <code>null</code> if success. * @throws IOException */ private String doInstall(DelayedLaunchInfo launchInfo, final String remotePath, final IDevice device, boolean reinstall) throws IOException { return device.installRemotePackage(remotePath, reinstall); } /** * launches an application on a device or emulator * * @param info the {@link DelayedLaunchInfo} that indicates the launch action * @param device the device or emulator to launch the application on */ public void launchApp(final DelayedLaunchInfo info, IDevice device) { if (info.isDebugMode()) { synchronized (sListLock) { if (mWaitingForDebuggerApplications.contains(info) == false) { mWaitingForDebuggerApplications.add(info); } } } if (info.getLaunchAction().doLaunchAction(info, device)) { // if the app is not a debug app, we need to do some clean up, as // the process is done! if (info.isDebugMode() == false) { // stop the launch object, since there's no debug, and it can't // provide any control over the app stopLaunch(info); } } else { // something went wrong or no further launch action needed // lets stop the Launch stopLaunch(info); } } private boolean launchEmulator(AndroidLaunchConfiguration config, AvdInfo avdToLaunch) { // split the custom command line in segments ArrayList<String> customArgs = new ArrayList<String>(); boolean hasWipeData = false; if (config.mEmulatorCommandLine != null && config.mEmulatorCommandLine.length() > 0) { String[] segments = config.mEmulatorCommandLine.split("\\s+"); //$NON-NLS-1$ // we need to remove the empty strings for (String s : segments) { if (s.length() > 0) { customArgs.add(s); if (!hasWipeData && s.equals(FLAG_WIPE_DATA)) { hasWipeData = true; } } } } boolean needsWipeData = config.mWipeData && !hasWipeData; if (needsWipeData) { if (!AdtPlugin.displayPrompt("Android Launch", "Are you sure you want to wipe all user data when starting this emulator?")) { needsWipeData = false; } } // build the command line based on the available parameters. ArrayList<String> list = new ArrayList<String>(); list.add(AdtPlugin.getOsAbsoluteEmulator()); list.add(FLAG_AVD); list.add(avdToLaunch.getName()); if (config.mNetworkSpeed != null) { list.add(FLAG_NETSPEED); list.add(config.mNetworkSpeed); } if (config.mNetworkDelay != null) { list.add(FLAG_NETDELAY); list.add(config.mNetworkDelay); } if (needsWipeData) { list.add(FLAG_WIPE_DATA); } if (config.mNoBootAnim) { list.add(FLAG_NO_BOOT_ANIM); } list.addAll(customArgs); // convert the list into an array for the call to exec. String[] command = list.toArray(new String[list.size()]); // launch the emulator try { Process process = Runtime.getRuntime().exec(command); grabEmulatorOutput(process); } catch (IOException e) { return false; } return true; } /** * Looks for and returns an existing {@link ILaunchConfiguration} object for a * specified project. * @param manager The {@link ILaunchManager}. * @param type The {@link ILaunchConfigurationType}. * @param projectName The name of the project * @return an existing <code>ILaunchConfiguration</code> object matching the project, or * <code>null</code>. */ private static ILaunchConfiguration findConfig(ILaunchManager manager, ILaunchConfigurationType type, String projectName) { try { ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type); for (ILaunchConfiguration config : configs) { if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "").equals(projectName)) { //$NON-NLS-1$ return config; } } } catch (CoreException e) { MessageDialog.openError(AdtPlugin.getDisplay().getActiveShell(), "Launch Error", e.getStatus().getMessage()); } // didn't find anything that matches. Return null return null; } /** * Connects a remote debugger on the specified port. * @param debugPort The port to connect the debugger to * @param launch The associated AndroidLaunch object. * @param monitor A Progress monitor * @return false if cancelled by the monitor * @throws CoreException */ public static boolean connectRemoteDebugger(int debugPort, AndroidLaunch launch, IProgressMonitor monitor) throws CoreException { // get some default parameters. int connectTimeout = JavaRuntime.getPreferences().getInt(JavaRuntime.PREF_CONNECT_TIMEOUT); HashMap<String, String> newMap = new HashMap<String, String>(); newMap.put("hostname", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$ newMap.put("port", Integer.toString(debugPort)); //$NON-NLS-1$ newMap.put("timeout", Integer.toString(connectTimeout)); // get the default VM connector IVMConnector connector = JavaRuntime.getDefaultVMConnector(); // connect to remote VM connector.connect(newMap, monitor, launch); // check for cancellation if (monitor.isCanceled()) { IDebugTarget[] debugTargets = launch.getDebugTargets(); for (IDebugTarget target : debugTargets) { if (target.canDisconnect()) { target.disconnect(); } } return false; } return true; } /** * Launch a new thread that connects a remote debugger on the specified port. * @param debugPort The port to connect the debugger to * @param androidLaunch The associated AndroidLaunch object. * @param monitor A Progress monitor * @see #connectRemoteDebugger(int, AndroidLaunch, IProgressMonitor) */ public static void launchRemoteDebugger(final int debugPort, final AndroidLaunch androidLaunch, final IProgressMonitor monitor) { new Thread("Debugger connection") { //$NON-NLS-1$ @Override public void run() { try { connectRemoteDebugger(debugPort, androidLaunch, monitor); } catch (CoreException e) { androidLaunch.stopLaunch(); } monitor.done(); } }.start(); } /** * Sent when a new {@link AndroidDebugBridge} is started. * <p/> * This is sent from a non UI thread. * @param bridge the new {@link AndroidDebugBridge} object. * * @see IDebugBridgeChangeListener#bridgeChanged(AndroidDebugBridge) */ public void bridgeChanged(AndroidDebugBridge bridge) { // The adb server has changed. We cancel any pending launches. String message = "adb server change: cancelling '%1$s'!"; synchronized (sListLock) { for (DelayedLaunchInfo launchInfo : mWaitingForReadyEmulatorList) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } for (DelayedLaunchInfo launchInfo : mWaitingForDebuggerApplications) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } mWaitingForReadyEmulatorList.clear(); mWaitingForDebuggerApplications.clear(); } } /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. * * @see IDeviceChangeListener#deviceConnected(IDevice) */ public void deviceConnected(IDevice device) { synchronized (sListLock) { // look if there's an app waiting for a device if (mWaitingForEmulatorLaunches.size() > 0) { // get/remove first launch item from the list // FIXME: what if we have multiple launches waiting? DelayedLaunchInfo launchInfo = mWaitingForEmulatorLaunches.get(0); mWaitingForEmulatorLaunches.remove(0); // give the launch item its device for later use. launchInfo.setDevice(device); // and move it to the other list mWaitingForReadyEmulatorList.add(launchInfo); // and tell the user about it AdtPlugin.printToConsole(launchInfo.getProject(), String.format("New emulator found: %1$s", device.getSerialNumber())); AdtPlugin.printToConsole(launchInfo.getProject(), String.format("Waiting for HOME ('%1$s') to be launched...", AdtPlugin.getDefault().getPreferenceStore().getString( AdtPrefs.PREFS_HOME_PACKAGE))); } } } /** * Sent when the a device is connected to the {@link AndroidDebugBridge}. * <p/> * This is sent from a non UI thread. * @param device the new device. * * @see IDeviceChangeListener#deviceDisconnected(IDevice) */ @SuppressWarnings("unchecked") public void deviceDisconnected(IDevice device) { // any pending launch on this device must be canceled. String message = "%1$s disconnected! Cancelling '%2$s'!"; synchronized (sListLock) { ArrayList<DelayedLaunchInfo> copyList = (ArrayList<DelayedLaunchInfo>) mWaitingForReadyEmulatorList.clone(); for (DelayedLaunchInfo launchInfo : copyList) { if (launchInfo.getDevice() == device) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, device.getSerialNumber(), launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } } copyList = (ArrayList<DelayedLaunchInfo>) mWaitingForDebuggerApplications.clone(); for (DelayedLaunchInfo launchInfo : copyList) { if (launchInfo.getDevice() == device) { AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(message, device.getSerialNumber(), launchInfo.getLaunchAction().getLaunchDescription())); stopLaunch(launchInfo); } } } } /** * Sent when a device data changed, or when clients are started/terminated on the device. * <p/> * This is sent from a non UI thread. * @param device the device that was updated. * @param changeMask the mask indicating what changed. * * @see IDeviceChangeListener#deviceChanged(IDevice, int) */ public void deviceChanged(IDevice device, int changeMask) { // We could check if any starting device we care about is now ready, but we can wait for // its home app to show up, so... } /** * Sent when an existing client information changed. * <p/> * This is sent from a non UI thread. * @param client the updated client. * @param changeMask the bit mask describing the changed properties. It can contain * any of the following values: {@link Client#CHANGE_INFO}, {@link Client#CHANGE_NAME} * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE}, * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE}, * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA} * * @see IClientChangeListener#clientChanged(Client, int) */ public void clientChanged(final Client client, int changeMask) { boolean connectDebugger = false; if ((changeMask & Client.CHANGE_NAME) == Client.CHANGE_NAME) { String applicationName = client.getClientData().getClientDescription(); if (applicationName != null) { IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore(); String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE); if (home.equals(applicationName)) { // looks like home is up, get its device IDevice device = client.getDevice(); // look for application waiting for home synchronized (sListLock) { for (int i = 0; i < mWaitingForReadyEmulatorList.size(); ) { DelayedLaunchInfo launchInfo = mWaitingForReadyEmulatorList.get(i); if (launchInfo.getDevice() == device) { // it's match, remove from the list mWaitingForReadyEmulatorList.remove(i); // We couldn't check earlier the API level of the device // (it's asynchronous when the device boot, and usually // deviceConnected is called before it's queried for its build info) // so we check now if (checkBuildInfo(launchInfo, device) == false) { // device is not the proper API! AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); return; } AdtPlugin.printToConsole(launchInfo.getProject(), String.format("HOME is up on device '%1$s'", device.getSerialNumber())); // attempt to sync the new package onto the device. if (syncApp(launchInfo, device)) { // application package is sync'ed, lets attempt to launch it. launchApp(launchInfo, device); } else { // failure! Cancel and return AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!"); stopLaunch(launchInfo); } break; } else { i++; } } } } // check if it's already waiting for a debugger, and if so we connect to it. if (client.getClientData().getDebuggerConnectionStatus() == DebuggerStatus.WAITING) { // search for this client in the list; synchronized (sListLock) { int index = mUnknownClientsWaitingForDebugger.indexOf(client); if (index != -1) { connectDebugger = true; mUnknownClientsWaitingForDebugger.remove(client); } } } } } // if it's not home, it could be an app that is now in debugger mode that we're waiting for // lets check it if ((changeMask & Client.CHANGE_DEBUGGER_STATUS) == Client.CHANGE_DEBUGGER_STATUS) { ClientData clientData = client.getClientData(); String applicationName = client.getClientData().getClientDescription(); if (clientData.getDebuggerConnectionStatus() == DebuggerStatus.WAITING) { // Get the application name, and make sure its valid. if (applicationName == null) { // looks like we don't have the client yet, so we keep it around for when its // name becomes available. synchronized (sListLock) { mUnknownClientsWaitingForDebugger.add(client); } return; } else { connectDebugger = true; } } } if (connectDebugger) { Log.d("adt", "Debugging " + client); // now check it against the apps waiting for a debugger String applicationName = client.getClientData().getClientDescription(); Log.d("adt", "App Name: " + applicationName); synchronized (sListLock) { for (int i = 0; i < mWaitingForDebuggerApplications.size(); ) { final DelayedLaunchInfo launchInfo = mWaitingForDebuggerApplications.get(i); if (client.getDevice() == launchInfo.getDevice() && applicationName.equals(launchInfo.getDebugPackageName())) { // this is a match. We remove the launch info from the list mWaitingForDebuggerApplications.remove(i); // and connect the debugger. String msg = String.format( "Attempting to connect debugger to '%1$s' on port %2$d", launchInfo.getDebugPackageName(), client.getDebuggerListenPort()); AdtPlugin.printToConsole(launchInfo.getProject(), msg); new Thread("Debugger Connection") { //$NON-NLS-1$ @Override public void run() { try { if (connectRemoteDebugger( client.getDebuggerListenPort(), launchInfo.getLaunch(), launchInfo.getMonitor()) == false) { return; } } catch (CoreException e) { // well something went wrong. AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format("Launch error: %s", e.getMessage())); // stop the launch stopLaunch(launchInfo); } launchInfo.getMonitor().done(); } }.start(); // we're done processing this client. return; } else { i++; } } } // if we get here, we haven't found an app that we were launching, so we look // for opened android projects that contains the app asking for a debugger. // If we find one, we automatically connect to it. IProject project = ProjectHelper.findAndroidProjectByAppName(applicationName); if (project != null) { debugRunningApp(project, client.getDebuggerListenPort()); } } } /** * Get the stderr/stdout outputs of a process and return when the process is done. * Both <b>must</b> be read or the process will block on windows. * @param process The process to get the output from */ private void grabEmulatorOutput(final Process process) { // read the lines as they come. if null is returned, it's // because the process finished new Thread("") { //$NON-NLS-1$ @Override public void run() { // create a buffer to read the stderr output InputStreamReader is = new InputStreamReader(process.getErrorStream()); BufferedReader errReader = new BufferedReader(is); try { while (true) { String line = errReader.readLine(); if (line != null) { AdtPlugin.printErrorToConsole("Emulator", line); } else { break; } } } catch (IOException e) { // do nothing. } } }.start(); new Thread("") { //$NON-NLS-1$ @Override public void run() { InputStreamReader is = new InputStreamReader(process.getInputStream()); BufferedReader outReader = new BufferedReader(is); try { while (true) { String line = outReader.readLine(); if (line != null) { AdtPlugin.printToConsole("Emulator", line); } else { break; } } } catch (IOException e) { // do nothing. } } }.start(); } /* (non-Javadoc) * @see com.android.ide.eclipse.adt.launch.ILaunchController#stopLaunch(com.android.ide.eclipse.adt.launch.AndroidLaunchController.DelayedLaunchInfo) */ public void stopLaunch(DelayedLaunchInfo launchInfo) { launchInfo.getLaunch().stopLaunch(); synchronized (sListLock) { mWaitingForReadyEmulatorList.remove(launchInfo); mWaitingForDebuggerApplications.remove(launchInfo); } } }
true
true
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); if (deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); }
public void launch(final IProject project, String mode, IFile apk, String packageName, String debugPackageName, Boolean debuggable, String requiredApiVersionNumber, final IAndroidLaunchAction launchAction, final AndroidLaunchConfiguration config, final AndroidLaunch launch, IProgressMonitor monitor) { String message = String.format("Performing %1$s", launchAction.getLaunchDescription()); AdtPlugin.printToConsole(project, message); // create the launch info final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName, debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch, monitor); // set the debug mode launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE)); // get the SDK Sdk currentSdk = Sdk.getCurrent(); AvdManager avdManager = currentSdk.getAvdManager(); // reload the AVDs to make sure we are up to date try { avdManager.reloadAvds(NullSdkLog.getLogger()); } catch (AndroidLocationException e1) { // this happens if the AVD Manager failed to find the folder in which the AVDs are // stored. This is unlikely to happen, but if it does, we should force to go manual // to allow using physical devices. config.mTargetMode = TargetMode.MANUAL; } // get the project target final IAndroidTarget projectTarget = currentSdk.getTarget(project); // FIXME: check errors on missing sdk, AVD manager, or project target. // device chooser response object. final DeviceChooserResponse response = new DeviceChooserResponse(); /* * Launch logic: * - Manually Mode * Always display a UI that lets a user see the current running emulators/devices. * The UI must show which devices are compatibles, and allow launching new emulators * with compatible (and not yet running) AVD. * - Automatic Way * * Preferred AVD set. * If Preferred AVD is not running: launch it. * Launch the application on the preferred AVD. * * No preferred AVD. * Count the number of compatible emulators/devices. * If != 1, display a UI similar to manual mode. * If == 1, launch the application on this AVD/device. */ if (config.mTargetMode == TargetMode.AUTO) { // if we are in automatic target mode, we need to find the current devices IDevice[] devices = AndroidDebugBridge.getBridge().getDevices(); // first check if we have a preferred AVD name, and if it actually exists, and is valid // (ie able to run the project). // We need to check this in case the AVD was recreated with a different target that is // not compatible. AvdInfo preferredAvd = null; if (config.mAvdName != null) { preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/); if (projectTarget.isCompatibleBaseFor(preferredAvd.getTarget()) == false) { preferredAvd = null; AdtPlugin.printErrorToConsole(project, String.format( "Preferred AVD '%1$s' is not compatible with the project target '%2$s'. Looking for a compatible AVD...", config.mAvdName, projectTarget.getName())); } } if (preferredAvd != null) { // look for a matching device for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) { response.setDeviceToUse(d); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'", config.mAvdName, d)); continueLaunch(response, project, launch, launchInfo, config); return; } } // at this point we have a valid preferred AVD that is not running. // We need to start it. response.setAvdToLaunch(preferredAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.", config.mAvdName)); continueLaunch(response, project, launch, launchInfo, config); return; } // no (valid) preferred AVD? look for one. HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>(); boolean hasDevice = false; // if there's 1+ device running, we may force manual mode, // as we cannot always detect proper compatibility with // devices. This is the case if the project target is not // a standard platform for (IDevice d : devices) { String deviceAvd = d.getAvdName(); if (deviceAvd != null) { // physical devices return null. AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/); if (info != null && projectTarget.isCompatibleBaseFor(info.getTarget())) { compatibleRunningAvds.put(d, info); } } else { if (projectTarget.isPlatform()) { // means this can run on any device as long // as api level is high enough AndroidVersion deviceVersion = Sdk.getDeviceVersion(d); // the deviceVersion may be null if it wasn't yet queried (device just // plugged in or emulator just booting up. if (deviceVersion != null && deviceVersion.canRun(projectTarget.getVersion())) { // device is compatible with project compatibleRunningAvds.put(d, null); continue; } } else { // for non project platform, we can't be sure if a device can // run an application or not, since we don't query the device // for the list of optional libraries that it supports. } hasDevice = true; } } // depending on the number of devices, we'll simulate an automatic choice // from the device chooser or simply show up the device chooser. if (hasDevice == false && compatibleRunningAvds.size() == 0) { // if zero emulators/devices, we launch an emulator. // We need to figure out which AVD first. // we are going to take the closest AVD. ie a compatible AVD that has the API level // closest to the project target. AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd != null) { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } else { AdtPlugin.printToConsole(project, String.format( "Failed to find an AVD compatible with target '%1$s'.", projectTarget.getName())); final Display display = AdtPlugin.getDisplay(); final boolean[] searchAgain = new boolean[] { false }; // ask the user to create a new one. display.syncExec(new Runnable() { public void run() { Shell shell = display.getActiveShell(); if (MessageDialog.openQuestion(shell, "Android AVD Error", "No compatible targets were found. Do you wish to a add new Android Virtual Device?")) { AvdManagerAction action = new AvdManagerAction(); action.run(null /*action*/); searchAgain[0] = true; } } }); if (searchAgain[0]) { // attempt to reload the AVDs and find one compatible. defaultAvd = findMatchingAvd(avdManager, projectTarget); if (defaultAvd == null) { AdtPlugin.printErrorToConsole(project, String.format( "Still no compatible AVDs with target '%1$s': Aborting launch.", projectTarget.getName())); stopLaunch(launchInfo); } else { response.setAvdToLaunch(defaultAvd); AdtPlugin.printToConsole(project, String.format( "Launching new emulator with compatible AVD '%1$s'", defaultAvd.getName())); continueLaunch(response, project, launch, launchInfo, config); return; } } } } else if (hasDevice == false && compatibleRunningAvds.size() == 1) { Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next(); response.setDeviceToUse(e.getKey()); // get the AvdInfo, if null, the device is a physical device. AvdInfo avdInfo = e.getValue(); if (avdInfo != null) { message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'", response.getDeviceToUse(), e.getValue().getName()); } else { message = String.format("Automatic Target Mode: using device '%1$s'", response.getDeviceToUse()); } AdtPlugin.printToConsole(project, message); continueLaunch(response, project, launch, launchInfo, config); return; } // if more than one device, we'll bring up the DeviceChooser dialog below. if (compatibleRunningAvds.size() >= 2) { message = "Automatic Target Mode: Several compatible targets. Please select a target device."; } else if (hasDevice) { message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device."; } AdtPlugin.printToConsole(project, message); } // bring up the device chooser. AdtPlugin.getDisplay().asyncExec(new Runnable() { public void run() { try { // open the chooser dialog. It'll fill 'response' with the device to use // or the AVD to launch. DeviceChooserDialog dialog = new DeviceChooserDialog( AdtPlugin.getDisplay().getActiveShell(), response, launchInfo.getPackageName(), projectTarget); if (dialog.open() == Dialog.OK) { AndroidLaunchController.this.continueLaunch(response, project, launch, launchInfo, config); } else { AdtPlugin.printErrorToConsole(project, "Launch canceled!"); stopLaunch(launchInfo); return; } } catch (Exception e) { // there seems to be some case where the shell will be null. (might be // an OS X bug). Because of this the creation of the dialog will throw // and IllegalArg exception interrupting the launch with no user feedback. // So we trap all the exception and display something. String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getCanonicalName(); } AdtPlugin.printErrorToConsole(project, String.format("Error during launch: %s", msg)); stopLaunch(launchInfo); } } }); }
diff --git a/service/src/main/java/org/openengsb/labs/delegation/service/internal/Activator.java b/service/src/main/java/org/openengsb/labs/delegation/service/internal/Activator.java index 3ed55cb..8bbd39e 100644 --- a/service/src/main/java/org/openengsb/labs/delegation/service/internal/Activator.java +++ b/service/src/main/java/org/openengsb/labs/delegation/service/internal/Activator.java @@ -1,89 +1,90 @@ /** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.labs.delegation.service.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import org.openengsb.labs.delegation.service.Constants; import org.openengsb.labs.delegation.service.DelegationUtil; import org.osgi.framework.Bundle; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.BundleListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Activator implements BundleActivator { private static final Logger LOGGER = LoggerFactory.getLogger(Activator.class); @Override public void start(BundleContext context) { BundleListener bundleListener = new BundleListener() { @Override public void bundleChanged(BundleEvent event) { if (event.getType() == BundleEvent.STARTED) { handleBundleInstall(event.getBundle()); } } }; context.addBundleListener(bundleListener); for (Bundle b : context.getBundles()) { if (b.getState() == Bundle.ACTIVE) { handleBundleInstall(b); } } } private synchronized void handleBundleInstall(Bundle b) { LOGGER.info("injecting ClassProvider-Service into bundle {}.", b.getSymbolicName()); + @SuppressWarnings("unchecked") Enumeration<String> keys = b.getHeaders().keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (key.equals(Constants.PROVIDED_CLASSES)) { String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses); } else if (key.startsWith(Constants.PROVIDED_CLASSES)) { String context = key.replaceFirst(Constants.PROVIDED_CLASSES + "\\-", ""); String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses, context); } } } private Collection<String> parseProvidedClasses(String providedClassesString) { String[] providedClassesArray = providedClassesString.split(","); Collection<String> providedClassesList = new ArrayList<String>(); for (String p : providedClassesArray) { providedClassesList.add(p.trim()); } return providedClassesList; } @Override public void stop(BundleContext context) throws Exception { // TODO Auto-generated method stub } }
true
true
private synchronized void handleBundleInstall(Bundle b) { LOGGER.info("injecting ClassProvider-Service into bundle {}.", b.getSymbolicName()); Enumeration<String> keys = b.getHeaders().keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (key.equals(Constants.PROVIDED_CLASSES)) { String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses); } else if (key.startsWith(Constants.PROVIDED_CLASSES)) { String context = key.replaceFirst(Constants.PROVIDED_CLASSES + "\\-", ""); String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses, context); } } }
private synchronized void handleBundleInstall(Bundle b) { LOGGER.info("injecting ClassProvider-Service into bundle {}.", b.getSymbolicName()); @SuppressWarnings("unchecked") Enumeration<String> keys = b.getHeaders().keys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); if (key.equals(Constants.PROVIDED_CLASSES)) { String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses); } else if (key.startsWith(Constants.PROVIDED_CLASSES)) { String context = key.replaceFirst(Constants.PROVIDED_CLASSES + "\\-", ""); String providedClassesString = (String) b.getHeaders().get(key); Collection<String> providedClasses = parseProvidedClasses(providedClassesString); DelegationUtil.registerClassProviderForBundle(b, providedClasses, context); } } }
diff --git a/src/org/openstreetmap/josm/actions/search/SearchAction.java b/src/org/openstreetmap/josm/actions/search/SearchAction.java index 219a0c4b..7fe2ff36 100644 --- a/src/org/openstreetmap/josm/actions/search/SearchAction.java +++ b/src/org/openstreetmap/josm/actions/search/SearchAction.java @@ -1,340 +1,341 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.actions.search; import static org.openstreetmap.josm.gui.help.HelpUtil.ht; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.Font; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.actions.JosmAction; import org.openstreetmap.josm.data.osm.DataSet; import org.openstreetmap.josm.data.osm.Filter; import org.openstreetmap.josm.data.osm.OsmPrimitive; import org.openstreetmap.josm.gui.ExtendedDialog; import org.openstreetmap.josm.gui.widgets.HistoryComboBox; import org.openstreetmap.josm.tools.GBC; import org.openstreetmap.josm.tools.Shortcut; public class SearchAction extends JosmAction{ public static final int DEFAULT_SEARCH_HISTORY_SIZE = 10; public static enum SearchMode { replace, add, remove, in_selection } public static final LinkedList<SearchSetting> searchHistory = new LinkedList<SearchSetting>(); private static SearchSetting lastSearch = null; public SearchAction() { super(tr("Search..."), "dialogs/search", tr("Search for objects."), Shortcut.registerShortcut("system:find", tr("Search..."), KeyEvent.VK_F, Shortcut.GROUP_HOTKEY), true); putValue("help", ht("/Action/Search")); } public void actionPerformed(ActionEvent e) { if (!isEnabled()) return; SearchSetting s = lastSearch; if (s == null) { s = new SearchSetting("", SearchMode.replace, false /* case insensitive */, false /* no regexp */); } SearchSetting se = showSearchDialog(s); if(se != null) { searchWithHistory(se); } } public static List<String> getSearchExpressionHistory() { ArrayList<String> ret = new ArrayList<String>(searchHistory.size()); for (SearchSetting ss: searchHistory) { ret.add(ss.text); } return ret; } public static SearchSetting showSearchDialog(SearchSetting initialValues) { // -- prepare the combo box with the search expressions // JLabel label = new JLabel( initialValues instanceof Filter ? tr("Please enter a filter string.") : tr("Please enter a search string.")); final HistoryComboBox hcbSearchString = new HistoryComboBox(); hcbSearchString.setText(initialValues.text); hcbSearchString.getEditor().selectAll(); hcbSearchString.getEditor().getEditorComponent().requestFocusInWindow(); hcbSearchString.setToolTipText(tr("Enter the search expression")); // we have to reverse the history, because ComboBoxHistory will reverse it again // in addElement() // List<String> searchExpressionHistory = getSearchExpressionHistory(); Collections.reverse(searchExpressionHistory); hcbSearchString.setPossibleItems(searchExpressionHistory); JRadioButton replace = new JRadioButton(tr("replace selection"), initialValues.mode == SearchMode.replace); JRadioButton add = new JRadioButton(tr("add to selection"), initialValues.mode == SearchMode.add); JRadioButton remove = new JRadioButton(tr("remove from selection"), initialValues.mode == SearchMode.remove); JRadioButton in_selection = new JRadioButton(tr("find in selection"), initialValues.mode == SearchMode.in_selection); ButtonGroup bg = new ButtonGroup(); bg.add(replace); bg.add(add); bg.add(remove); bg.add(in_selection); JCheckBox caseSensitive = new JCheckBox(tr("case sensitive"), initialValues.caseSensitive); JCheckBox regexSearch = new JCheckBox(tr("regular expression"), initialValues.regexSearch); JPanel left = new JPanel(new GridBagLayout()); left.add(label, GBC.eop()); left.add(hcbSearchString, GBC.eop().fill(GBC.HORIZONTAL)); left.add(replace, GBC.eol()); left.add(add, GBC.eol()); left.add(remove, GBC.eol()); left.add(in_selection, GBC.eop()); left.add(caseSensitive, GBC.eol()); left.add(regexSearch, GBC.eol()); JPanel right = new JPanel(); JLabel description = new JLabel("<html><ul>" + "<li>"+tr("<b>Baker Street</b> - 'Baker' and 'Street' in any key or name.")+"</li>" + "<li>"+tr("<b>\"Baker Street\"</b> - 'Baker Street' in any key or name.")+"</li>" + "<li>"+tr("<b>name:Bak</b> - 'Bak' anywhere in the name.")+"</li>" + "<li>"+tr("<b>type=route</b> - key 'type' with value exactly 'route'.") + "</li>" + "<li>"+tr("<b>type=*</b> - key 'type' with any value. Try also <b>*=value</b>, <b>type=</b>, <b>*=*</b>, <b>*=</b>") + "</li>" + "<li>"+tr("<b>-name:Bak</b> - not 'Bak' in the name.")+"</li>" + "<li>"+tr("<b>foot:</b> - key=foot set to any value.")+"</li>" + "<li>"+tr("<u>Special targets:</u>")+"</li>" + "<li>"+tr("<b>type:</b> - type of the object (<b>node</b>, <b>way</b>, <b>relation</b>)")+"</li>" + "<li>"+tr("<b>user:</b>... - all objects changed by user")+"</li>" + "<li>"+tr("<b>user:anonymous</b> - all objects changed by anonymous users")+"</li>" + "<li>"+tr("<b>id:</b>... - object with given ID (0 for new objects)")+"</li>" + "<li>"+tr("<b>changeset:</b>... - object with given changeset id (0 objects without assigned changeset)")+"</li>" - + "<li>"+tr("<b>nodes:</b>... - object with given number of nodes")+"</li>" + + "<li>"+tr("<b>nodes:</b>... - object with given number of nodes (nodes:count or nodes:min-max)")+"</li>" + "<li>"+tr("<b>tags:</b>... - object with given number of tags (tags:count or tags:min-max)")+"</li>" + + "<li>"+tr("<b>timestamp:</b>... - objects with this timestamp (<b>2009-11-12T14:51:09Z</b>, <b>2009-11-12</b> or <b>T14:51</b> ...)")+"</li>" + "<li>"+tr("<b>modified</b> - all changed objects")+"</li>" + "<li>"+tr("<b>selected</b> - all selected objects")+"</li>" + "<li>"+tr("<b>incomplete</b> - all incomplete objects")+"</li>" + "<li>"+tr("<b>untagged</b> - all untagged objects")+"</li>" + "<li>"+tr("<b>child <i>expr</i></b> - all children of objects matching the expression")+"</li>" + "<li>"+tr("<b>parent <i>expr</i></b> - all parents of objects matching the expression")+"</li>" + "<li>"+tr("Use <b>|</b> or <b>OR</b> to combine with logical or")+"</li>" + "<li>"+tr("Use <b>\"</b> to quote operators (e.g. if key contains :)")+"</li>" + "<li>"+tr("Use <b>(</b> and <b>)</b> to group expressions")+"</li>" + "</ul></html>"); description.setFont(description.getFont().deriveFont(Font.PLAIN)); right.add(description); final JPanel p = new JPanel(); p.add(left); p.add(right); ExtendedDialog dialog = new ExtendedDialog( Main.parent, initialValues instanceof Filter ? tr("Filter") : tr("Search"), new String[] { initialValues instanceof Filter ? tr("Submit filter") : tr("Start Search"), tr("Cancel")} ); dialog.setButtonIcons(new String[] {"dialogs/search.png", "cancel.png"}); dialog.configureContextsensitiveHelp("/Action/Search", true /* show help button */); dialog.setContent(p); dialog.showDialog(); int result = dialog.getValue(); if(result != 1) return null; // User pressed OK - let's perform the search SearchMode mode = replace.isSelected() ? SearchAction.SearchMode.replace : (add.isSelected() ? SearchAction.SearchMode.add : (remove.isSelected() ? SearchAction.SearchMode.remove : SearchAction.SearchMode.in_selection)); initialValues.text = hcbSearchString.getText(); initialValues.mode = mode; initialValues.caseSensitive = caseSensitive.isSelected(); initialValues.regexSearch = regexSearch.isSelected(); return initialValues; } /** * Adds the search specified by the settings in <code>s</code> to the * search history and performs the search. * * @param s */ public static void searchWithHistory(SearchSetting s) { if(searchHistory.isEmpty() || !s.equals(searchHistory.getFirst())) { searchHistory.addFirst(new SearchSetting(s)); } int maxsize = Main.pref.getInteger("search.history-size", DEFAULT_SEARCH_HISTORY_SIZE); while (searchHistory.size() > maxsize) { searchHistory.removeLast(); } lastSearch = new SearchSetting(s); search(s); } public static void searchWithoutHistory(SearchSetting s) { lastSearch = new SearchSetting(s); search(s); } public interface Function{ public Boolean isSomething(OsmPrimitive o); } public static Integer getSelection(SearchSetting s, Collection<OsmPrimitive> sel, Function f) { Integer foundMatches = 0; try { String searchText = s.text; if(s instanceof Filter){ searchText = "(" + s.text + ")" + (((Filter)s).applyForChildren ? ("| child (" + s.text + ")"): ""); searchText = (((Filter)s).inverted ? "-" : "") + "(" + searchText + ")"; } /*System.out.println(searchText);*/ SearchCompiler.Match matcher = SearchCompiler.compile(searchText, s.caseSensitive, s.regexSearch); foundMatches = 0; for (OsmPrimitive osm : Main.main.getCurrentDataSet().allNonDeletedCompletePrimitives()) { if (s.mode == SearchMode.replace) { if (matcher.match(osm)) { sel.add(osm); ++foundMatches; } else { sel.remove(osm); } } else if (s.mode == SearchMode.add && !f.isSomething(osm) && matcher.match(osm)) { sel.add(osm); ++foundMatches; } else if (s.mode == SearchMode.remove && f.isSomething(osm) && matcher.match(osm)) { sel.remove(osm); ++foundMatches; } else if (s.mode == SearchMode.in_selection && f.isSomething(osm)&& !matcher.match(osm)) { sel.remove(osm); ++foundMatches; } } } catch (SearchCompiler.ParseError e) { JOptionPane.showMessageDialog( Main.parent, e.getMessage(), tr("Error"), JOptionPane.ERROR_MESSAGE ); } return foundMatches; } public static void search(String search, SearchMode mode, boolean caseSensitive, boolean regexSearch) { search(new SearchSetting(search, mode, caseSensitive, regexSearch)); } public static void search(SearchSetting s) { // FIXME: This is confusing. The GUI says nothing about loading primitives from an URL. We'd like to *search* // for URLs in the current data set. // Disabling until a better solution is in place // // if (search.startsWith("http://") || search.startsWith("ftp://") || search.startsWith("https://") // || search.startsWith("file:/")) { // SelectionWebsiteLoader loader = new SelectionWebsiteLoader(search, mode); // if (loader.url != null && loader.url.getHost() != null) { // Main.worker.execute(loader); // return; // } // } final DataSet ds = Main.main.getCurrentDataSet(); Collection<OsmPrimitive> sel = ds.getSelected(); int foundMatches = getSelection(s, sel, new Function(){ public Boolean isSomething(OsmPrimitive o){ return ds.isSelected(o); } }); ds.setSelected(sel); if (foundMatches == 0) { String msg = null; if (s.mode == SearchMode.replace) { msg = tr("No match found for ''{0}''", s.text); } else if (s.mode == SearchMode.add) { msg = tr("Nothing added to selection by searching for ''{0}''", s.text); } else if (s.mode == SearchMode.remove) { msg = tr("Nothing removed from selection by searching for ''{0}''", s.text); } else if (s.mode == SearchMode.in_selection) { msg = tr("Nothing found in selection by searching for ''{0}''", s.text); } Main.map.statusLine.setHelpText(msg); JOptionPane.showMessageDialog( Main.parent, msg, tr("Warning"), JOptionPane.WARNING_MESSAGE ); } else { Main.map.statusLine.setHelpText(tr("Found {0} matches", foundMatches)); } } public static class SearchSetting { public String text; public SearchMode mode; public boolean caseSensitive; public boolean regexSearch; public SearchSetting(String text, SearchMode mode, boolean caseSensitive, boolean regexSearch) { super(); this.caseSensitive = caseSensitive; this.regexSearch = regexSearch; this.mode = mode; this.text = text; } public SearchSetting(SearchSetting original) { super(); this.caseSensitive = original.caseSensitive; this.regexSearch = original.regexSearch; this.mode = original.mode; this.text = original.text; } @Override public String toString() { String cs = caseSensitive ? tr("CS") : tr("CI"); String rx = regexSearch ? (", " + tr("RX")) : ""; return "\"" + text + "\" (" + cs + rx + ", " + mode + ")"; } @Override public boolean equals(Object other) { if(!(other instanceof SearchSetting)) return false; SearchSetting o = (SearchSetting) other; return (o.caseSensitive == this.caseSensitive && o.regexSearch == this.regexSearch && o.mode.equals(this.mode) && o.text.equals(this.text)); } } /** * Refreshes the enabled state * */ @Override protected void updateEnabledState() { setEnabled(getEditLayer() != null); } }
false
true
public static SearchSetting showSearchDialog(SearchSetting initialValues) { // -- prepare the combo box with the search expressions // JLabel label = new JLabel( initialValues instanceof Filter ? tr("Please enter a filter string.") : tr("Please enter a search string.")); final HistoryComboBox hcbSearchString = new HistoryComboBox(); hcbSearchString.setText(initialValues.text); hcbSearchString.getEditor().selectAll(); hcbSearchString.getEditor().getEditorComponent().requestFocusInWindow(); hcbSearchString.setToolTipText(tr("Enter the search expression")); // we have to reverse the history, because ComboBoxHistory will reverse it again // in addElement() // List<String> searchExpressionHistory = getSearchExpressionHistory(); Collections.reverse(searchExpressionHistory); hcbSearchString.setPossibleItems(searchExpressionHistory); JRadioButton replace = new JRadioButton(tr("replace selection"), initialValues.mode == SearchMode.replace); JRadioButton add = new JRadioButton(tr("add to selection"), initialValues.mode == SearchMode.add); JRadioButton remove = new JRadioButton(tr("remove from selection"), initialValues.mode == SearchMode.remove); JRadioButton in_selection = new JRadioButton(tr("find in selection"), initialValues.mode == SearchMode.in_selection); ButtonGroup bg = new ButtonGroup(); bg.add(replace); bg.add(add); bg.add(remove); bg.add(in_selection); JCheckBox caseSensitive = new JCheckBox(tr("case sensitive"), initialValues.caseSensitive); JCheckBox regexSearch = new JCheckBox(tr("regular expression"), initialValues.regexSearch); JPanel left = new JPanel(new GridBagLayout()); left.add(label, GBC.eop()); left.add(hcbSearchString, GBC.eop().fill(GBC.HORIZONTAL)); left.add(replace, GBC.eol()); left.add(add, GBC.eol()); left.add(remove, GBC.eol()); left.add(in_selection, GBC.eop()); left.add(caseSensitive, GBC.eol()); left.add(regexSearch, GBC.eol()); JPanel right = new JPanel(); JLabel description = new JLabel("<html><ul>" + "<li>"+tr("<b>Baker Street</b> - 'Baker' and 'Street' in any key or name.")+"</li>" + "<li>"+tr("<b>\"Baker Street\"</b> - 'Baker Street' in any key or name.")+"</li>" + "<li>"+tr("<b>name:Bak</b> - 'Bak' anywhere in the name.")+"</li>" + "<li>"+tr("<b>type=route</b> - key 'type' with value exactly 'route'.") + "</li>" + "<li>"+tr("<b>type=*</b> - key 'type' with any value. Try also <b>*=value</b>, <b>type=</b>, <b>*=*</b>, <b>*=</b>") + "</li>" + "<li>"+tr("<b>-name:Bak</b> - not 'Bak' in the name.")+"</li>" + "<li>"+tr("<b>foot:</b> - key=foot set to any value.")+"</li>" + "<li>"+tr("<u>Special targets:</u>")+"</li>" + "<li>"+tr("<b>type:</b> - type of the object (<b>node</b>, <b>way</b>, <b>relation</b>)")+"</li>" + "<li>"+tr("<b>user:</b>... - all objects changed by user")+"</li>" + "<li>"+tr("<b>user:anonymous</b> - all objects changed by anonymous users")+"</li>" + "<li>"+tr("<b>id:</b>... - object with given ID (0 for new objects)")+"</li>" + "<li>"+tr("<b>changeset:</b>... - object with given changeset id (0 objects without assigned changeset)")+"</li>" + "<li>"+tr("<b>nodes:</b>... - object with given number of nodes")+"</li>" + "<li>"+tr("<b>tags:</b>... - object with given number of tags (tags:count or tags:min-max)")+"</li>" + "<li>"+tr("<b>modified</b> - all changed objects")+"</li>" + "<li>"+tr("<b>selected</b> - all selected objects")+"</li>" + "<li>"+tr("<b>incomplete</b> - all incomplete objects")+"</li>" + "<li>"+tr("<b>untagged</b> - all untagged objects")+"</li>" + "<li>"+tr("<b>child <i>expr</i></b> - all children of objects matching the expression")+"</li>" + "<li>"+tr("<b>parent <i>expr</i></b> - all parents of objects matching the expression")+"</li>" + "<li>"+tr("Use <b>|</b> or <b>OR</b> to combine with logical or")+"</li>" + "<li>"+tr("Use <b>\"</b> to quote operators (e.g. if key contains :)")+"</li>" + "<li>"+tr("Use <b>(</b> and <b>)</b> to group expressions")+"</li>" + "</ul></html>"); description.setFont(description.getFont().deriveFont(Font.PLAIN)); right.add(description); final JPanel p = new JPanel(); p.add(left); p.add(right); ExtendedDialog dialog = new ExtendedDialog( Main.parent, initialValues instanceof Filter ? tr("Filter") : tr("Search"), new String[] { initialValues instanceof Filter ? tr("Submit filter") : tr("Start Search"), tr("Cancel")} ); dialog.setButtonIcons(new String[] {"dialogs/search.png", "cancel.png"}); dialog.configureContextsensitiveHelp("/Action/Search", true /* show help button */); dialog.setContent(p); dialog.showDialog(); int result = dialog.getValue(); if(result != 1) return null; // User pressed OK - let's perform the search SearchMode mode = replace.isSelected() ? SearchAction.SearchMode.replace : (add.isSelected() ? SearchAction.SearchMode.add : (remove.isSelected() ? SearchAction.SearchMode.remove : SearchAction.SearchMode.in_selection)); initialValues.text = hcbSearchString.getText(); initialValues.mode = mode; initialValues.caseSensitive = caseSensitive.isSelected(); initialValues.regexSearch = regexSearch.isSelected(); return initialValues; }
public static SearchSetting showSearchDialog(SearchSetting initialValues) { // -- prepare the combo box with the search expressions // JLabel label = new JLabel( initialValues instanceof Filter ? tr("Please enter a filter string.") : tr("Please enter a search string.")); final HistoryComboBox hcbSearchString = new HistoryComboBox(); hcbSearchString.setText(initialValues.text); hcbSearchString.getEditor().selectAll(); hcbSearchString.getEditor().getEditorComponent().requestFocusInWindow(); hcbSearchString.setToolTipText(tr("Enter the search expression")); // we have to reverse the history, because ComboBoxHistory will reverse it again // in addElement() // List<String> searchExpressionHistory = getSearchExpressionHistory(); Collections.reverse(searchExpressionHistory); hcbSearchString.setPossibleItems(searchExpressionHistory); JRadioButton replace = new JRadioButton(tr("replace selection"), initialValues.mode == SearchMode.replace); JRadioButton add = new JRadioButton(tr("add to selection"), initialValues.mode == SearchMode.add); JRadioButton remove = new JRadioButton(tr("remove from selection"), initialValues.mode == SearchMode.remove); JRadioButton in_selection = new JRadioButton(tr("find in selection"), initialValues.mode == SearchMode.in_selection); ButtonGroup bg = new ButtonGroup(); bg.add(replace); bg.add(add); bg.add(remove); bg.add(in_selection); JCheckBox caseSensitive = new JCheckBox(tr("case sensitive"), initialValues.caseSensitive); JCheckBox regexSearch = new JCheckBox(tr("regular expression"), initialValues.regexSearch); JPanel left = new JPanel(new GridBagLayout()); left.add(label, GBC.eop()); left.add(hcbSearchString, GBC.eop().fill(GBC.HORIZONTAL)); left.add(replace, GBC.eol()); left.add(add, GBC.eol()); left.add(remove, GBC.eol()); left.add(in_selection, GBC.eop()); left.add(caseSensitive, GBC.eol()); left.add(regexSearch, GBC.eol()); JPanel right = new JPanel(); JLabel description = new JLabel("<html><ul>" + "<li>"+tr("<b>Baker Street</b> - 'Baker' and 'Street' in any key or name.")+"</li>" + "<li>"+tr("<b>\"Baker Street\"</b> - 'Baker Street' in any key or name.")+"</li>" + "<li>"+tr("<b>name:Bak</b> - 'Bak' anywhere in the name.")+"</li>" + "<li>"+tr("<b>type=route</b> - key 'type' with value exactly 'route'.") + "</li>" + "<li>"+tr("<b>type=*</b> - key 'type' with any value. Try also <b>*=value</b>, <b>type=</b>, <b>*=*</b>, <b>*=</b>") + "</li>" + "<li>"+tr("<b>-name:Bak</b> - not 'Bak' in the name.")+"</li>" + "<li>"+tr("<b>foot:</b> - key=foot set to any value.")+"</li>" + "<li>"+tr("<u>Special targets:</u>")+"</li>" + "<li>"+tr("<b>type:</b> - type of the object (<b>node</b>, <b>way</b>, <b>relation</b>)")+"</li>" + "<li>"+tr("<b>user:</b>... - all objects changed by user")+"</li>" + "<li>"+tr("<b>user:anonymous</b> - all objects changed by anonymous users")+"</li>" + "<li>"+tr("<b>id:</b>... - object with given ID (0 for new objects)")+"</li>" + "<li>"+tr("<b>changeset:</b>... - object with given changeset id (0 objects without assigned changeset)")+"</li>" + "<li>"+tr("<b>nodes:</b>... - object with given number of nodes (nodes:count or nodes:min-max)")+"</li>" + "<li>"+tr("<b>tags:</b>... - object with given number of tags (tags:count or tags:min-max)")+"</li>" + "<li>"+tr("<b>timestamp:</b>... - objects with this timestamp (<b>2009-11-12T14:51:09Z</b>, <b>2009-11-12</b> or <b>T14:51</b> ...)")+"</li>" + "<li>"+tr("<b>modified</b> - all changed objects")+"</li>" + "<li>"+tr("<b>selected</b> - all selected objects")+"</li>" + "<li>"+tr("<b>incomplete</b> - all incomplete objects")+"</li>" + "<li>"+tr("<b>untagged</b> - all untagged objects")+"</li>" + "<li>"+tr("<b>child <i>expr</i></b> - all children of objects matching the expression")+"</li>" + "<li>"+tr("<b>parent <i>expr</i></b> - all parents of objects matching the expression")+"</li>" + "<li>"+tr("Use <b>|</b> or <b>OR</b> to combine with logical or")+"</li>" + "<li>"+tr("Use <b>\"</b> to quote operators (e.g. if key contains :)")+"</li>" + "<li>"+tr("Use <b>(</b> and <b>)</b> to group expressions")+"</li>" + "</ul></html>"); description.setFont(description.getFont().deriveFont(Font.PLAIN)); right.add(description); final JPanel p = new JPanel(); p.add(left); p.add(right); ExtendedDialog dialog = new ExtendedDialog( Main.parent, initialValues instanceof Filter ? tr("Filter") : tr("Search"), new String[] { initialValues instanceof Filter ? tr("Submit filter") : tr("Start Search"), tr("Cancel")} ); dialog.setButtonIcons(new String[] {"dialogs/search.png", "cancel.png"}); dialog.configureContextsensitiveHelp("/Action/Search", true /* show help button */); dialog.setContent(p); dialog.showDialog(); int result = dialog.getValue(); if(result != 1) return null; // User pressed OK - let's perform the search SearchMode mode = replace.isSelected() ? SearchAction.SearchMode.replace : (add.isSelected() ? SearchAction.SearchMode.add : (remove.isSelected() ? SearchAction.SearchMode.remove : SearchAction.SearchMode.in_selection)); initialValues.text = hcbSearchString.getText(); initialValues.mode = mode; initialValues.caseSensitive = caseSensitive.isSelected(); initialValues.regexSearch = regexSearch.isSelected(); return initialValues; }
diff --git a/src/com/android/calendar/event/CreateEventDialogFragment.java b/src/com/android/calendar/event/CreateEventDialogFragment.java index 868cb3a5..5eb69a10 100644 --- a/src/com/android/calendar/event/CreateEventDialogFragment.java +++ b/src/com/android/calendar/event/CreateEventDialogFragment.java @@ -1,315 +1,315 @@ /* Copyright (C) 2012 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.android.calendar.event; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.provider.CalendarContract; import android.provider.CalendarContract.Calendars; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.text.format.DateUtils; import android.text.format.Time; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.calendar.AsyncQueryService; import com.android.calendar.CalendarController; import com.android.calendar.CalendarController.EventType; import com.android.calendar.CalendarEventModel; import com.android.calendar.GeneralPreferences; import com.android.calendar.R; import com.android.calendar.Utils; /** * Allows the user to quickly create a new all-day event from the calendar's month view. */ public class CreateEventDialogFragment extends DialogFragment implements TextWatcher { private static final int TOKEN_CALENDARS = 1 << 3; private static final String KEY_DATE_STRING = "date_string"; private static final String KEY_DATE_IN_MILLIS = "date_in_millis"; private static final String EVENT_DATE_FORMAT = "%a, %b %d, %Y"; private AlertDialog mAlertDialog; private CalendarQueryService mService; private EditText mEventTitle; private View mColor; private TextView mCalendarName; private TextView mAccountName; private TextView mDate; private Button mButtonAddEvent; private CalendarController mController; private EditEventHelper mEditEventHelper; private String mDateString; private long mDateInMillis; private CalendarEventModel mModel; private long mCalendarId = -1; private String mCalendarOwner; private class CalendarQueryService extends AsyncQueryService { /** * @param context */ public CalendarQueryService(Context context) { super(context); } @Override public void onQueryComplete(int token, Object cookie, Cursor cursor) { setDefaultCalendarView(cursor); if (cursor != null) { cursor.close(); } } } public CreateEventDialogFragment() { // Empty constructor required for DialogFragment. } public CreateEventDialogFragment(Time day) { setDay(day); } public void setDay(Time day) { mDateString = day.format(EVENT_DATE_FORMAT); mDateInMillis = day.toMillis(true); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mDateString = savedInstanceState.getString(KEY_DATE_STRING); mDateInMillis = savedInstanceState.getLong(KEY_DATE_IN_MILLIS); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity activity = getActivity(); final LayoutInflater layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.create_event_dialog, null); mColor = view.findViewById(R.id.color); mCalendarName = (TextView) view.findViewById(R.id.calendar_name); mAccountName = (TextView) view.findViewById(R.id.account_name); mEventTitle = (EditText) view.findViewById(R.id.event_title); mEventTitle.addTextChangedListener(this); mDate = (TextView) view.findViewById(R.id.event_day); if (mDateString != null) { mDate.setText(mDateString); } mAlertDialog = new AlertDialog.Builder(activity) .setTitle(R.string.new_event_dialog_label) .setView(view) .setPositiveButton(R.string.create_event_dialog_save, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { createAllDayEvent(); dismiss(); } }) .setNeutralButton(R.string.edit_label, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mController.sendEventRelatedEventWithExtraWithTitleWithCalendarId(this, EventType.CREATE_EVENT, -1, mDateInMillis, mDateInMillis + DateUtils.DAY_IN_MILLIS, 0, 0, CalendarController.EXTRA_CREATE_ALL_DAY, -1, mEventTitle.getText().toString(), mCalendarId); dismiss(); } }) .setNegativeButton(android.R.string.cancel, null) .create(); return mAlertDialog; } @Override public void onResume() { super.onResume(); if (mButtonAddEvent == null) { mButtonAddEvent = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE); mButtonAddEvent.setEnabled(mEventTitle.getText().toString().length() > 0); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_DATE_STRING, mDateString); outState.putLong(KEY_DATE_IN_MILLIS, mDateInMillis); } @Override public void onActivityCreated(Bundle args) { super.onActivityCreated(args); final Context context = getActivity(); mController = CalendarController.getInstance(getActivity()); mEditEventHelper = new EditEventHelper(context); mModel = new CalendarEventModel(context); mService = new CalendarQueryService(context); mService.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI, EditEventHelper.CALENDARS_PROJECTION, EditEventHelper.CALENDARS_WHERE_WRITEABLE_VISIBLE, null, null); } private void createAllDayEvent() { mModel.mStart = mDateInMillis; mModel.mEnd = mDateInMillis + DateUtils.DAY_IN_MILLIS; mModel.mTitle = mEventTitle.getText().toString(); mModel.mAllDay = true; mModel.mCalendarId = mCalendarId; mModel.mOwnerAccount = mCalendarOwner; if (mEditEventHelper.saveEvent(mModel, null, 0)) { Toast.makeText(getActivity(), R.string.creating_event, Toast.LENGTH_SHORT).show(); } } @Override public void afterTextChanged(Editable s) { // Do nothing. } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing. } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (mButtonAddEvent != null) { mButtonAddEvent.setEnabled(s.length() > 0); } } // Find the calendar position in the cursor that matches calendar in // preference private void setDefaultCalendarView(Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { // Create an error message for the user that, when clicked, // will exit this activity without saving the event. dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.no_syncable_calendars).setIconAttribute( android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found) .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final Activity activity = getActivity(); if (activity != null) { Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); final String[] array = {"com.android.calendar"}; nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array); nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(nextIntent); + activity.startActivity(nextIntent); } } }) .setNegativeButton(android.R.string.no, null); builder.show(); return; } String defaultCalendar = Utils.getSharedPreference( getActivity(), GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE); cursor.moveToPosition(-1); while (cursor.moveToNext()) { String calendarOwner = cursor.getString(calendarOwnerIndex); if (defaultCalendar == null) { // There is no stored default upon the first time running. Use a primary // calendar in this case. if (calendarOwner != null && calendarOwner.equals(cursor.getString(accountNameIndex)) && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals( cursor.getString(accountTypeIndex))) { setCalendarFields(cursor); return; } } else if (defaultCalendar.equals(calendarOwner)) { // Found the default calendar. setCalendarFields(cursor); return; } } cursor.moveToFirst(); setCalendarFields(cursor); } private void setCalendarFields(Cursor cursor) { int calendarIdIndex = cursor.getColumnIndexOrThrow(Calendars._ID); int colorIndex = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR); int calendarNameIndex = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME); int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); mCalendarId = cursor.getLong(calendarIdIndex); mCalendarOwner = cursor.getString(calendarOwnerIndex); mColor.setBackgroundColor(Utils.getDisplayColorFromColor(cursor .getInt(colorIndex))); String accountName = cursor.getString(accountNameIndex); String calendarName = cursor.getString(calendarNameIndex); mCalendarName.setText(calendarName); if (calendarName.equals(accountName)) { mAccountName.setVisibility(View.GONE); } else { mAccountName.setVisibility(View.VISIBLE); mAccountName.setText(accountName); } } }
true
true
private void setDefaultCalendarView(Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { // Create an error message for the user that, when clicked, // will exit this activity without saving the event. dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.no_syncable_calendars).setIconAttribute( android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found) .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final Activity activity = getActivity(); if (activity != null) { Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); final String[] array = {"com.android.calendar"}; nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array); nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(nextIntent); } } }) .setNegativeButton(android.R.string.no, null); builder.show(); return; } String defaultCalendar = Utils.getSharedPreference( getActivity(), GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE); cursor.moveToPosition(-1); while (cursor.moveToNext()) { String calendarOwner = cursor.getString(calendarOwnerIndex); if (defaultCalendar == null) { // There is no stored default upon the first time running. Use a primary // calendar in this case. if (calendarOwner != null && calendarOwner.equals(cursor.getString(accountNameIndex)) && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals( cursor.getString(accountTypeIndex))) { setCalendarFields(cursor); return; } } else if (defaultCalendar.equals(calendarOwner)) { // Found the default calendar. setCalendarFields(cursor); return; } } cursor.moveToFirst(); setCalendarFields(cursor); }
private void setDefaultCalendarView(Cursor cursor) { if (cursor == null || cursor.getCount() == 0) { // Create an error message for the user that, when clicked, // will exit this activity without saving the event. dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.no_syncable_calendars).setIconAttribute( android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found) .setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final Activity activity = getActivity(); if (activity != null) { Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); final String[] array = {"com.android.calendar"}; nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array); nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(nextIntent); } } }) .setNegativeButton(android.R.string.no, null); builder.show(); return; } String defaultCalendar = Utils.getSharedPreference( getActivity(), GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); int calendarOwnerIndex = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int accountNameIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int accountTypeIndex = cursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE); cursor.moveToPosition(-1); while (cursor.moveToNext()) { String calendarOwner = cursor.getString(calendarOwnerIndex); if (defaultCalendar == null) { // There is no stored default upon the first time running. Use a primary // calendar in this case. if (calendarOwner != null && calendarOwner.equals(cursor.getString(accountNameIndex)) && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals( cursor.getString(accountTypeIndex))) { setCalendarFields(cursor); return; } } else if (defaultCalendar.equals(calendarOwner)) { // Found the default calendar. setCalendarFields(cursor); return; } } cursor.moveToFirst(); setCalendarFields(cursor); }
diff --git a/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/attributes/PathElementCSAttribution.java b/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/attributes/PathElementCSAttribution.java index 76e433d195..19d1889adf 100644 --- a/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/attributes/PathElementCSAttribution.java +++ b/examples/org.eclipse.ocl.examples.xtext.base/src/org/eclipse/ocl/examples/xtext/base/attributes/PathElementCSAttribution.java @@ -1,77 +1,77 @@ /** * <copyright> * * Copyright (c) 2012 E.D.Willink 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: * E.D.Willink - initial API and implementation * * </copyright> */ package org.eclipse.ocl.examples.xtext.base.attributes; import java.util.List; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EObject; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.ocl.examples.pivot.Element; import org.eclipse.ocl.examples.pivot.NamedElement; import org.eclipse.ocl.examples.pivot.scoping.AbstractAttribution; import org.eclipse.ocl.examples.pivot.scoping.EnvironmentView; import org.eclipse.ocl.examples.pivot.scoping.ScopeFilter; import org.eclipse.ocl.examples.pivot.scoping.ScopeView; import org.eclipse.ocl.examples.xtext.base.baseCST.PathElementCS; import org.eclipse.ocl.examples.xtext.base.baseCST.PathNameCS; public class PathElementCSAttribution extends AbstractAttribution { public static final @NonNull PathElementCSAttribution INSTANCE = new PathElementCSAttribution(); @Override public ScopeView computeLookup(@NonNull EObject target, @NonNull EnvironmentView environmentView, @NonNull ScopeView scopeView) { PathElementCS csPathElement = (PathElementCS)target; EClassifier eClassifier = csPathElement.getElementType(); if (eClassifier == null) { // If this is actually a definition - Element element = csPathElement.getElement(); + Element element = csPathElement.basicGetElement(); assert (element instanceof NamedElement) && !element.eIsProxy(); environmentView.addNamedElement((NamedElement)element); return null; } EClassifier savedRequiredType = environmentView.getRequiredType(); ScopeFilter scopeFilter = null; try { environmentView.setRequiredType(eClassifier); PathNameCS csPathName = csPathElement.getPathName(); List<PathElementCS> path = csPathName.getPath(); int index = path.indexOf(csPathElement); if (index >= path.size()-1) { // Last element may have a scope filter scopeFilter = csPathName.getScopeFilter(); if (scopeFilter != null) { environmentView.addFilter(scopeFilter); } } if (index <= 0) { // First path element is resolved in parent's parent scope environmentView.computeLookups(scopeView.getParent().getParent()); } else { // Subsequent elements in previous scope Element parent = path.get(index-1).getElement(); if ((parent != null) && !parent.eIsProxy()) { // environmentView.computeLookups(parent, null); environmentView.computeQualifiedLookups(parent); } } return null; } finally { if (scopeFilter != null) { environmentView.removeFilter(scopeFilter); } environmentView.setRequiredType(savedRequiredType); } } }
true
true
public ScopeView computeLookup(@NonNull EObject target, @NonNull EnvironmentView environmentView, @NonNull ScopeView scopeView) { PathElementCS csPathElement = (PathElementCS)target; EClassifier eClassifier = csPathElement.getElementType(); if (eClassifier == null) { // If this is actually a definition Element element = csPathElement.getElement(); assert (element instanceof NamedElement) && !element.eIsProxy(); environmentView.addNamedElement((NamedElement)element); return null; } EClassifier savedRequiredType = environmentView.getRequiredType(); ScopeFilter scopeFilter = null; try { environmentView.setRequiredType(eClassifier); PathNameCS csPathName = csPathElement.getPathName(); List<PathElementCS> path = csPathName.getPath(); int index = path.indexOf(csPathElement); if (index >= path.size()-1) { // Last element may have a scope filter scopeFilter = csPathName.getScopeFilter(); if (scopeFilter != null) { environmentView.addFilter(scopeFilter); } } if (index <= 0) { // First path element is resolved in parent's parent scope environmentView.computeLookups(scopeView.getParent().getParent()); } else { // Subsequent elements in previous scope Element parent = path.get(index-1).getElement(); if ((parent != null) && !parent.eIsProxy()) { // environmentView.computeLookups(parent, null); environmentView.computeQualifiedLookups(parent); } } return null; } finally { if (scopeFilter != null) { environmentView.removeFilter(scopeFilter); } environmentView.setRequiredType(savedRequiredType); } }
public ScopeView computeLookup(@NonNull EObject target, @NonNull EnvironmentView environmentView, @NonNull ScopeView scopeView) { PathElementCS csPathElement = (PathElementCS)target; EClassifier eClassifier = csPathElement.getElementType(); if (eClassifier == null) { // If this is actually a definition Element element = csPathElement.basicGetElement(); assert (element instanceof NamedElement) && !element.eIsProxy(); environmentView.addNamedElement((NamedElement)element); return null; } EClassifier savedRequiredType = environmentView.getRequiredType(); ScopeFilter scopeFilter = null; try { environmentView.setRequiredType(eClassifier); PathNameCS csPathName = csPathElement.getPathName(); List<PathElementCS> path = csPathName.getPath(); int index = path.indexOf(csPathElement); if (index >= path.size()-1) { // Last element may have a scope filter scopeFilter = csPathName.getScopeFilter(); if (scopeFilter != null) { environmentView.addFilter(scopeFilter); } } if (index <= 0) { // First path element is resolved in parent's parent scope environmentView.computeLookups(scopeView.getParent().getParent()); } else { // Subsequent elements in previous scope Element parent = path.get(index-1).getElement(); if ((parent != null) && !parent.eIsProxy()) { // environmentView.computeLookups(parent, null); environmentView.computeQualifiedLookups(parent); } } return null; } finally { if (scopeFilter != null) { environmentView.removeFilter(scopeFilter); } environmentView.setRequiredType(savedRequiredType); } }
diff --git a/src/com/weibogrep/user/Updater.java b/src/com/weibogrep/user/Updater.java index e55cf72..cf36e55 100644 --- a/src/com/weibogrep/user/Updater.java +++ b/src/com/weibogrep/user/Updater.java @@ -1,23 +1,30 @@ package com.weibogrep.user; import java.io.*; import com.weibogrep.util.*; public class Updater { public static void main(String []args) { updateAll(); } public static void updateAll() { File baseDir = new File(UserMgmt.BASE_DIR); - String[] users = baseDir.list(); - for (int i = 0; i < users.length; i++) { - long uid = Long.parseLong(users[i]); - UserMgmt um = new UserMgmt(uid); - ZLog.info("updating " + uid + " , last post id is " + um.getLastPost()); - um.update(); + File[] files = baseDir.listFiles(); + for (int i = 0; i < files.length; i++) { + if (files[i].isDirectory()) { + try { + long uid = Long.parseLong(files[i].getName()); + UserMgmt um = new UserMgmt(uid); + ZLog.info("updating " + uid + " , last post id is " + um.getLastPost()); + um.update(); + } catch (Exception e) { + ZLog.err("updating " + files[i].getName() + " error"); + e.printStackTrace(); + } + } } } }
true
true
public static void updateAll() { File baseDir = new File(UserMgmt.BASE_DIR); String[] users = baseDir.list(); for (int i = 0; i < users.length; i++) { long uid = Long.parseLong(users[i]); UserMgmt um = new UserMgmt(uid); ZLog.info("updating " + uid + " , last post id is " + um.getLastPost()); um.update(); } }
public static void updateAll() { File baseDir = new File(UserMgmt.BASE_DIR); File[] files = baseDir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { try { long uid = Long.parseLong(files[i].getName()); UserMgmt um = new UserMgmt(uid); ZLog.info("updating " + uid + " , last post id is " + um.getLastPost()); um.update(); } catch (Exception e) { ZLog.err("updating " + files[i].getName() + " error"); e.printStackTrace(); } } } }
diff --git a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java index 1e275c8..fd2aed4 100644 --- a/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java +++ b/src/net/appositedesigns/fileexplorer/quickactions/QuickActionHelper.java @@ -1,104 +1,105 @@ package net.appositedesigns.fileexplorer.quickactions; import java.io.File; import net.appositedesigns.fileexplorer.FileExplorerMain; import net.appositedesigns.fileexplorer.FileListEntry; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.util.FileActionsHelper; import android.view.View; import android.view.View.OnClickListener; public final class QuickActionHelper { private FileExplorerMain mContext; public QuickActionHelper(FileExplorerMain mContext) { super(); this.mContext = mContext; } public void showQuickActions(final View view, final FileListEntry entry) { final File file = entry.getPath(); final QuickAction actions = new QuickAction(view); int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext); ActionItem action = null; for(int i=availableActions.length-1;i>=0;i--) { int a = availableActions[i]; action = null; switch (a) { case R.string.action_cut: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.cutFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_copy: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.copyFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_delete: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete)); action.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { actions.dismiss(); FileActionsHelper.deleteFile(file, mContext); } }); + break; case R.string.action_share: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.share(file, mContext); } }); break; default: break; } if(action!=null) { actions.addActionItem(action); } } actions.setAnimStyle(QuickAction.ANIM_AUTO); actions.show(); } }
true
true
public void showQuickActions(final View view, final FileListEntry entry) { final File file = entry.getPath(); final QuickAction actions = new QuickAction(view); int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext); ActionItem action = null; for(int i=availableActions.length-1;i>=0;i--) { int a = availableActions[i]; action = null; switch (a) { case R.string.action_cut: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.cutFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_copy: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.copyFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_delete: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete)); action.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { actions.dismiss(); FileActionsHelper.deleteFile(file, mContext); } }); case R.string.action_share: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.share(file, mContext); } }); break; default: break; } if(action!=null) { actions.addActionItem(action); } } actions.setAnimStyle(QuickAction.ANIM_AUTO); actions.show(); }
public void showQuickActions(final View view, final FileListEntry entry) { final File file = entry.getPath(); final QuickAction actions = new QuickAction(view); int[] availableActions = FileActionsHelper.getContextMenuOptions(file, mContext); ActionItem action = null; for(int i=availableActions.length-1;i>=0;i--) { int a = availableActions[i]; action = null; switch (a) { case R.string.action_cut: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_cut)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.cutFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_copy: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_copy)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.copyFile(file, mContext); actions.dismiss(); } }); break; case R.string.action_delete: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_delete)); action.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { actions.dismiss(); FileActionsHelper.deleteFile(file, mContext); } }); break; case R.string.action_share: action = new ActionItem(mContext.getResources().getDrawable(R.drawable.action_share)); action.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { FileActionsHelper.share(file, mContext); } }); break; default: break; } if(action!=null) { actions.addActionItem(action); } } actions.setAnimStyle(QuickAction.ANIM_AUTO); actions.show(); }
diff --git a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java index 9a48c6f..e2dd308 100644 --- a/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java +++ b/bundles/org.eclipse.wst.xml.xpath2.processor/src/org/eclipse/wst/xml/xpath2/processor/internal/types/ElementType.java @@ -1,193 +1,193 @@ /******************************************************************************* * Copyright (c) 2005, 2009 Andrea Bittau, University College London, 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: * Andrea Bittau - initial API and implementation from the PsychoPath XPath 2.0 * Mukul Gandhi - bug 276134 - improvements to schema aware primitive type support * for attribute/element nodes * David Carver - bug 281186 - implementation of fn:id and fn:idref *******************************************************************************/ package org.eclipse.wst.xml.xpath2.processor.internal.types; import org.apache.xerces.dom.PSVIElementNSImpl; import org.apache.xerces.xs.XSTypeDefinition; import org.eclipse.wst.xml.xpath2.processor.ResultSequence; import org.eclipse.wst.xml.xpath2.processor.ResultSequenceFactory; import org.eclipse.wst.xml.xpath2.processor.function.XSCtrLibrary; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.TypeInfo; /** * A representation of the ElementType datatype */ public class ElementType extends NodeType { private Element _value; private String _string_value; // constructor only usefull for string_type() // XXX needs to be fixed in future /** * Initialises to a null element */ public ElementType() { this(null, 0); } /** * Initialises according to the supplied parameters * * @param v * The element being represented * @param doc_order * The document order */ public ElementType(Element v, int doc_order) { super(v, doc_order); _value = v; _string_value = null; } /** * Retrieves the actual element value being represented * * @return Actual element value being represented */ public Element value() { return _value; } /** * Retrieves the datatype's full pathname * * @return "element" which is the datatype's full pathname */ @Override public String string_type() { return "element"; } /** * Retrieves a String representation of the element being stored * * @return String representation of the element being stored */ @Override public String string_value() { // XXX can we cache ? if (_string_value != null) return _string_value; _string_value = textnode_strings(_value); return _string_value; } /** * Creates a new ResultSequence consisting of the element stored * * @return New ResultSequence consisting of the element stored */ @Override public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); - if (XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { + if (typeDef != null && XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; } // recursively concatenate TextNode strings /** * Recursively concatenate TextNode strings * * @param node * Node to recurse * @return String representation of the node supplied */ public static String textnode_strings(Node node) { String result = ""; if (node.getNodeType() == Node.TEXT_NODE) { Text tn = (Text) node; result += tn.getData(); } NodeList nl = node.getChildNodes(); // concatenate children for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); result += textnode_strings(n); } return result; } /** * Retrieves the name of the node * * @return QName representation of the name of the node */ @Override public QName node_name() { QName name = new QName(_value.getPrefix(), _value.getLocalName(), _value.getNamespaceURI()); return name; } @Override public ResultSequence nilled() { ResultSequence rs = ResultSequenceFactory.create_new(); // XXX PSVI !!! rs.add(new XSBoolean(false)); return rs; } /** * @since 1.1 */ @Override public boolean isID() { return isElementType(SCHEMA_TYPE_ID); } /** * @since 1.1 */ @Override public boolean isIDREF() { return isElementType(SCHEMA_TYPE_IDREF); } protected boolean isElementType(String typeName) { TypeInfo typeInfo = _value.getSchemaTypeInfo(); return isType(typeInfo, typeName); } }
true
true
public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); if (XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; }
public ResultSequence typed_value() { ResultSequence rs = ResultSequenceFactory.create_new(); PSVIElementNSImpl psviElem = (PSVIElementNSImpl)_value; XSTypeDefinition typeDef = psviElem.getTypeDefinition(); if (typeDef != null && XSCtrLibrary.XML_SCHEMA_NS.equals(typeDef.getNamespace())) { Object schemaTypeValue = getTypedValueForPrimitiveType(typeDef); if (schemaTypeValue != null) { rs.add((AnyType)schemaTypeValue); } else { rs.add(new XSUntypedAtomic(string_value())); } } else { rs.add(new XSUntypedAtomic(string_value())); } return rs; }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/synchronize/StopManager.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/synchronize/StopManager.java index 80b8bde1e..24e8834da 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/synchronize/StopManager.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/synchronize/StopManager.java @@ -1,525 +1,526 @@ package de.fu_berlin.inf.dpp.synchronize; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.picocontainer.Disposable; import de.fu_berlin.inf.dpp.User; import de.fu_berlin.inf.dpp.activities.AbstractActivityReceiver; import de.fu_berlin.inf.dpp.activities.IActivity; import de.fu_berlin.inf.dpp.activities.IActivityReceiver; import de.fu_berlin.inf.dpp.activities.StopActivity; import de.fu_berlin.inf.dpp.activities.StopActivity.State; import de.fu_berlin.inf.dpp.activities.StopActivity.Type; import de.fu_berlin.inf.dpp.annotations.Component; import de.fu_berlin.inf.dpp.observables.SharedProjectObservable; import de.fu_berlin.inf.dpp.project.IActivityListener; import de.fu_berlin.inf.dpp.project.IActivityProvider; import de.fu_berlin.inf.dpp.project.ISharedProject; import de.fu_berlin.inf.dpp.project.internal.SharedProject; import de.fu_berlin.inf.dpp.util.Util; import de.fu_berlin.inf.dpp.util.ValueChangeListener; @Component(module = "core") public class StopManager implements IActivityProvider, Disposable { private static Logger log = Logger.getLogger(StopManager.class.getName()); // Waits MILLISTOWAIT ms until the next test for progress cancellation public final int MILLISTOWAIT = 100; private final List<IActivityListener> activityListeners = new LinkedList<IActivityListener>(); protected List<Blockable> blockables = new LinkedList<Blockable>(); protected ISharedProject sharedProject; SharedProjectObservable sharedProjectObservable; /** * Maps a User to a List of his StartHandles. Never touch this directly, use * the add and remove methods. */ private Map<User, List<StartHandle>> startHandles = Collections .synchronizedMap(new HashMap<User, List<StartHandle>>()); /** * For every initiated unlock (identified by its StopActivity id) there is * one acknowledgment expected. */ private Map<String, StartHandle> startsToBeAcknowledged = Collections .synchronizedMap(new HashMap<String, StartHandle>()); // blocking mechanism protected Lock reentrantLock = new ReentrantLock(); protected final Condition acknowledged = reentrantLock.newCondition(); /** * For every initiated StopActivity (type: LockRequest) there is one * acknowledgment expected. */ protected Set<StopActivity> expectedAcknowledgments = Collections .synchronizedSet(new HashSet<StopActivity>()); protected ValueChangeListener<SharedProject> sharedProjectObserver = new ValueChangeListener<SharedProject>() { public void setValue(SharedProject newSharedProject) { if (newSharedProject == sharedProject) return; // session ended, start all local start handles if (newSharedProject == null && sharedProject != null) { for (StartHandle startHandle : getStartHandles(sharedProject .getLocalUser())) { startHandle.start(); } lockProject(false); } if (sharedProject != null) { sharedProject.removeActivityProvider(StopManager.this); reset(); } sharedProject = newSharedProject; if (newSharedProject != null) { newSharedProject.addActivityProvider(StopManager.this); } } }; public StopManager(SharedProjectObservable observable) { this.sharedProjectObservable = observable; observable.add(sharedProjectObserver); } protected IActivityReceiver activityReceiver = new AbstractActivityReceiver() { @Override public void receive(final StopActivity stopActivity) { if (sharedProject == null) throw new IllegalStateException( "Cannot receive StopActivities without a shared project"); User user = sharedProject.getUser(stopActivity.getRecipient()); if (user == null || !user.isLocal()) throw new IllegalArgumentException( "Received StopActivity which is not for the local user"); if (stopActivity.getType() == Type.LOCKREQUEST) { /* * local user locks his project and adds a startHandle so he * knows he is locked. Then he acknowledges */ if (stopActivity.getState() == State.INITIATED) { addStartHandle(generateStartHandle(stopActivity)); // locks project and acknowledges Util.runSafeSWTSync(log, new Runnable() { public void run() { lockProject(true); fireActivity(stopActivity .generateAcknowledgment(sharedProject .getLocalUser().getJID().toString())); } }); return; } if (stopActivity.getState() == State.ACKNOWLEDGED) { if (!expectedAcknowledgments.contains(stopActivity)) { log.warn("Received unexpected StopActivity: " + stopActivity); return; } // it has to be removed from the expected ack list // because it already arrived if (expectedAcknowledgments.remove(stopActivity)) { reentrantLock.lock(); acknowledged.signalAll(); reentrantLock.unlock(); return; } else { log.warn("Received unexpected " + "StopActivity acknowledgement: " + stopActivity); return; } } } if (stopActivity.getType() == Type.UNLOCKREQUEST) { if (stopActivity.getState() == State.INITIATED) { executeUnlock(generateStartHandle(stopActivity)); // sends an acknowledgment fireActivity(stopActivity .generateAcknowledgment(sharedProject.getLocalUser() .getJID().toString())); + return; } if (stopActivity.getState() == State.ACKNOWLEDGED) { StartHandle handle = startsToBeAcknowledged .remove(stopActivity.getActivityID()); if (handle == null) { log.error("StartHandle for " + stopActivity + " could not be found."); return; } handle.acknowledge(); return; } } throw new IllegalArgumentException( "StopActivity is of unknown type: " + stopActivity); } }; /** * Blocking method that asks the given users to halt all user-input and * returns a list of handles to be used when the users can start again. * * TODO This method is not tested for more than one user since it is not * used yet. * * @param users * the participants who has to stop * @param cause * the cause for stopping as it is displayed in the progress * monitor * * @param monitor * The caller is expected to call beginTask and done on the given * SubMonitor * * @noSWT This method mustn't be called from the SWT thread. * * @blocking returning after the given users acknowledged the stop * * @cancelable This method can be canceled by the user * * @throws CancellationException */ public List<StartHandle> stop(final Collection<User> users, final String cause, final SubMonitor monitor) throws CancellationException { final List<StartHandle> resultingHandles = Collections .synchronizedList(new LinkedList<StartHandle>()); final CountDownLatch doneSignal = new CountDownLatch(users.size()); for (final User user : users) { Util.runSafeAsync(log, new Runnable() { public void run() { try { StartHandle startHandle = stop(user, cause, SubMonitor .convert(new NullProgressMonitor())); // FIXME Race Condition: startHandle was not added yet // in case of cancellation resultingHandles.add(startHandle); log.debug("Added " + startHandle + " to resulting handles."); doneSignal.countDown(); } catch (CancellationException e) { log.debug("User canceled the Stopping"); monitor.setCanceled(true); } catch (InterruptedException e) { log .debug("Canceling because of an InterruptedException"); monitor.setCanceled(true); } } }); } while (resultingHandles.size() != users.size() && !monitor.isCanceled()) { try { // waiting for all startHandles doneSignal.await(MILLISTOWAIT, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log .error("Stopping was interrupted. Not all users could successfully be stopped."); } } if (monitor.isCanceled()) { // Restart the already stopped users log .debug("Monitor was canceled. Restarting already stopped users."); for (StartHandle startHandle : resultingHandles) startHandle.start(); throw new CancellationException(); } return resultingHandles; } /** * Blocking method that asks the given user to halt all user-input and * returns a handle to be used when the user can start again. * * @param user * the participant who has to stop * @param cause * the cause for stopping as it is displayed in the progress * monitor * * @param progress * The caller is expected to call beginTask and done on the given * SubMonitor * * @noSWT This method mustn't be called from the SWT thread. * * @blocking returning after the given user acknowledged the stop * * @cancelable This method can be canceled by the user * * @throws CancellationException * @throws InterruptedException */ public StartHandle stop(User user, String cause, final SubMonitor progress) throws CancellationException, InterruptedException { if (sharedProject == null) throw new IllegalStateException( "Stop cannot be called without a shared project"); // Creating StopActivity for asking user to stop final StopActivity stopActivity = new StopActivity(sharedProject .getLocalUser().getJID().toString(), sharedProject.getLocalUser() .getJID(), user.getJID(), Type.LOCKREQUEST, State.INITIATED); StartHandle handle = generateStartHandle(stopActivity); addStartHandle(handle); // Short cut if affected user is local if (user.isLocal()) { Util.runSafeSWTSync(log, new Runnable() { public void run() { lockProject(true); } }); return handle; } StopActivity expectedAck = stopActivity.generateAcknowledgment(user .getJID().toString()); expectedAcknowledgments.add(expectedAck); Util.runSafeSWTSync(log, new Runnable() { public void run() { fireActivity(stopActivity); } }); // Block until user acknowledged log.debug("Waiting for acknowledgment " + Util.prefix(user.getJID())); reentrantLock.lock(); try { while (expectedAcknowledgments.contains(expectedAck) && !progress.isCanceled()) { if (acknowledged.await(MILLISTOWAIT, TimeUnit.MILLISECONDS)) { continue; /* * Used to make FindBugs happy that we don't do * anything if we are woken up */ } } if (expectedAcknowledgments.contains(expectedAck)) { log.warn("No acknowlegment arrived, gave up waiting"); expectedAcknowledgments.remove(expectedAck); handle.start(); throw new CancellationException(); } log.debug("Acknowledgment arrived " + Util.prefix(user.getJID())); } catch (InterruptedException e) { handle.start(); throw new InterruptedException(); } finally { reentrantLock.unlock(); } return handle; } /** * The goal of this method is to ensure that the local user cannot cause any * editing activities (FileActivities and TextEditActivities). * * @param lock * if true the project gets locked, else it gets unlocked */ protected void lockProject(boolean lock) { for (Blockable blockable : blockables) { if (lock) blockable.block(); else blockable.unblock(); } } /** * Unlocks project without sending an acknowledgment if there don't exist * any more startHandles. * * @return true if the affected user is unlocked afterwards */ protected boolean executeUnlock(StartHandle startHandle) { if (!startHandle.getUser().isLocal()) throw new IllegalArgumentException( "ExecuteUnlock may only be called with a StartHandle for the local user"); if (!removeStartHandle(startHandle)) { /* * Ok if the local user was the initiator of the stop. If not * something is wrong. */ log.debug(startHandle + " couldn't be removed because it doesn't exist any more."); } int remainingHandles = getStartHandles(sharedProject.getLocalUser()) .size(); if (remainingHandles > 0) { log.debug(remainingHandles + " startHandles remaining."); return false; } Util.runSafeSWTSync(log, new Runnable() { public void run() { lockProject(false); } }); return true; } /** * Sends an initiated unlock request. * * @param handle * the startHandle whose start() initiated the unlocking */ public void initiateUnlock(StartHandle handle) { if (sharedProject == null) throw new IllegalStateException( "Cannot initiate unlock without a shared project"); // short cut for local user if (handle.getUser().isLocal()) { executeUnlock(handle); return; } startsToBeAcknowledged.put(handle.getHandleID(), handle); final StopActivity activity = new StopActivity(sharedProject .getLocalUser().getJID().toString(), sharedProject.getLocalUser() .getJID(), handle.getUser().getJID(), Type.UNLOCKREQUEST, State.INITIATED, handle.getHandleID()); Util.runSafeSWTSync(log, new Runnable() { public void run() { fireActivity(activity); } }); } /** * {@inheritDoc} */ public void addActivityListener(IActivityListener listener) { activityListeners.add(listener); } /** * {@inheritDoc} */ public void exec(IActivity activity) { activity.dispatch(activityReceiver); } /** * {@inheritDoc} */ public void removeActivityListener(IActivityListener listener) { activityListeners.remove(listener); } public void fireActivity(StopActivity stopActivity) { User recipient = sharedProject.getUser(stopActivity.getRecipient()); if (recipient == null) throw new IllegalArgumentException("StopActivity contains" + " recipient which already left: " + stopActivity); sharedProject.sendActivity(recipient, stopActivity); } /** * Adds a StartHandle to startHandles, which maps a user to a list of * StartHandles. These Lists are created lazily. */ public void addStartHandle(StartHandle startHandle) { getStartHandles(startHandle.getUser()).add(startHandle); } /** * Removes a StartHandle from startHandles. If the list for user is empty * then the user is removed from startHandles. * * @return false if the given startHandle didn't exist in Map, true * otherwise */ public boolean removeStartHandle(StartHandle startHandle) { return getStartHandles(startHandle.getUser()).remove(startHandle); } public synchronized List<StartHandle> getStartHandles(User user) { List<StartHandle> result = startHandles.get(user); if (result == null) { result = new CopyOnWriteArrayList<StartHandle>(); startHandles.put(user, result); } return result; } public StartHandle generateStartHandle(StopActivity stopActivity) { User user = sharedProject.getUser(stopActivity.getUser()); return new StartHandle(user, this, stopActivity.getActivityID()); } public void addBlockable(Blockable stoppable) { blockables.add(stoppable); } public void removeBlockable(Blockable stoppable) { blockables.remove(stoppable); } public void dispose() { sharedProjectObservable.remove(sharedProjectObserver); } protected void reset() { lockProject(false); startHandles.clear(); expectedAcknowledgments.clear(); } }
true
true
public void receive(final StopActivity stopActivity) { if (sharedProject == null) throw new IllegalStateException( "Cannot receive StopActivities without a shared project"); User user = sharedProject.getUser(stopActivity.getRecipient()); if (user == null || !user.isLocal()) throw new IllegalArgumentException( "Received StopActivity which is not for the local user"); if (stopActivity.getType() == Type.LOCKREQUEST) { /* * local user locks his project and adds a startHandle so he * knows he is locked. Then he acknowledges */ if (stopActivity.getState() == State.INITIATED) { addStartHandle(generateStartHandle(stopActivity)); // locks project and acknowledges Util.runSafeSWTSync(log, new Runnable() { public void run() { lockProject(true); fireActivity(stopActivity .generateAcknowledgment(sharedProject .getLocalUser().getJID().toString())); } }); return; } if (stopActivity.getState() == State.ACKNOWLEDGED) { if (!expectedAcknowledgments.contains(stopActivity)) { log.warn("Received unexpected StopActivity: " + stopActivity); return; } // it has to be removed from the expected ack list // because it already arrived if (expectedAcknowledgments.remove(stopActivity)) { reentrantLock.lock(); acknowledged.signalAll(); reentrantLock.unlock(); return; } else { log.warn("Received unexpected " + "StopActivity acknowledgement: " + stopActivity); return; } } } if (stopActivity.getType() == Type.UNLOCKREQUEST) { if (stopActivity.getState() == State.INITIATED) { executeUnlock(generateStartHandle(stopActivity)); // sends an acknowledgment fireActivity(stopActivity .generateAcknowledgment(sharedProject.getLocalUser() .getJID().toString())); } if (stopActivity.getState() == State.ACKNOWLEDGED) { StartHandle handle = startsToBeAcknowledged .remove(stopActivity.getActivityID()); if (handle == null) { log.error("StartHandle for " + stopActivity + " could not be found."); return; } handle.acknowledge(); return; } } throw new IllegalArgumentException( "StopActivity is of unknown type: " + stopActivity); }
public void receive(final StopActivity stopActivity) { if (sharedProject == null) throw new IllegalStateException( "Cannot receive StopActivities without a shared project"); User user = sharedProject.getUser(stopActivity.getRecipient()); if (user == null || !user.isLocal()) throw new IllegalArgumentException( "Received StopActivity which is not for the local user"); if (stopActivity.getType() == Type.LOCKREQUEST) { /* * local user locks his project and adds a startHandle so he * knows he is locked. Then he acknowledges */ if (stopActivity.getState() == State.INITIATED) { addStartHandle(generateStartHandle(stopActivity)); // locks project and acknowledges Util.runSafeSWTSync(log, new Runnable() { public void run() { lockProject(true); fireActivity(stopActivity .generateAcknowledgment(sharedProject .getLocalUser().getJID().toString())); } }); return; } if (stopActivity.getState() == State.ACKNOWLEDGED) { if (!expectedAcknowledgments.contains(stopActivity)) { log.warn("Received unexpected StopActivity: " + stopActivity); return; } // it has to be removed from the expected ack list // because it already arrived if (expectedAcknowledgments.remove(stopActivity)) { reentrantLock.lock(); acknowledged.signalAll(); reentrantLock.unlock(); return; } else { log.warn("Received unexpected " + "StopActivity acknowledgement: " + stopActivity); return; } } } if (stopActivity.getType() == Type.UNLOCKREQUEST) { if (stopActivity.getState() == State.INITIATED) { executeUnlock(generateStartHandle(stopActivity)); // sends an acknowledgment fireActivity(stopActivity .generateAcknowledgment(sharedProject.getLocalUser() .getJID().toString())); return; } if (stopActivity.getState() == State.ACKNOWLEDGED) { StartHandle handle = startsToBeAcknowledged .remove(stopActivity.getActivityID()); if (handle == null) { log.error("StartHandle for " + stopActivity + " could not be found."); return; } handle.acknowledge(); return; } } throw new IllegalArgumentException( "StopActivity is of unknown type: " + stopActivity); }
diff --git a/src/main/java/com/gitblit/wicket/pages/BlamePage.java b/src/main/java/com/gitblit/wicket/pages/BlamePage.java index ef023b75..ae85c433 100644 --- a/src/main/java/com/gitblit/wicket/pages/BlamePage.java +++ b/src/main/java/com/gitblit/wicket/pages/BlamePage.java @@ -1,286 +1,289 @@ /* * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.wicket.pages; import java.awt.Color; import java.text.DateFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.behavior.SimpleAttributeModifier; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.revwalk.RevCommit; import com.gitblit.Keys; import com.gitblit.models.AnnotatedLine; import com.gitblit.models.PathModel; import com.gitblit.utils.ColorFactory; import com.gitblit.utils.DiffUtils; import com.gitblit.utils.JGitUtils; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.CacheControl; import com.gitblit.wicket.CacheControl.LastModified; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.panels.CommitHeaderPanel; import com.gitblit.wicket.panels.LinkPanel; import com.gitblit.wicket.panels.PathBreadcrumbsPanel; @CacheControl(LastModified.BOOT) public class BlamePage extends RepositoryPage { /** * The different types of Blame visualizations. */ private enum BlameType { COMMIT, AUTHOR, AGE; private BlameType() { } public static BlameType get(String name) { for (BlameType blameType : BlameType.values()) { if (blameType.name().equalsIgnoreCase(name)) { return blameType; } } throw new IllegalArgumentException("Unknown Blame Type [" + name + "]"); } @Override public String toString() { return name().toLowerCase(); } } public BlamePage(PageParameters params) { super(params); final String blobPath = WicketUtils.getPath(params); final String blameTypeParam = params.getString("blametype", BlameType.COMMIT.toString()); final BlameType activeBlameType = BlameType.get(blameTypeParam); RevCommit commit = getCommit(); add(new BookmarkablePageLink<Void>("blobLink", BlobPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); add(new BookmarkablePageLink<Void>("commitLink", CommitPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); add(new BookmarkablePageLink<Void>("commitDiffLink", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); // blame page links add(new BookmarkablePageLink<Void>("headLink", BlamePage.class, WicketUtils.newPathParameter(repositoryName, Constants.HEAD, blobPath))); add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); // "Blame by" links for (BlameType type : BlameType.values()) { String typeString = type.toString(); PageParameters blameTypePageParam = WicketUtils.newBlameTypeParameter(repositoryName, commit.getName(), WicketUtils.getPath(params), typeString); String blameByLinkText = "blameBy" + Character.toUpperCase(typeString.charAt(0)) + typeString.substring(1) + "Link"; BookmarkablePageLink<Void> blameByPageLink = new BookmarkablePageLink<Void>(blameByLinkText, BlamePage.class, blameTypePageParam); if (activeBlameType == type) { blameByPageLink.add(new SimpleAttributeModifier("style", "font-weight:bold;")); } add(blameByPageLink); } add(new CommitHeaderPanel("commitHeader", repositoryName, commit)); add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, blobPath, objectId)); String format = app().settings().getString(Keys.web.datetimestampLongFormat, "EEEE, MMMM d, yyyy HH:mm Z"); final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(getTimeZone()); PathModel pathModel = null; List<PathModel> paths = JGitUtils.getFilesInPath(getRepository(), StringUtils.getRootPath(blobPath), commit); for (PathModel path : paths) { if (path.path.equals(blobPath)) { pathModel = path; break; } } if (pathModel == null) { + final String notFound = MessageFormat.format("Blame page failed to find {0} in {1} @ {2}", + blobPath, repositoryName, objectId); + logger.error(notFound); add(new Label("annotation").setVisible(false)); add(new Label("missingBlob", missingBlob(blobPath, commit)).setEscapeModelStrings(false)); return; } add(new Label("missingBlob").setVisible(false)); List<AnnotatedLine> lines = DiffUtils.blame(getRepository(), blobPath, objectId); final Map<?, String> colorMap = initializeColors(activeBlameType, lines); ListDataProvider<AnnotatedLine> blameDp = new ListDataProvider<AnnotatedLine>(lines); - DataView<AnnotatedLine> blameView = new DataView<AnnotatedLine>("blameView", blameDp) { + DataView<AnnotatedLine> blameView = new DataView<AnnotatedLine>("annotation", blameDp) { private static final long serialVersionUID = 1L; private String lastCommitId = ""; private boolean showInitials = true; private String zeroId = ObjectId.zeroId().getName(); @Override public void populateItem(final Item<AnnotatedLine> item) { final AnnotatedLine entry = item.getModelObject(); // commit id and author if (!lastCommitId.equals(entry.commitId)) { lastCommitId = entry.commitId; if (zeroId.equals(entry.commitId)) { // unknown commit item.add(new Label("commit", "<?>")); showInitials = false; } else { // show the link for first line LinkPanel commitLink = new LinkPanel("commit", null, getShortObjectId(entry.commitId), CommitPage.class, newCommitParameter(entry.commitId)); WicketUtils.setHtmlTooltip(commitLink, MessageFormat.format("{0}, {1}", entry.author, df.format(entry.when))); item.add(commitLink); WicketUtils.setCssStyle(item, "border-top: 1px solid #ddd;"); showInitials = true; } } else { if (showInitials) { showInitials = false; // show author initials item.add(new Label("commit", getInitials(entry.author))); } else { // hide the commit link until the next block item.add(new Label("commit").setVisible(false)); } } // line number item.add(new Label("line", "" + entry.lineNumber)); // line content String color; switch (activeBlameType) { case AGE: color = colorMap.get(entry.when); break; case AUTHOR: color = colorMap.get(entry.author); break; default: color = colorMap.get(entry.commitId); break; } Component data = new Label("data", StringUtils.escapeForHtml(entry.data, true)).setEscapeModelStrings(false); data.add(new SimpleAttributeModifier("style", "background-color: " + color + ";")); item.add(data); } }; add(blameView); } private String getInitials(String author) { StringBuilder sb = new StringBuilder(); String[] chunks = author.split(" "); for (String chunk : chunks) { sb.append(chunk.charAt(0)); } return sb.toString().toUpperCase(); } @Override protected String getPageName() { return getString("gb.blame"); } @Override protected Class<? extends BasePage> getRepoNavPageClass() { return TreePage.class; } protected String missingBlob(String blobPath, RevCommit commit) { StringBuilder sb = new StringBuilder(); sb.append("<div class=\"alert alert-error\">"); String pattern = getString("gb.doesNotExistInTree").replace("{0}", "<b>{0}</b>").replace("{1}", "<b>{1}</b>"); sb.append(MessageFormat.format(pattern, blobPath, commit.getTree().getId().getName())); sb.append("</div>"); return sb.toString(); } private Map<?, String> initializeColors(BlameType blameType, List<AnnotatedLine> lines) { ColorFactory colorFactory = new ColorFactory(); Map<?, String> colorMap; if (BlameType.AGE == blameType) { Set<Date> keys = new TreeSet<Date>(new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { // younger code has a brighter, older code lightens to white return o1.compareTo(o2); } }); for (AnnotatedLine line : lines) { keys.add(line.when); } // TODO consider making this a setting colorMap = colorFactory.getGraduatedColorMap(keys, Color.decode("#FFA63A")); } else { Set<String> keys = new HashSet<String>(); for (AnnotatedLine line : lines) { if (blameType == BlameType.AUTHOR) { keys.add(line.author); } else { keys.add(line.commitId); } } colorMap = colorFactory.getRandomColorMap(keys); } return colorMap; } }
false
true
public BlamePage(PageParameters params) { super(params); final String blobPath = WicketUtils.getPath(params); final String blameTypeParam = params.getString("blametype", BlameType.COMMIT.toString()); final BlameType activeBlameType = BlameType.get(blameTypeParam); RevCommit commit = getCommit(); add(new BookmarkablePageLink<Void>("blobLink", BlobPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); add(new BookmarkablePageLink<Void>("commitLink", CommitPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); add(new BookmarkablePageLink<Void>("commitDiffLink", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); // blame page links add(new BookmarkablePageLink<Void>("headLink", BlamePage.class, WicketUtils.newPathParameter(repositoryName, Constants.HEAD, blobPath))); add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); // "Blame by" links for (BlameType type : BlameType.values()) { String typeString = type.toString(); PageParameters blameTypePageParam = WicketUtils.newBlameTypeParameter(repositoryName, commit.getName(), WicketUtils.getPath(params), typeString); String blameByLinkText = "blameBy" + Character.toUpperCase(typeString.charAt(0)) + typeString.substring(1) + "Link"; BookmarkablePageLink<Void> blameByPageLink = new BookmarkablePageLink<Void>(blameByLinkText, BlamePage.class, blameTypePageParam); if (activeBlameType == type) { blameByPageLink.add(new SimpleAttributeModifier("style", "font-weight:bold;")); } add(blameByPageLink); } add(new CommitHeaderPanel("commitHeader", repositoryName, commit)); add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, blobPath, objectId)); String format = app().settings().getString(Keys.web.datetimestampLongFormat, "EEEE, MMMM d, yyyy HH:mm Z"); final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(getTimeZone()); PathModel pathModel = null; List<PathModel> paths = JGitUtils.getFilesInPath(getRepository(), StringUtils.getRootPath(blobPath), commit); for (PathModel path : paths) { if (path.path.equals(blobPath)) { pathModel = path; break; } } if (pathModel == null) { add(new Label("annotation").setVisible(false)); add(new Label("missingBlob", missingBlob(blobPath, commit)).setEscapeModelStrings(false)); return; } add(new Label("missingBlob").setVisible(false)); List<AnnotatedLine> lines = DiffUtils.blame(getRepository(), blobPath, objectId); final Map<?, String> colorMap = initializeColors(activeBlameType, lines); ListDataProvider<AnnotatedLine> blameDp = new ListDataProvider<AnnotatedLine>(lines); DataView<AnnotatedLine> blameView = new DataView<AnnotatedLine>("blameView", blameDp) { private static final long serialVersionUID = 1L; private String lastCommitId = ""; private boolean showInitials = true; private String zeroId = ObjectId.zeroId().getName(); @Override public void populateItem(final Item<AnnotatedLine> item) { final AnnotatedLine entry = item.getModelObject(); // commit id and author if (!lastCommitId.equals(entry.commitId)) { lastCommitId = entry.commitId; if (zeroId.equals(entry.commitId)) { // unknown commit item.add(new Label("commit", "<?>")); showInitials = false; } else { // show the link for first line LinkPanel commitLink = new LinkPanel("commit", null, getShortObjectId(entry.commitId), CommitPage.class, newCommitParameter(entry.commitId)); WicketUtils.setHtmlTooltip(commitLink, MessageFormat.format("{0}, {1}", entry.author, df.format(entry.when))); item.add(commitLink); WicketUtils.setCssStyle(item, "border-top: 1px solid #ddd;"); showInitials = true; } } else { if (showInitials) { showInitials = false; // show author initials item.add(new Label("commit", getInitials(entry.author))); } else { // hide the commit link until the next block item.add(new Label("commit").setVisible(false)); } } // line number item.add(new Label("line", "" + entry.lineNumber)); // line content String color; switch (activeBlameType) { case AGE: color = colorMap.get(entry.when); break; case AUTHOR: color = colorMap.get(entry.author); break; default: color = colorMap.get(entry.commitId); break; } Component data = new Label("data", StringUtils.escapeForHtml(entry.data, true)).setEscapeModelStrings(false); data.add(new SimpleAttributeModifier("style", "background-color: " + color + ";")); item.add(data); } }; add(blameView); }
public BlamePage(PageParameters params) { super(params); final String blobPath = WicketUtils.getPath(params); final String blameTypeParam = params.getString("blametype", BlameType.COMMIT.toString()); final BlameType activeBlameType = BlameType.get(blameTypeParam); RevCommit commit = getCommit(); add(new BookmarkablePageLink<Void>("blobLink", BlobPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); add(new BookmarkablePageLink<Void>("commitLink", CommitPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); add(new BookmarkablePageLink<Void>("commitDiffLink", CommitDiffPage.class, WicketUtils.newObjectParameter(repositoryName, objectId))); // blame page links add(new BookmarkablePageLink<Void>("headLink", BlamePage.class, WicketUtils.newPathParameter(repositoryName, Constants.HEAD, blobPath))); add(new BookmarkablePageLink<Void>("historyLink", HistoryPage.class, WicketUtils.newPathParameter(repositoryName, objectId, blobPath))); // "Blame by" links for (BlameType type : BlameType.values()) { String typeString = type.toString(); PageParameters blameTypePageParam = WicketUtils.newBlameTypeParameter(repositoryName, commit.getName(), WicketUtils.getPath(params), typeString); String blameByLinkText = "blameBy" + Character.toUpperCase(typeString.charAt(0)) + typeString.substring(1) + "Link"; BookmarkablePageLink<Void> blameByPageLink = new BookmarkablePageLink<Void>(blameByLinkText, BlamePage.class, blameTypePageParam); if (activeBlameType == type) { blameByPageLink.add(new SimpleAttributeModifier("style", "font-weight:bold;")); } add(blameByPageLink); } add(new CommitHeaderPanel("commitHeader", repositoryName, commit)); add(new PathBreadcrumbsPanel("breadcrumbs", repositoryName, blobPath, objectId)); String format = app().settings().getString(Keys.web.datetimestampLongFormat, "EEEE, MMMM d, yyyy HH:mm Z"); final DateFormat df = new SimpleDateFormat(format); df.setTimeZone(getTimeZone()); PathModel pathModel = null; List<PathModel> paths = JGitUtils.getFilesInPath(getRepository(), StringUtils.getRootPath(blobPath), commit); for (PathModel path : paths) { if (path.path.equals(blobPath)) { pathModel = path; break; } } if (pathModel == null) { final String notFound = MessageFormat.format("Blame page failed to find {0} in {1} @ {2}", blobPath, repositoryName, objectId); logger.error(notFound); add(new Label("annotation").setVisible(false)); add(new Label("missingBlob", missingBlob(blobPath, commit)).setEscapeModelStrings(false)); return; } add(new Label("missingBlob").setVisible(false)); List<AnnotatedLine> lines = DiffUtils.blame(getRepository(), blobPath, objectId); final Map<?, String> colorMap = initializeColors(activeBlameType, lines); ListDataProvider<AnnotatedLine> blameDp = new ListDataProvider<AnnotatedLine>(lines); DataView<AnnotatedLine> blameView = new DataView<AnnotatedLine>("annotation", blameDp) { private static final long serialVersionUID = 1L; private String lastCommitId = ""; private boolean showInitials = true; private String zeroId = ObjectId.zeroId().getName(); @Override public void populateItem(final Item<AnnotatedLine> item) { final AnnotatedLine entry = item.getModelObject(); // commit id and author if (!lastCommitId.equals(entry.commitId)) { lastCommitId = entry.commitId; if (zeroId.equals(entry.commitId)) { // unknown commit item.add(new Label("commit", "<?>")); showInitials = false; } else { // show the link for first line LinkPanel commitLink = new LinkPanel("commit", null, getShortObjectId(entry.commitId), CommitPage.class, newCommitParameter(entry.commitId)); WicketUtils.setHtmlTooltip(commitLink, MessageFormat.format("{0}, {1}", entry.author, df.format(entry.when))); item.add(commitLink); WicketUtils.setCssStyle(item, "border-top: 1px solid #ddd;"); showInitials = true; } } else { if (showInitials) { showInitials = false; // show author initials item.add(new Label("commit", getInitials(entry.author))); } else { // hide the commit link until the next block item.add(new Label("commit").setVisible(false)); } } // line number item.add(new Label("line", "" + entry.lineNumber)); // line content String color; switch (activeBlameType) { case AGE: color = colorMap.get(entry.when); break; case AUTHOR: color = colorMap.get(entry.author); break; default: color = colorMap.get(entry.commitId); break; } Component data = new Label("data", StringUtils.escapeForHtml(entry.data, true)).setEscapeModelStrings(false); data.add(new SimpleAttributeModifier("style", "background-color: " + color + ";")); item.add(data); } }; add(blameView); }
diff --git a/samples/tinycloud/org.kevoree.modeling.genetic.tinycloud.sample/src/main/java/org/kevoree/modeling/genetic/tinycloud/SampleRunnerEpsilonMOEAD_Darwin.java b/samples/tinycloud/org.kevoree.modeling.genetic.tinycloud.sample/src/main/java/org/kevoree/modeling/genetic/tinycloud/SampleRunnerEpsilonMOEAD_Darwin.java index 5d72f0a..0e87707 100644 --- a/samples/tinycloud/org.kevoree.modeling.genetic.tinycloud.sample/src/main/java/org/kevoree/modeling/genetic/tinycloud/SampleRunnerEpsilonMOEAD_Darwin.java +++ b/samples/tinycloud/org.kevoree.modeling.genetic.tinycloud.sample/src/main/java/org/kevoree/modeling/genetic/tinycloud/SampleRunnerEpsilonMOEAD_Darwin.java @@ -1,67 +1,67 @@ package org.kevoree.modeling.genetic.tinycloud; import org.cloud.Cloud; import org.kevoree.modeling.genetic.tinycloud.fitnesses.CloudAdaptationCostFitness; import org.kevoree.modeling.genetic.tinycloud.fitnesses.CloudConsumptionFitness; import org.kevoree.modeling.genetic.tinycloud.fitnesses.CloudRedondencyFitness; import org.kevoree.modeling.genetic.tinycloud.mutators.AddNodeMutator; import org.kevoree.modeling.genetic.tinycloud.mutators.RemoveNodeMutator; import org.kevoree.modeling.optimization.api.metric.ParetoMetrics; import org.kevoree.modeling.optimization.api.mutation.MutationSelectionStrategy; import org.kevoree.modeling.optimization.api.solution.Solution; import org.kevoree.modeling.optimization.engine.genetic.GeneticAlgorithm; import org.kevoree.modeling.optimization.engine.genetic.GeneticEngine; import org.kevoree.modeling.optimization.executionmodel.ExecutionModel; import org.kevoree.modeling.optimization.framework.SolutionPrinter; import org.kevoree.modeling.optimization.web.Server; import java.util.List; /** * Created with IntelliJ IDEA. * User: duke * Date: 07/08/13 * Time: 16:00 */ public class SampleRunnerEpsilonMOEAD_Darwin { public static void main(String[] args) throws Exception { GeneticEngine<Cloud> engine = new GeneticEngine<Cloud>(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.RANDOM); engine.addOperator(new AddNodeMutator()); engine.addOperator(new RemoveNodeMutator()); engine.addFitnessFuntion(new CloudConsumptionFitness()); engine.addFitnessFuntion(new CloudRedondencyFitness()); //engine.addFitnessFuntion(new CloudAdaptationCostFitness()); - engine.setMaxGeneration(200); - engine.setPopulationFactory(new DefaultCloudPopulationFactory().setSize(5)); + engine.setMaxGeneration(300); + engine.setPopulationFactory(new DefaultCloudPopulationFactory().setSize(20)); engine.setAlgorithm(GeneticAlgorithm.HypervolumeNSGAII); //engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); //engine.addParetoMetric(ParetoMetrics.MEAN); engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); List<Solution<Cloud>> result = engine.solve(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.SPUTNIK_CASTE); //DARWIN does not exist, changed tp Sputnik_caste by Assaad engine.solve(); //engine.solve(); ExecutionModel model = engine.getExecutionModel(); Server.instance$.serveExecutionModel(model); for (Solution sol : result) { SolutionPrinter.instance$.print(sol, System.out); } System.out.println(engine.getMutationSelector().toString()); } }
true
true
public static void main(String[] args) throws Exception { GeneticEngine<Cloud> engine = new GeneticEngine<Cloud>(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.RANDOM); engine.addOperator(new AddNodeMutator()); engine.addOperator(new RemoveNodeMutator()); engine.addFitnessFuntion(new CloudConsumptionFitness()); engine.addFitnessFuntion(new CloudRedondencyFitness()); //engine.addFitnessFuntion(new CloudAdaptationCostFitness()); engine.setMaxGeneration(200); engine.setPopulationFactory(new DefaultCloudPopulationFactory().setSize(5)); engine.setAlgorithm(GeneticAlgorithm.HypervolumeNSGAII); //engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); //engine.addParetoMetric(ParetoMetrics.MEAN); engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); List<Solution<Cloud>> result = engine.solve(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.SPUTNIK_CASTE); //DARWIN does not exist, changed tp Sputnik_caste by Assaad engine.solve(); //engine.solve(); ExecutionModel model = engine.getExecutionModel(); Server.instance$.serveExecutionModel(model); for (Solution sol : result) { SolutionPrinter.instance$.print(sol, System.out); } System.out.println(engine.getMutationSelector().toString()); }
public static void main(String[] args) throws Exception { GeneticEngine<Cloud> engine = new GeneticEngine<Cloud>(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.RANDOM); engine.addOperator(new AddNodeMutator()); engine.addOperator(new RemoveNodeMutator()); engine.addFitnessFuntion(new CloudConsumptionFitness()); engine.addFitnessFuntion(new CloudRedondencyFitness()); //engine.addFitnessFuntion(new CloudAdaptationCostFitness()); engine.setMaxGeneration(300); engine.setPopulationFactory(new DefaultCloudPopulationFactory().setSize(20)); engine.setAlgorithm(GeneticAlgorithm.HypervolumeNSGAII); //engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); //engine.addParetoMetric(ParetoMetrics.MEAN); engine.addParetoMetric(ParetoMetrics.HYPERVOLUME); List<Solution<Cloud>> result = engine.solve(); engine.setMutationSelectionStrategy(MutationSelectionStrategy.SPUTNIK_CASTE); //DARWIN does not exist, changed tp Sputnik_caste by Assaad engine.solve(); //engine.solve(); ExecutionModel model = engine.getExecutionModel(); Server.instance$.serveExecutionModel(model); for (Solution sol : result) { SolutionPrinter.instance$.print(sol, System.out); } System.out.println(engine.getMutationSelector().toString()); }
diff --git a/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java b/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java index a50e2bc..e13fcdc 100644 --- a/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java +++ b/stripes/src/net/sourceforge/stripes/tag/InputOptionTag.java @@ -1,157 +1,157 @@ /* Copyright 2005-2006 Tim Fennell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.tag; import net.sourceforge.stripes.exception.StripesJspException; import net.sourceforge.stripes.util.HtmlUtil; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTag; import java.io.IOException; /** * <p>Generates an {@literal <option value="foo">Fooey</option>} HTML tag. Coordinates with an * enclosing select tag to determine it's state (i.e. whether or not it is selected.) As a result * some of the logic regarding state repopulation is a bit complex.</p> * * <p>Since options can have only a single value per option the value attribute of the tag * must be a scalar, which will be converted into a String using a Formatter if an * appropriate one can be found, otherwise the toString() method will be invoked. The presence of * a "selected" attribute is used as an indication that this option believes it should be selected * by default - the value (as opposed to the presence) of the selected attribute is never used....</p> * * <p>The option tag delegates to its enclosing select tag to determine whether or not it should * be selected. See the {@link InputSelectTag "select tag"} for documentation on how it * determines selection status. If the select tag <em>has no opinion</em> on selection state * (note that this is not the same as select tag deeming the option should not be selected) then * the presence of the selected attribute (or lack thereof) is used to turn selection on or off.</p> * * <p>If the option has a body then the String value of that body will be used to generate the * body of the generated HTML option. If the body is empty or not present then the label attribute * will be written into the body of the tag.</p> * * @author Tim Fennell */ public class InputOptionTag extends InputTagSupport implements BodyTag { private String selected; private String label; private Object value; /** Sets the value of this option. */ public void setValue(Object value) { this.value = value; } /** Returns the value of the option as set with setValue(). */ public Object getValue() { return this.value; } /** Sets the label that will be used as the option body if no body is supplied. */ public void setLabel(String label) { this.label = label; } /** Returns the value set with setLabel(). */ public String getLabel() { return this.label; } /** Sets whether or not this option believes it should be selected by default. */ public void setSelected(String selected) { this.selected = selected; } /** Returns the value set with setSelected(). */ public String getSelected() { return this.selected; } /** * Does nothing. * @return EVAL_BODY_BUFFERED in all cases. */ @Override public int doStartInputTag() throws JspException { return EVAL_BODY_BUFFERED; } /** Does nothing. */ public void doInitBody() throws JspException { } /** * Does nothing. * @return SKIP_BODY in all cases. */ public int doAfterBody() throws JspException { return SKIP_BODY; } /** * Locates the option's parent select tag, determines selection state and then writes out * an option tag with an appropriate body. * * @return EVAL_PAGE in all cases. * @throws JspException if the option is not contained inside an InputSelectTag or output * cannot be written. */ @Override public int doEndInputTag() throws JspException { // Find our mandatory enclosing select tag InputSelectTag selectTag = getParentTag(InputSelectTag.class); if (selectTag == null) { throw new StripesJspException ("Option tags must always be contained inside a select tag."); } // Decide if the label will come from the body of the option, of the label attr String actualLabel = getBodyContentAsString(); if (actualLabel == null) { - actualLabel = this.label; + actualLabel = HtmlUtil.encode(this.label); } // If no explicit value attribute set, use the tag label as the value Object actualValue; if (this.value == null) { actualValue = actualLabel; } else { actualValue = this.value; } getAttributes().put("value", format(actualValue)); // Determine if the option should be selected if (selectTag.isOptionSelected(actualValue, (this.selected != null))) { getAttributes().put("selected", "selected"); } // And finally write the tag out to the page try { writeOpenTag(getPageContext().getOut(), "option"); if (actualLabel != null) { - getPageContext().getOut().write(HtmlUtil.encode(actualLabel)); + getPageContext().getOut().write(actualLabel); } writeCloseTag(getPageContext().getOut(), "option"); // Clean out the attributes we modified getAttributes().remove("selected"); getAttributes().remove("value"); } catch (IOException ioe) { throw new JspException("IOException in InputOptionTag.doEndTag().", ioe); } return EVAL_PAGE; } /** * Overridden to make sure that options do not try and register themselves with * the form tag. This is done because options are not standalone input tags, but * always part of a select tag (which gets registered). */ @Override protected void registerWithParentForm() throws StripesJspException { // Do nothing, options are not standalone fields and should not register } }
false
true
public int doEndInputTag() throws JspException { // Find our mandatory enclosing select tag InputSelectTag selectTag = getParentTag(InputSelectTag.class); if (selectTag == null) { throw new StripesJspException ("Option tags must always be contained inside a select tag."); } // Decide if the label will come from the body of the option, of the label attr String actualLabel = getBodyContentAsString(); if (actualLabel == null) { actualLabel = this.label; } // If no explicit value attribute set, use the tag label as the value Object actualValue; if (this.value == null) { actualValue = actualLabel; } else { actualValue = this.value; } getAttributes().put("value", format(actualValue)); // Determine if the option should be selected if (selectTag.isOptionSelected(actualValue, (this.selected != null))) { getAttributes().put("selected", "selected"); } // And finally write the tag out to the page try { writeOpenTag(getPageContext().getOut(), "option"); if (actualLabel != null) { getPageContext().getOut().write(HtmlUtil.encode(actualLabel)); } writeCloseTag(getPageContext().getOut(), "option"); // Clean out the attributes we modified getAttributes().remove("selected"); getAttributes().remove("value"); } catch (IOException ioe) { throw new JspException("IOException in InputOptionTag.doEndTag().", ioe); } return EVAL_PAGE; }
public int doEndInputTag() throws JspException { // Find our mandatory enclosing select tag InputSelectTag selectTag = getParentTag(InputSelectTag.class); if (selectTag == null) { throw new StripesJspException ("Option tags must always be contained inside a select tag."); } // Decide if the label will come from the body of the option, of the label attr String actualLabel = getBodyContentAsString(); if (actualLabel == null) { actualLabel = HtmlUtil.encode(this.label); } // If no explicit value attribute set, use the tag label as the value Object actualValue; if (this.value == null) { actualValue = actualLabel; } else { actualValue = this.value; } getAttributes().put("value", format(actualValue)); // Determine if the option should be selected if (selectTag.isOptionSelected(actualValue, (this.selected != null))) { getAttributes().put("selected", "selected"); } // And finally write the tag out to the page try { writeOpenTag(getPageContext().getOut(), "option"); if (actualLabel != null) { getPageContext().getOut().write(actualLabel); } writeCloseTag(getPageContext().getOut(), "option"); // Clean out the attributes we modified getAttributes().remove("selected"); getAttributes().remove("value"); } catch (IOException ioe) { throw new JspException("IOException in InputOptionTag.doEndTag().", ioe); } return EVAL_PAGE; }
diff --git a/Java_CCN/com/parc/ccn/library/profiles/VersioningProfile.java b/Java_CCN/com/parc/ccn/library/profiles/VersioningProfile.java index f03343478..eb80063f2 100644 --- a/Java_CCN/com/parc/ccn/library/profiles/VersioningProfile.java +++ b/Java_CCN/com/parc/ccn/library/profiles/VersioningProfile.java @@ -1,529 +1,529 @@ package com.parc.ccn.library.profiles; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidParameterException; import java.sql.Timestamp; import java.util.ArrayList; import com.parc.ccn.Library; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.ContentObject; import com.parc.ccn.data.query.BloomFilter; import com.parc.ccn.data.query.ExcludeAny; import com.parc.ccn.data.query.ExcludeComponent; import com.parc.ccn.data.query.ExcludeFilter; import com.parc.ccn.data.security.ContentVerifier; import com.parc.ccn.data.security.PublisherPublicKeyDigest; import com.parc.ccn.data.security.SignedInfo; import com.parc.ccn.data.util.DataUtils; import com.parc.ccn.data.util.DataUtils.Tuple; import com.parc.ccn.library.CCNLibrary; import com.parc.ccn.library.io.CCNVersionedInputStream; /** * Versions, when present, usually occupy the penultimate component of the CCN name, * not counting the digest component. A name may actually incorporate multiple * versions, where the rightmost version is the version of "this" object, if it * has one, and previous (parent) versions are the versions of the objects of * which this object is a part. The most common location of a version, if present, * is in the next to last component of the name, where the last component is a * segment number (which is generally always present; versions themselves are * optional). More complicated segmentation profiles occur, where a versioned * object has components that are structured and named in ways other than segments -- * and may themselves have individual versions (e.g. if the components of such * a composite object are written as CCNNetworkObjects and automatically pick * up an (unnecessary) version in their own right). Versioning operations therefore * take context from their caller about where to expect to find a version, * and attempt to ignore other versions in the name. * * Versions may be chosen based on time. * The first byte of the version component is 0xFD. The remaining bytes are a * big-endian binary number. If based on time they are expressed in units of * 2**(-12) seconds since the start of Unix time, using the minimum number of * bytes. The time portion will thus take 48 bits until quite a few centuries * from now (Sun, 20 Aug 4147 07:32:16 GMT). With 12 bits of precision, it allows * for sub-millisecond resolution. The client generating the version stamp * should try to avoid using a stamp earlier than (or the same as) any * version of the file, to the extent that it knows about it. It should * also avoid generating stamps that are unreasonably far in the future. */ public class VersioningProfile implements CCNProfile { public static final byte VERSION_MARKER = (byte)0xFD; public static final byte [] FIRST_VERSION_MARKER = new byte []{VERSION_MARKER}; public static final byte FF = (byte) 0xFF; public static final byte OO = (byte) 0x00; /** * Add a version field to a ContentName. * @return ContentName with a version appended. Does not affect previous versions. */ public static ContentName addVersion(ContentName name, long version) { // Need a minimum-bytes big-endian representation of version. byte [] vcomp = null; if (0 == version) { vcomp = FIRST_VERSION_MARKER; } else { byte [] varr = BigInteger.valueOf(version).toByteArray(); vcomp = new byte[varr.length + 1]; vcomp[0] = VERSION_MARKER; System.arraycopy(varr, 0, vcomp, 1, varr.length); } return new ContentName(name, vcomp); } /** * Converts a timestamp into a fixed point representation, with 12 bits in the fractional * component, and adds this to the ContentName as a version field. The timestamp is rounded * to the nearest value in the fixed point representation. * <p> * This allows versions to be recorded as a timestamp with a 1/4096 second accuracy. * @see #addVersion(ContentName, long) */ public static ContentName addVersion(ContentName name, Timestamp version) { if (null == version) throw new IllegalArgumentException("Version cannot be null!"); return addVersion(name, DataUtils.timestampToBinaryTime12AsLong(version)); } /** * Add a version field based on the current time, accurate to 1/4096 second. * @see #addVersion(ContentName, Timestamp) */ public static ContentName addVersion(ContentName name) { return addVersion(name, SignedInfo.now()); } /** * Adds a version to a ContentName; if there is a terminal version there already, * first removes it. */ public static ContentName updateVersion(ContentName name, long version) { return addVersion(cutTerminalVersion(name).first(), version); } /** * Adds a version to a ContentName; if there is a terminal version there already, * first removes it. */ public static ContentName updateVersion(ContentName name, Timestamp version) { return addVersion(cutTerminalVersion(name).first(), version); } /** * Add updates the version field based on the current time, accurate to 1/4096 second. * @see #updateVersion(ContentName, Timestamp) */ public static ContentName updateVersion(ContentName name) { return updateVersion(name, SignedInfo.now()); } /** * Finds the last component that looks like a version in name. * @param name * @return the index of the last version component in the name, or -1 if there is no version * component in the name */ public static int findLastVersionComponent(ContentName name) { int i = name.count(); for (;i >= 0; i--) if (isVersionComponent(name.component(i))) return i; return -1; } /** * Checks to see if this name has a validly formatted version field anywhere in it. */ public static boolean containsVersion(ContentName name) { return findLastVersionComponent(name) != -1; } /** * Checks to see if this name has a validly formatted version field either in final * component or in next to last component with final component being a segment marker. */ public static boolean hasTerminalVersion(ContentName name) { if ((name.count() > 0) && ((isVersionComponent(name.lastComponent()) || ((name.count() > 1) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2)))))) { return true; } return false; } /** * Check a name component to see if it is a valid version field */ public static boolean isVersionComponent(byte [] nameComponent) { return (null != nameComponent) && (0 != nameComponent.length) && (VERSION_MARKER == nameComponent[0]) && ((nameComponent.length == 1) || (nameComponent[1] != 0)); } public static boolean isBaseVersionComponent(byte [] nameComponent) { return (isVersionComponent(nameComponent) && (1 == nameComponent.length)); } /** * Remove a terminal version marker (one that is either the last component of name, or * the next to last component of name followed by a segment marker) if one exists, otherwise * return name as it was passed in. * @param name * @return */ public static Tuple<ContentName, byte[]> cutTerminalVersion(ContentName name) { if (name.count() > 0) { if (isVersionComponent(name.lastComponent())) { return new Tuple<ContentName, byte []>(name.parent(), name.lastComponent()); } else if ((name.count() > 2) && SegmentationProfile.isSegment(name) && isVersionComponent(name.component(name.count()-2))) { return new Tuple<ContentName, byte []>(name.cut(name.count()-2), name.component(name.count()-2)); } } return new Tuple<ContentName, byte []>(name, null); } /** * Take a name which may have one or more version components in it, * and strips the last one and all following components. If no version components * present, returns the name as handed in. */ public static ContentName cutLastVersion(ContentName name) { int offset = findLastVersionComponent(name); return (offset == -1) ? name : new ContentName(offset, name.components()); } /** * Function to get the version field as a long. Starts from the end and checks each name component for the version marker. * @param name * @return long * @throws VersionMissingException */ public static long getLastVersionAsLong(ContentName name) throws VersionMissingException { int i = findLastVersionComponent(name); if (i == -1) throw new VersionMissingException(); return getVersionComponentAsLong(name.component(i)); } public static long getVersionComponentAsLong(byte [] versionComponent) { byte [] versionData = new byte[versionComponent.length - 1]; System.arraycopy(versionComponent, 1, versionData, 0, versionComponent.length - 1); if (versionData.length == 0) return 0; return new BigInteger(versionData).longValue(); } public static Timestamp getVersionComponentAsTimestamp(byte [] versionComponent) { return versionLongToTimestamp(getVersionComponentAsLong(versionComponent)); } /** * Extract the version from this name as a Timestamp. * @throws VersionMissingException */ public static Timestamp getLastVersionAsTimestamp(ContentName name) throws VersionMissingException { long time = getLastVersionAsLong(name); return DataUtils.binaryTime12ToTimestamp(time); } /** * Returns null if no version, otherwise returns the last version in the name. * @param name * @return */ public static Timestamp getLastVersionAsTimestampIfVersioned(ContentName name) { int versionComponent = findLastVersionComponent(name); if (versionComponent < 0) return null; return getVersionComponentAsTimestamp(name.component(versionComponent)); } public static Timestamp getTerminalVersionAsTimestampIfVersioned(ContentName name) { if (!hasTerminalVersion(name)) return null; int versionComponent = findLastVersionComponent(name); if (versionComponent < 0) return null; return getVersionComponentAsTimestamp(name.component(versionComponent)); } public static Timestamp versionLongToTimestamp(long version) { return DataUtils.binaryTime12ToTimestamp(version); } /** * Control whether versions start at 0 or 1. * @return */ public static final int baseVersion() { return 0; } /** * Compares terminal version (versions at the end of, or followed by only a segment * marker) of a name to a given timestamp. * @param left * @param right * @return */ public static int compareVersions( Timestamp left, ContentName right) { if (!hasTerminalVersion(right)) { throw new IllegalArgumentException("Both names to compare must be versioned!"); } try { return left.compareTo(getLastVersionAsTimestamp(right)); } catch (VersionMissingException e) { throw new IllegalArgumentException("Name that isVersioned returns true for throws VersionMissingException!: " + right); } } public static int compareVersionComponents( byte [] left, byte [] right) throws VersionMissingException { // Propagate correct exception to callers. if ((null == left) || (null == right)) throw new VersionMissingException("Must compare two versions!"); // DKS TODO -- should be able to just compare byte arrays, but would have to check version return getVersionComponentAsTimestamp(left).compareTo(getVersionComponentAsTimestamp(right)); } /** * See if version is a version of parent (not commutative). * @return */ public static boolean isVersionOf(ContentName version, ContentName parent) { Tuple<ContentName, byte []>versionParts = cutTerminalVersion(version); if (!parent.equals(versionParts.first())) { return false; // not versions of the same thing } if (null == versionParts.second()) return false; // version isn't a version return true; } /** * This compares two names, with terminal versions, and determines whether one is later than the other. * @param laterVersion * @param earlierVersion * @return * @throws VersionMissingException */ public static boolean isLaterVersionOf(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException { // TODO -- remove temporary warning Library.logger().warning("SEMANTICS CHANGED: if experiencing unexpected behavior, check to see if you want to call isLaterVerisionOf or startsWithLaterVersionOf"); Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion); Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion); if (!laterVersionParts.first().equals(earlierVersionParts.first())) { return false; // not versions of the same thing } return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second()) > 0); } /** * Finds out if you have a versioned name, and a ContentObject that might have a versioned name which is * a later version of the given name, even if that CO name might not refer to a segment of the original name. * For example, given a name /parc/foo.txt/<version1> or /parc/foo.txt/<version1>/<segment> * and /parc/foo.txt/<version2>/<stuff>, return true, whether <stuff> is a segment marker, a whole * bunch of repo write information, or whatever. * @param newName Will check to see if this name begins with something which is a later version of previousVersion. * @param previousVersion The name to compare to, must have a terminal version or be unversioned. * @return */ public static boolean startsWithLaterVersionOf(ContentName newName, ContentName previousVersion) { // If no version, treat whole name as prefix and any version as a later version. Tuple<ContentName, byte []>previousVersionParts = cutTerminalVersion(previousVersion); if (!previousVersionParts.first().isPrefixOf(newName)) return false; if (null == previousVersionParts.second()) { return ((newName.count() > previousVersionParts.first().count()) && VersioningProfile.isVersionComponent(newName.component(previousVersionParts.first().count()))); } try { return (compareVersionComponents(newName.component(previousVersionParts.first().count()), previousVersionParts.second()) > 0); } catch (VersionMissingException e) { return false; // newName doesn't have to have a version there... } } public static int compareTerminalVersions(ContentName laterVersion, ContentName earlierVersion) throws VersionMissingException { Tuple<ContentName, byte []>earlierVersionParts = cutTerminalVersion(earlierVersion); Tuple<ContentName, byte []>laterVersionParts = cutTerminalVersion(laterVersion); if (!laterVersionParts.first().equals(earlierVersionParts.first())) { throw new IllegalArgumentException("Names not versions of the same name!"); } return (compareVersionComponents(laterVersionParts.second(), earlierVersionParts.second())); } /** * Builds an Exclude filter that excludes components before or @ start, and components after * the last valid version. * @param startingVersionComponent The latest version component we know about. Can be null or * VersioningProfile.isBaseVersionComponent() == true to indicate that we want to start * from 0 (we don't have a known version we're trying to update). This exclude filter will * find versions *after* the version represented in startingVersionComponent. * @return An exclude filter. * @throws InvalidParameterException */ public static ExcludeFilter acceptVersions(byte [] startingVersionComponent) { byte [] start = null; // initially exclude name components just before the first version, whether that is the // 0th version or the version passed in if ((null == startingVersionComponent) || VersioningProfile.isBaseVersionComponent(startingVersionComponent)) { start = new byte [] { VersioningProfile.VERSION_MARKER, VersioningProfile.OO, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF, VersioningProfile.FF }; } else { start = startingVersionComponent; } ArrayList<ExcludeFilter.Element> ees = new ArrayList<ExcludeFilter.Element>(); ees.add(new ExcludeAny()); ees.add(new ExcludeComponent(start)); ees.add(new ExcludeComponent(new byte [] { VERSION_MARKER+1, OO, OO, OO, OO, OO, OO } )); ees.add(new ExcludeAny()); return new ExcludeFilter(ees); } /** * Active methods. Want to provide profile-specific methods that: * - find the latest version without regard to what is below it * - if no version given, gets the latest version * - if a starting version given, gets the latest version available *after* that version; * will time out if no such newer version exists * Returns a content object, which may or may not be a segment of the latest version, but the * latest version information is available from its name. * * - find the first segment of the latest version of a name * - if no version given, gets the first segment of the latest version * - if a starting version given, gets the latest version available *after* that version or times out * Will ensure that what it returns is a segment of a version of that object. * * - generate an interest designed to find the first segment of the latest version * of a name, in the above form; caller is responsible for checking and re-issuing */ /** * Gets the latest version using a single interest/response. There may be newer versions available * if you ask again passing in the version found (i.e. each response will be the latest version * a given responder knows about. Further queries will move past that responder to other responders, * who may have newer information.) * * @param name If the name ends in a version then this method explicitly looks for a newer version * than that, and will time out if no such later version exists. If the name does not end in a * version then this call just looks for the latest version. * @param publisher Currently unused, will limit query to a specific publisher. * @param timeout * @return A ContentObject with the latest version, or null if the query timed out. Note - the content * returned could be any name under this new version - by default it will get the leftmost item, * but right now that is generally a repo start write, not a segment. Changing the marker values * used will fix that. * TODO fix marker values * @throws IOException * DKS TODO -- doesn't use publisher * DKS TODO -- specify separately latest version known? */ public static ContentObject getLatestVersionAfter(ContentName name, PublisherPublicKeyDigest publisher, long timeout, CCNLibrary library) throws IOException { if (hasTerminalVersion(name)) { // Has a version. Make sure it doesn't have a segment; find a version after this one. name = SegmentationProfile.segmentRoot(name); } else { // Doesn't have a version. Add the "0" version, so we are finding any version after that. ContentName firstVersionName = addVersion(name, baseVersion()); name = firstVersionName; } byte [] versionComponent = name.lastComponent(); // initially exclude name components just before the first version, whether that is the // 0th version or the version passed in while (true) { ContentObject co = library.getLatest(name, acceptVersions(versionComponent), timeout); if (co == null) { Library.logger().info("Null returned from getLatest for name: " + name); return null; } // What we get should be a block representing a later version of name. It might // be an actual segment of a versioned object, but it might also be an ancillary // object - e.g. a repo message -- which starts with a particular version of name. if (startsWithLaterVersionOf(co.name(), name)) { // we got a valid version! Library.logger().info("Got latest version: " + co.name()); return co; } else { Library.logger().info("Rejected potential candidate version: " + co.name() + " not a later version of " + name); } versionComponent = co.name().component(name.count()-1); } } /** * DKS fix this one up to restrict length of valid answer, and check for segments. Don't * use above method to do this. * This method returns * @param desiredName The name of the object we are looking for the first segment of. * If (VersioningProfile.hasTerminalVersion(desiredName) == false), will get latest version it can * find of desiredName. * If desiredName has a terminal version, will try to find the first block of content whose * version is *after* desiredName (i.e. getLatestVersion starting from desiredName). * @param startingSegmentNumber The desired block number, or SegmentationProfile.baseSegment if null. * @param timeout * @param verifier Cannot be null. * @return The first block of a stream with a version later than desiredName, or null if timeout is reached. * @throws IOException */ public static ContentObject getFirstBlockOfLatestVersionAfter(ContentName startingVersion, Long startingSegmentNumber, long timeout, ContentVerifier verifier, CCNLibrary library) throws IOException { Library.logger().info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion); int prefixLength = hasTerminalVersion(startingVersion) ? startingVersion.count() : startingVersion.count() + 1; ContentObject result = getLatestVersionAfter(startingVersion, null, timeout, library); if (null != result){ Library.logger().info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName()); // Now need to verify the block we got - if (!verifier.verifySegment(result)) { + if (!verifier.verify(result)) { return null; } // Now we know the version. Did we luck out and get first block? if (CCNVersionedInputStream.isFirstSegment(startingVersion, result, startingSegmentNumber)) { Library.logger().info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name()); return result; } // This isn't the first block. Might be simply a later (cached) segment, or might be something // crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion // is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock // above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got, // which works fine only if we have the wrong segment rather than some other beast entirely (like metadata). // So chop off the new name just after the (first) version, and use that. If getLatestVersion is working // right, that should be the right thing. startingVersion = result.name().cut(prefixLength); Library.logger().info("getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion); return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block. } else { Library.logger().info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion); } return result; } /** * This is a temporary function to allow use of this functionality, which will * get refactored and moved elsewhere in a cleaner form. * @param startingVersion * @param publisher * @param timeout * @param library * @return * @throws IOException */ public static ContentObject getFirstBlockOfLatestVersion(ContentName startingVersion, PublisherPublicKeyDigest publisher, long timeout, CCNLibrary library) throws IOException { return getFirstBlockOfLatestVersionAfter(startingVersion, null, timeout, new ContentObject.SimpleVerifier(publisher), library); } }
true
true
public static ContentObject getFirstBlockOfLatestVersionAfter(ContentName startingVersion, Long startingSegmentNumber, long timeout, ContentVerifier verifier, CCNLibrary library) throws IOException { Library.logger().info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion); int prefixLength = hasTerminalVersion(startingVersion) ? startingVersion.count() : startingVersion.count() + 1; ContentObject result = getLatestVersionAfter(startingVersion, null, timeout, library); if (null != result){ Library.logger().info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName()); // Now need to verify the block we got if (!verifier.verifySegment(result)) { return null; } // Now we know the version. Did we luck out and get first block? if (CCNVersionedInputStream.isFirstSegment(startingVersion, result, startingSegmentNumber)) { Library.logger().info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name()); return result; } // This isn't the first block. Might be simply a later (cached) segment, or might be something // crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion // is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock // above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got, // which works fine only if we have the wrong segment rather than some other beast entirely (like metadata). // So chop off the new name just after the (first) version, and use that. If getLatestVersion is working // right, that should be the right thing. startingVersion = result.name().cut(prefixLength); Library.logger().info("getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion); return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block. } else { Library.logger().info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion); } return result; }
public static ContentObject getFirstBlockOfLatestVersionAfter(ContentName startingVersion, Long startingSegmentNumber, long timeout, ContentVerifier verifier, CCNLibrary library) throws IOException { Library.logger().info("getFirstBlockOfLatestVersion: getting version later than " + startingVersion); int prefixLength = hasTerminalVersion(startingVersion) ? startingVersion.count() : startingVersion.count() + 1; ContentObject result = getLatestVersionAfter(startingVersion, null, timeout, library); if (null != result){ Library.logger().info("getFirstBlockOfLatestVersion: retrieved latest version object " + result.name() + " type: " + result.signedInfo().getTypeName()); // Now need to verify the block we got if (!verifier.verify(result)) { return null; } // Now we know the version. Did we luck out and get first block? if (CCNVersionedInputStream.isFirstSegment(startingVersion, result, startingSegmentNumber)) { Library.logger().info("getFirstBlockOfLatestVersion: got first block on first try: " + result.name()); return result; } // This isn't the first block. Might be simply a later (cached) segment, or might be something // crazy like a repo_start_write. So what we want is to get the version of this new block -- if getLatestVersion // is doing its job, we now know the version we want (if we already knew that, we called super.getFirstBlock // above. If we get here, _baseName isn't versioned yet. So instead of taking segmentRoot of what we got, // which works fine only if we have the wrong segment rather than some other beast entirely (like metadata). // So chop off the new name just after the (first) version, and use that. If getLatestVersion is working // right, that should be the right thing. startingVersion = result.name().cut(prefixLength); Library.logger().info("getFirstBlockOfLatestVersion: Have version information, now querying first segment of " + startingVersion); return SegmentationProfile.getSegment(startingVersion, startingSegmentNumber, null, timeout, verifier, library); // now that we have the latest version, go back for the first block. } else { Library.logger().info("getFirstBlockOfLatestVersion: no block available for later version of " + startingVersion); } return result; }
diff --git a/src/main/java/com/socialsite/BasePage.java b/src/main/java/com/socialsite/BasePage.java index 7af3567..e30ef03 100644 --- a/src/main/java/com/socialsite/BasePage.java +++ b/src/main/java/com/socialsite/BasePage.java @@ -1,116 +1,116 @@ /** * Copyright SocialSite (C) 2009 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.socialsite; import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.IHeaderContributor; import org.apache.wicket.markup.html.IHeaderResponse; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.model.IModel; import org.apache.wicket.spring.injection.annot.SpringBean; import com.socialsite.dao.UserDao; import com.socialsite.persistence.User; /** * BasePage for the socialsite Application * * @author Ananth * */ @AuthorizeInstantiation( { "USER", "FRIEND", "OWNER" }) public class BasePage extends WebPage implements IHeaderContributor { private static final long serialVersionUID = 1L; protected HeaderPanel headerPanel; @SpringBean(name = "userDao") private UserDao<User> userDao; /** * Constructor */ public BasePage() { this(null); } /** * Constructor. * * @param model */ public BasePage(final IModel<?> model) { super(model); // header panel add(headerPanel = new HeaderPanel("header")); } public void renderHead(final IHeaderResponse response) { // NOTE add all the css references here.Don't add css link in the other // pages or panel.This will help in combing all the css files into // single file during deployment response.renderCSSReference("css/libraries.css"); response.renderCSSReference("css/template/template.css"); response.renderCSSReference("css/grid/grids.css"); response.renderCSSReference("css/content.css"); response.renderCSSReference("css/module/mod.css"); response.renderCSSReference("css/module/mod_skins.css"); response.renderCSSReference("css/talk/talk.css"); response.renderCSSReference("css/talk/talk_skins.css"); -// response.renderCSSReference("css/global.css"); -// response.renderCSSReference("css/home.css"); -// response.renderCSSReference("css/login.css"); -// response.renderCSSReference("css/scrap.css"); -// response.renderCSSReference("css/profile.css"); -// response.renderCSSReference("css/typography.css"); -// response.renderCSSReference("css/round.css"); + response.renderCSSReference("css/global.css"); + response.renderCSSReference("css/home.css"); + response.renderCSSReference("css/login.css"); + response.renderCSSReference("css/scrap.css"); + response.renderCSSReference("css/profile.css"); + response.renderCSSReference("css/typography.css"); + response.renderCSSReference("css/round.css"); response.renderCSSReference("css/wmd.css"); response.renderCSSReference("css/menu.css"); // renders the jquery and socialsite in all pages response.renderJavascriptReference("js/jquery/jquery.js"); response.renderJavascriptReference("js/socialsite/socialsite.js"); } /** * set the user id in the session and also sets the roles in the session * * @param userId * user id */ public void setUserId(final long userId) { final SocialSiteSession session = SocialSiteSession.get(); // set the user id session.setUserId(userId); // set the roles session.getSessionUser().setRoles( userDao.getUsersRelation(userId, session.getSessionUser().getId())); } }
true
true
public void renderHead(final IHeaderResponse response) { // NOTE add all the css references here.Don't add css link in the other // pages or panel.This will help in combing all the css files into // single file during deployment response.renderCSSReference("css/libraries.css"); response.renderCSSReference("css/template/template.css"); response.renderCSSReference("css/grid/grids.css"); response.renderCSSReference("css/content.css"); response.renderCSSReference("css/module/mod.css"); response.renderCSSReference("css/module/mod_skins.css"); response.renderCSSReference("css/talk/talk.css"); response.renderCSSReference("css/talk/talk_skins.css"); // response.renderCSSReference("css/global.css"); // response.renderCSSReference("css/home.css"); // response.renderCSSReference("css/login.css"); // response.renderCSSReference("css/scrap.css"); // response.renderCSSReference("css/profile.css"); // response.renderCSSReference("css/typography.css"); // response.renderCSSReference("css/round.css"); response.renderCSSReference("css/wmd.css"); response.renderCSSReference("css/menu.css"); // renders the jquery and socialsite in all pages response.renderJavascriptReference("js/jquery/jquery.js"); response.renderJavascriptReference("js/socialsite/socialsite.js"); }
public void renderHead(final IHeaderResponse response) { // NOTE add all the css references here.Don't add css link in the other // pages or panel.This will help in combing all the css files into // single file during deployment response.renderCSSReference("css/libraries.css"); response.renderCSSReference("css/template/template.css"); response.renderCSSReference("css/grid/grids.css"); response.renderCSSReference("css/content.css"); response.renderCSSReference("css/module/mod.css"); response.renderCSSReference("css/module/mod_skins.css"); response.renderCSSReference("css/talk/talk.css"); response.renderCSSReference("css/talk/talk_skins.css"); response.renderCSSReference("css/global.css"); response.renderCSSReference("css/home.css"); response.renderCSSReference("css/login.css"); response.renderCSSReference("css/scrap.css"); response.renderCSSReference("css/profile.css"); response.renderCSSReference("css/typography.css"); response.renderCSSReference("css/round.css"); response.renderCSSReference("css/wmd.css"); response.renderCSSReference("css/menu.css"); // renders the jquery and socialsite in all pages response.renderJavascriptReference("js/jquery/jquery.js"); response.renderJavascriptReference("js/socialsite/socialsite.js"); }
diff --git a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java index c3c6fdaef..6be9dbdd3 100644 --- a/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java +++ b/opentripplanner-api-webapp/src/main/java/org/opentripplanner/api/ws/PlanGenerator.java @@ -1,802 +1,803 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (props, 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.opentripplanner.api.ws; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.Trip; import org.opentripplanner.api.model.Itinerary; import org.opentripplanner.api.model.Leg; import org.opentripplanner.api.model.Place; import org.opentripplanner.api.model.RelativeDirection; import org.opentripplanner.api.model.TripPlan; import org.opentripplanner.api.model.WalkStep; import org.opentripplanner.common.geometry.DirectionUtils; import org.opentripplanner.common.geometry.PackedCoordinateSequence; import org.opentripplanner.routing.core.DirectEdge; import org.opentripplanner.routing.core.Edge; import org.opentripplanner.routing.core.EdgeNarrative; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.core.RouteSpec; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseMode; import org.opentripplanner.routing.core.TraverseModeSet; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.Vertex; import org.opentripplanner.routing.edgetype.Dwell; import org.opentripplanner.routing.edgetype.EdgeWithElevation; import org.opentripplanner.routing.edgetype.PatternDwell; import org.opentripplanner.routing.edgetype.PatternInterlineDwell; import org.opentripplanner.routing.edgetype.FreeEdge; import org.opentripplanner.routing.edgetype.PlainStreetEdge; import org.opentripplanner.routing.edgetype.StreetVertex; import org.opentripplanner.routing.edgetype.TinyTurnEdge; import org.opentripplanner.routing.error.PathNotFoundException; import org.opentripplanner.routing.error.VertexNotFoundException; import org.opentripplanner.routing.patch.Alert; import org.opentripplanner.routing.services.FareService; import org.opentripplanner.routing.services.PathService; import org.opentripplanner.routing.services.PathServiceFactory; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.util.PolylineEncoder; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; public class PlanGenerator { private static final Logger LOGGER = Logger.getLogger(PlanGenerator.class.getCanonicalName()); Request request; private PathService pathService; private FareService fareService; public PlanGenerator(Request request, PathServiceFactory pathServiceFactory) { this.request = request; pathService = pathServiceFactory.getPathService(request.getRouterId()); Graph graph = pathService.getGraphService().getGraph(); fareService = graph.getService(FareService.class); } /** * Generates a TripPlan from a Request; * */ public TripPlan generate() { TraverseOptions options = getOptions(request); checkLocationsAccessible(request, options); /* try to plan the trip */ List<GraphPath> paths = null; boolean tooSloped = false; try { List<String> intermediates = request.getIntermediatePlaces(); if (intermediates.size() == 0) { paths = pathService.plan(request.getFrom(), request.getTo(), request.getDateTime(), options, request.getNumItineraries()); if (paths == null && request.getWheelchair()) { // There are no paths that meet the user's slope restrictions. // Try again without slope restrictions (and warn user). options.maxSlope = Double.MAX_VALUE; paths = pathService.plan(request.getFrom(), request.getTo(), request .getDateTime(), options, request.getNumItineraries()); tooSloped = true; } } else { paths = pathService.plan(request.getFrom(), request.getTo(), intermediates, request .getDateTime(), options); } } catch (VertexNotFoundException e) { LOGGER.log(Level.INFO, "Vertex not found: " + request.getFrom() + " : " + request.getTo(), e); throw e; } if (paths == null || paths.size() == 0) { LOGGER .log(Level.INFO, "Path not found: " + request.getFrom() + " : " + request.getTo()); throw new PathNotFoundException(); } TripPlan plan = generatePlan(paths, request); if (plan != null) { for (Itinerary i : plan.itinerary) { i.tooSloped = tooSloped; } } return plan; } /** * Generates a TripPlan from a set of paths */ public TripPlan generatePlan(List<GraphPath> paths, Request request) { GraphPath exemplar = paths.get(0); Vertex tripStartVertex = exemplar.getStartVertex(); Vertex tripEndVertex = exemplar.getEndVertex(); String startName = tripStartVertex.getName(); String endName = tripEndVertex.getName(); // Use vertex labels if they don't have names if (startName == null) { startName = tripStartVertex.getLabel(); } if (endName == null) { endName = tripEndVertex.getLabel(); } Place from = new Place(tripStartVertex.getX(), tripStartVertex.getY(), startName); Place to = new Place(tripEndVertex.getX(), tripEndVertex.getY(), endName); TripPlan plan = new TripPlan(from, to, request.getDateTime()); for (GraphPath path : paths) { Itinerary itinerary = generateItinerary(path, request.getShowIntermediateStops()); plan.addItinerary(itinerary); } return plan; } /** * Generate an itinerary from a @{link GraphPath}. The algorithm here is to walk over each edge * in the graph path, accumulating geometry, time, and length data. On mode change, a new leg is * generated. Street legs undergo an additional processing step to generate turn-by-turn * directions. * * @param path * @param showIntermediateStops whether intermediate stops are included in the generated * itinerary * @return itinerary */ private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; State prevState = null; EdgeNarrative backEdgeNarrative = null; for (State nextState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ if (prevState == null) { prevState = nextState; continue; } EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative(); backEdgeNarrative = prevState.getBackEdgeNarrative(); Edge backEdge = prevState.getBackEdge(); TraverseMode mode = frontEdgeNarrative.getMode(); if (backEdgeNarrative == null) { // this is the first state, so we need to create the initial leg leg = makeLeg(nextState); + leg.mode = mode.toString(); // maybe makeLeg should be setting the mode ? itinerary.addLeg(leg); if (mode.isOnStreetNonTransit()) { startWalk = i; } prevState = nextState; continue; } /* skip initial state, which has no back edges */ edgeElapsedTime = nextState.getTimeInMillis() - nextState.getBackState().getTimeInMillis(); TraverseMode previousMode = backEdgeNarrative.getMode(); if (previousMode == null) { previousMode = prevState.getBackState().getBackEdgeNarrative().getMode(); } // handle the effects of the previous edge on the leg /* ignore edges that should not contribute to the narrative */ if (backEdge instanceof FreeEdge) { prevState = nextState; continue; } if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) { itinerary.waitingTime += edgeElapsedTime; } leg.distance += backEdgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = backEdgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } addNotesToLeg(leg, backEdgeNarrative); /* * we are not boarding, alighting, etc. so are we walking/biking/driving or using * transit? */ if (previousMode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } leg.endTime = new Date(nextState.getTimeInMillis()); } else if (previousMode.isTransit()) { leg.endTime = new Date(nextState.getTimeInMillis()); /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* * first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ if (!(nextState.getBackEdge() instanceof Dwell || nextState.getBackEdge() instanceof PatternDwell || nextState .getBackEdge() instanceof PatternInterlineDwell)) { Place stop = makePlace(nextState); leg.stop.add(stop); } else { leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime()); } } } // now, transition between legs if necessary boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) { /* * change in mode. make a new leg if we are entering walk or transit, otherwise just * update the general itinerary info and move to next edge. */ boolean endLeg = false; if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) { // switching from STL to wall or bike, so we need to fix up // the start time, // mode, etc leg.startTime = new Date(nextState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); } else if (mode == TraverseMode.TRANSFER) { /* transferring mode is only used in transit-only planners */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; endLeg = true; } else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) { endLeg = true; } else { if (previousMode == TraverseMode.ALIGHTING) { // in this case, we are changing from an alighting mode // (preAlight) to // an onstreetnontransit. In this case, we have already // closed the // transit leg with alighting, so we don't want to // finalize a leg. } else if (previousMode == TraverseMode.BOARDING) { // we are changing from boarding to an on-transit mode, // so we need to // fix up the leg's route and departure time data leg.startTime = new Date(prevState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); Trip trip = frontEdgeNarrative.getTrip(); if (trip != null) { leg.headsign = trip.getTripHeadsign(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); leg.routeShortName = trip.getRoute().getShortName(); leg.routeLongName = trip.getRoute().getLongName(); } } else { // we are probably changing between walk and bike endLeg = true; } } if (endLeg) { /* finalize leg */ /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1)); } leg.to = makePlace(frontEdgeNarrative.getFromVertex()); leg.endTime = new Date(prevState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } /* initialize new leg */ leg = makeLeg(nextState); if (changingToInterlinedTrip) { leg.interlineWithPreviousLeg = true; } leg.mode = mode.toString(); startWalk = -1; leg.route = backEdgeNarrative.getName(); if (mode.isOnStreetNonTransit()) { /* * on-street (walk/bike) leg mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; } itinerary.addLeg(leg); } } /* end handling mode changes */ prevState = nextState; } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(backEdgeNarrative.getToVertex()); State finalState = path.states.getLast(); leg.endTime = new Date(finalState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; } private Set<Alert> addNotesToLeg(Leg leg, EdgeNarrative edgeNarrative) { Set<Alert> notes = edgeNarrative.getNotes(); if (notes != null) { for (Alert note : notes) { leg.addAlert(note); } } return notes; } /** * Adjusts an Itinerary's elevation fields from an elevation profile * * @return the elevation at the end of the profile */ private double applyElevation(PackedCoordinateSequence profile, Itinerary itinerary, double previousElevation) { if (profile != null) { for (Coordinate coordinate : profile.toCoordinateArray()) { if (previousElevation == Double.MAX_VALUE) { previousElevation = coordinate.y; continue; } double elevationChange = previousElevation - coordinate.y; if (elevationChange > 0) { itinerary.elevationGained += elevationChange; } else { itinerary.elevationLost -= elevationChange; } previousElevation = coordinate.y; } } return previousElevation; } /** * Makes a new empty leg from a starting edge */ private Leg makeLeg(State s) { Leg leg = new Leg(); leg.startTime = new Date(s.getBackState().getTimeInMillis()); EdgeNarrative en = s.getBackEdgeNarrative(); leg.route = en.getName(); Trip trip = en.getTrip(); if (trip != null) { leg.headsign = trip.getTripHeadsign(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); leg.routeShortName = trip.getRoute().getShortName(); leg.routeLongName = trip.getRoute().getLongName(); } leg.distance = 0.0; leg.from = makePlace(en.getFromVertex()); return leg; } /** * Makes a new empty Itinerary for a given path. * * @return */ private Itinerary makeEmptyItinerary(GraphPath path) { Itinerary itinerary = new Itinerary(); State startState = path.states.getFirst(); State endState = path.states.getLast(); itinerary.startTime = new Date(startState.getTimeInMillis()); itinerary.endTime = new Date(endState.getTimeInMillis()); itinerary.duration = endState.getTimeInMillis() - startState.getTimeInMillis(); if (fareService != null) { itinerary.fare = fareService.getCost(path); } itinerary.transfers = -1; return itinerary; } /** * Makes a new Place from a state. Contains information about time. * * @return */ private Place makePlace(State state) { Coordinate endCoord = state.getVertex().getCoordinate(); String name = state.getVertex().getName(); AgencyAndId stopId = state.getVertex().getStopId(); Date timeAtState = new Date(state.getTimeInMillis()); Place place = new Place(endCoord.x, endCoord.y, name, stopId, timeAtState); return place; } /** * Makes a new Place from a vertex. * * @return */ private Place makePlace(Vertex vertex) { Coordinate endCoord = vertex.getCoordinate(); Place place = new Place(endCoord.x, endCoord.y, vertex.getName()); place.stopId = vertex.getStopId(); return place; } /** * Throw an exception if the start and end locations are not wheelchair accessible given the * user's specified maximum slope. */ private void checkLocationsAccessible(Request request, TraverseOptions options) { if (request.getWheelchair()) { // check if the start and end locations are accessible if (!pathService.isAccessible(request.getFrom(), options) || !pathService.isAccessible(request.getTo(), options)) { throw new LocationNotAccessible(); } } } /** * Get the traverse options for a request * * @param request * @return */ private TraverseOptions getOptions(Request request) { TraverseModeSet modeSet = request.getModeSet(); assert (modeSet.isValid()); TraverseOptions options = new TraverseOptions(modeSet); options.optimizeFor = request.getOptimize(); options.setArriveBy(request.isArriveBy()); options.wheelchairAccessible = request.getWheelchair(); if (request.getMaxSlope() > 0) { options.maxSlope = request.getMaxSlope(); } if (request.getMaxWalkDistance() > 0) { options.setMaxWalkDistance(request.getMaxWalkDistance()); } if (request.getWalkSpeed() > 0) { options.speed = request.getWalkSpeed(); } options.triangleSafetyFactor = request.getTriangleSafetyFactor(); options.triangleSlopeFactor = request.getTriangleSlopeFactor(); options.triangleTimeFactor = request.getTriangleTimeFactor(); if (request.getMinTransferTime() != null) { options.minTransferTime = request.getMinTransferTime(); } if (request.getPreferredRoutes() != null) { for (String element : request.getPreferredRoutes()) { String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException( "AgencyId or routeId not set in preferredRoutes list"); } options.preferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } if (request.getUnpreferredRoutes() != null) { for (String element : request.getUnpreferredRoutes()) { String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException( "AgencyId or routeId not set in unpreferredRoutes list"); } options.unpreferredRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } if (request.getBannedRoutes() != null) { for (String element : request.getBannedRoutes()) { String[] routeSpec = element.split("_", 2); if (routeSpec.length != 2) { throw new IllegalArgumentException( "AgencyId or routeId not set in bannedRoutes list"); } options.bannedRoutes.add(new RouteSpec(routeSpec[0], routeSpec[1])); } } if (request.getTransferPenalty() != null) { options.transferPenalty = request.getTransferPenalty(); } return options; } /** * Converts a list of street edges to a list of turn-by-turn directions. * * @param edges : A list of street edges * @return */ private List<WalkStep> getWalkSteps(PathService pathService, List<State> states) { List<WalkStep> steps = new ArrayList<WalkStep>(); WalkStep step = null; double lastAngle = 0, distance = 0; // distance used for appending elevation profiles int roundaboutExit = 0; // track whether we are in a roundabout, and if so the exit number for (State currState : states) { Edge edge = currState.getBackEdge(); EdgeNarrative edgeNarrative = currState.getBackEdgeNarrative(); if (edge instanceof FreeEdge) { continue; } if (!edgeNarrative.getMode().isOnStreetNonTransit()) { continue; // ignore STLs and the like } Geometry geom = edgeNarrative.getGeometry(); if (geom == null) { continue; } String streetName = edgeNarrative.getName(); if (step == null) { // first step step = createWalkStep(currState); steps.add(step); double thisAngle = DirectionUtils.getFirstAngle(geom); step.setAbsoluteDirection(thisAngle); // new step, set distance to length of first edge distance = edgeNarrative.getDistance(); } else if (step.streetName != streetName && (step.streetName != null && !step.streetName.equals(streetName))) { /* street name has changed */ if (roundaboutExit > 0) { // if we were just on a roundabout, // make note of which exit was taken in the existing step step.exit = Integer.toString(roundaboutExit); // ordinal numbers from // localization roundaboutExit = 0; } /* start a new step */ step = createWalkStep(currState); steps.add(step); if (edgeNarrative.isRoundabout()) { // indicate that we are now on a roundabout // and use one-based exit numbering roundaboutExit = 1; } double thisAngle = DirectionUtils.getFirstAngle(geom); step.setDirections(lastAngle, thisAngle, edgeNarrative.isRoundabout()); // new step, set distance to length of first edge distance = edgeNarrative.getDistance(); } else { /* street name has not changed */ double thisAngle = DirectionUtils.getFirstAngle(geom); RelativeDirection direction = WalkStep.getRelativeDirection(lastAngle, thisAngle, edgeNarrative.isRoundabout()); boolean optionsBefore = pathService.multipleOptionsBefore(edge, currState .getBackState()); if (edgeNarrative.isRoundabout()) { // we are on a roundabout, and have already traversed at least one edge of it. if (optionsBefore) { // increment exit count if we passed one. roundaboutExit += 1; } } if (edgeNarrative.isRoundabout() || direction == RelativeDirection.CONTINUE) { // we are continuing almost straight, or continuing along a roundabout. // just append elevation info onto the existing step. if (step.elevation != null) { String s = encodeElevationProfile(edge, distance); if (step.elevation.length() > 0 && s != null && s.length() > 0) step.elevation += ","; step.elevation += s; } // extending a step, increment the existing distance distance += edgeNarrative.getDistance(); } else { // we are not on a roundabout, and not continuing straight through. // figure out if there were other plausible turn options at the last // intersection // to see if we should generate a "left to continue" instruction. boolean shouldGenerateContinue = false; if (edge instanceof PlainStreetEdge) { // the next edges will be TinyTurnEdges or PlainStreetEdges, we hope double angleDiff = getAbsoluteAngleDiff(thisAngle, lastAngle); for (DirectEdge alternative : pathService.getOutgoingEdges(currState .getBackState().getVertex())) { if (alternative instanceof TinyTurnEdge) { alternative = pathService.getOutgoingEdges( alternative.getToVertex()).get(0); } double altAngle = DirectionUtils.getFirstAngle(alternative .getGeometry()); double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle); if (altAngleDiff - angleDiff < Math.PI / 16) { shouldGenerateContinue = true; break; } } } else if (edge instanceof TinyTurnEdge) { // do nothing as this will be handled in other cases } else { double newAngle; if (currState.getVertex() instanceof StreetVertex) { newAngle = DirectionUtils.getFirstAngle(((StreetVertex) currState .getVertex()).getGeometry()); } else { List<DirectEdge> outgoingEdges = pathService.getOutgoingEdges(currState .getVertex()); Edge oge = outgoingEdges.get(0); newAngle = DirectionUtils.getFirstAngle(((DirectEdge) oge) .getGeometry()); } double angleDiff = getAbsoluteAngleDiff(newAngle, thisAngle); for (DirectEdge alternative : pathService.getOutgoingEdges(currState .getBackState().getVertex())) { if (alternative == edge) { continue; } alternative = pathService.getOutgoingEdges(alternative.getToVertex()) .get(0); double altAngle = DirectionUtils.getFirstAngle(alternative .getGeometry()); double altAngleDiff = getAbsoluteAngleDiff(altAngle, lastAngle); if (altAngleDiff - angleDiff < Math.PI / 16) { shouldGenerateContinue = true; break; } } } if (shouldGenerateContinue) { // turn to stay on same-named street step = createWalkStep(currState); steps.add(step); step.setDirections(lastAngle, thisAngle, false); step.stayOn = true; // new step, set distance to length of first edge distance = edgeNarrative.getDistance(); } } } // increment the total length for this step step.distance += edgeNarrative.getDistance(); step.addAlerts(edgeNarrative.getNotes()); lastAngle = DirectionUtils.getLastAngle(geom); } return steps; } private double getAbsoluteAngleDiff(double thisAngle, double lastAngle) { double angleDiff = thisAngle - lastAngle; if (angleDiff < 0) { angleDiff += Math.PI * 2; } double ccwAngleDiff = Math.PI * 2 - angleDiff; if (ccwAngleDiff < angleDiff) { angleDiff = ccwAngleDiff; } return angleDiff; } private WalkStep createWalkStep(State s) { EdgeNarrative en = s.getBackEdgeNarrative(); WalkStep step; step = new WalkStep(); step.streetName = en.getName(); step.lon = en.getFromVertex().getX(); step.lat = en.getFromVertex().getY(); step.elevation = encodeElevationProfile(s.getBackEdge(), 0); step.bogusName = en.hasBogusName(); step.addAlerts(en.getNotes()); return step; } private String encodeElevationProfile(Edge edge, double offset) { if (!(edge instanceof EdgeWithElevation)) { return ""; } EdgeWithElevation elevEdge = (EdgeWithElevation) edge; if (elevEdge.getElevationProfile() == null) { return ""; } StringBuilder str = new StringBuilder(); Coordinate[] coordArr = elevEdge.getElevationProfile().toCoordinateArray(); for (int i = 0; i < coordArr.length; i++) { str.append(Math.round(coordArr[i].x + offset)); str.append(","); str.append(Math.round(coordArr[i].y * 10.0) / 10.0); str.append(i < coordArr.length - 1 ? "," : ""); } return str.toString(); } }
true
true
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; State prevState = null; EdgeNarrative backEdgeNarrative = null; for (State nextState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ if (prevState == null) { prevState = nextState; continue; } EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative(); backEdgeNarrative = prevState.getBackEdgeNarrative(); Edge backEdge = prevState.getBackEdge(); TraverseMode mode = frontEdgeNarrative.getMode(); if (backEdgeNarrative == null) { // this is the first state, so we need to create the initial leg leg = makeLeg(nextState); itinerary.addLeg(leg); if (mode.isOnStreetNonTransit()) { startWalk = i; } prevState = nextState; continue; } /* skip initial state, which has no back edges */ edgeElapsedTime = nextState.getTimeInMillis() - nextState.getBackState().getTimeInMillis(); TraverseMode previousMode = backEdgeNarrative.getMode(); if (previousMode == null) { previousMode = prevState.getBackState().getBackEdgeNarrative().getMode(); } // handle the effects of the previous edge on the leg /* ignore edges that should not contribute to the narrative */ if (backEdge instanceof FreeEdge) { prevState = nextState; continue; } if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) { itinerary.waitingTime += edgeElapsedTime; } leg.distance += backEdgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = backEdgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } addNotesToLeg(leg, backEdgeNarrative); /* * we are not boarding, alighting, etc. so are we walking/biking/driving or using * transit? */ if (previousMode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } leg.endTime = new Date(nextState.getTimeInMillis()); } else if (previousMode.isTransit()) { leg.endTime = new Date(nextState.getTimeInMillis()); /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* * first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ if (!(nextState.getBackEdge() instanceof Dwell || nextState.getBackEdge() instanceof PatternDwell || nextState .getBackEdge() instanceof PatternInterlineDwell)) { Place stop = makePlace(nextState); leg.stop.add(stop); } else { leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime()); } } } // now, transition between legs if necessary boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) { /* * change in mode. make a new leg if we are entering walk or transit, otherwise just * update the general itinerary info and move to next edge. */ boolean endLeg = false; if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) { // switching from STL to wall or bike, so we need to fix up // the start time, // mode, etc leg.startTime = new Date(nextState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); } else if (mode == TraverseMode.TRANSFER) { /* transferring mode is only used in transit-only planners */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; endLeg = true; } else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) { endLeg = true; } else { if (previousMode == TraverseMode.ALIGHTING) { // in this case, we are changing from an alighting mode // (preAlight) to // an onstreetnontransit. In this case, we have already // closed the // transit leg with alighting, so we don't want to // finalize a leg. } else if (previousMode == TraverseMode.BOARDING) { // we are changing from boarding to an on-transit mode, // so we need to // fix up the leg's route and departure time data leg.startTime = new Date(prevState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); Trip trip = frontEdgeNarrative.getTrip(); if (trip != null) { leg.headsign = trip.getTripHeadsign(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); leg.routeShortName = trip.getRoute().getShortName(); leg.routeLongName = trip.getRoute().getLongName(); } } else { // we are probably changing between walk and bike endLeg = true; } } if (endLeg) { /* finalize leg */ /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1)); } leg.to = makePlace(frontEdgeNarrative.getFromVertex()); leg.endTime = new Date(prevState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } /* initialize new leg */ leg = makeLeg(nextState); if (changingToInterlinedTrip) { leg.interlineWithPreviousLeg = true; } leg.mode = mode.toString(); startWalk = -1; leg.route = backEdgeNarrative.getName(); if (mode.isOnStreetNonTransit()) { /* * on-street (walk/bike) leg mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; } itinerary.addLeg(leg); } } /* end handling mode changes */ prevState = nextState; } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(backEdgeNarrative.getToVertex()); State finalState = path.states.getLast(); leg.endTime = new Date(finalState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; }
private Itinerary generateItinerary(GraphPath path, boolean showIntermediateStops) { Itinerary itinerary = makeEmptyItinerary(path); Leg leg = null; CoordinateArrayListSequence coordinates = new CoordinateArrayListSequence(); double previousElevation = Double.MAX_VALUE; double edgeElapsedTime; GeometryFactory geometryFactory = new GeometryFactory(); int startWalk = -1; int i = -1; State prevState = null; EdgeNarrative backEdgeNarrative = null; for (State nextState : path.states) { i++; /* grab base edge and associated narrative information from SPT edge */ if (prevState == null) { prevState = nextState; continue; } EdgeNarrative frontEdgeNarrative = nextState.getBackEdgeNarrative(); backEdgeNarrative = prevState.getBackEdgeNarrative(); Edge backEdge = prevState.getBackEdge(); TraverseMode mode = frontEdgeNarrative.getMode(); if (backEdgeNarrative == null) { // this is the first state, so we need to create the initial leg leg = makeLeg(nextState); leg.mode = mode.toString(); // maybe makeLeg should be setting the mode ? itinerary.addLeg(leg); if (mode.isOnStreetNonTransit()) { startWalk = i; } prevState = nextState; continue; } /* skip initial state, which has no back edges */ edgeElapsedTime = nextState.getTimeInMillis() - nextState.getBackState().getTimeInMillis(); TraverseMode previousMode = backEdgeNarrative.getMode(); if (previousMode == null) { previousMode = prevState.getBackState().getBackEdgeNarrative().getMode(); } // handle the effects of the previous edge on the leg /* ignore edges that should not contribute to the narrative */ if (backEdge instanceof FreeEdge) { prevState = nextState; continue; } if (previousMode == TraverseMode.BOARDING || previousMode == TraverseMode.ALIGHTING) { itinerary.waitingTime += edgeElapsedTime; } leg.distance += backEdgeNarrative.getDistance(); /* for all edges with geometry, append their coordinates to the leg's. */ Geometry edgeGeometry = backEdgeNarrative.getGeometry(); if (edgeGeometry != null) { Coordinate[] edgeCoordinates = edgeGeometry.getCoordinates(); if (coordinates.size() > 0 && coordinates.getCoordinate(coordinates.size() - 1).equals( edgeCoordinates[0])) { coordinates.extend(edgeCoordinates, 1); } else { coordinates.extend(edgeCoordinates); } } addNotesToLeg(leg, backEdgeNarrative); /* * we are not boarding, alighting, etc. so are we walking/biking/driving or using * transit? */ if (previousMode.isOnStreetNonTransit()) { /* we are on the street (non-transit) */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); if (backEdge instanceof EdgeWithElevation) { PackedCoordinateSequence profile = ((EdgeWithElevation) backEdge) .getElevationProfile(); previousElevation = applyElevation(profile, itinerary, previousElevation); } leg.endTime = new Date(nextState.getTimeInMillis()); } else if (previousMode.isTransit()) { leg.endTime = new Date(nextState.getTimeInMillis()); /* we are on a transit trip */ itinerary.transitTime += edgeElapsedTime; if (showIntermediateStops) { /* add an intermediate stop to the current leg */ if (leg.stop == null) { /* * first transit edge, just create the list (the initial stop is current * "from" vertex) */ leg.stop = new ArrayList<Place>(); } /* any further transit edge, add "from" vertex to intermediate stops */ if (!(nextState.getBackEdge() instanceof Dwell || nextState.getBackEdge() instanceof PatternDwell || nextState .getBackEdge() instanceof PatternInterlineDwell)) { Place stop = makePlace(nextState); leg.stop.add(stop); } else { leg.stop.get(leg.stop.size() - 1).departure = new Date(nextState.getTime()); } } } // now, transition between legs if necessary boolean changingToInterlinedTrip = leg != null && leg.route != null && !leg.route.equals(backEdgeNarrative.getName()) && mode.isTransit() && previousMode != null && previousMode.isTransit(); if ((mode != previousMode || changingToInterlinedTrip) && mode != TraverseMode.STL) { /* * change in mode. make a new leg if we are entering walk or transit, otherwise just * update the general itinerary info and move to next edge. */ boolean endLeg = false; if (previousMode == TraverseMode.STL && mode.isOnStreetNonTransit()) { // switching from STL to wall or bike, so we need to fix up // the start time, // mode, etc leg.startTime = new Date(nextState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); } else if (mode == TraverseMode.TRANSFER) { /* transferring mode is only used in transit-only planners */ itinerary.walkTime += edgeElapsedTime; itinerary.walkDistance += backEdgeNarrative.getDistance(); } else if (mode == TraverseMode.BOARDING) { /* boarding mode */ itinerary.transfers++; endLeg = true; } else if (mode == TraverseMode.ALIGHTING || changingToInterlinedTrip) { endLeg = true; } else { if (previousMode == TraverseMode.ALIGHTING) { // in this case, we are changing from an alighting mode // (preAlight) to // an onstreetnontransit. In this case, we have already // closed the // transit leg with alighting, so we don't want to // finalize a leg. } else if (previousMode == TraverseMode.BOARDING) { // we are changing from boarding to an on-transit mode, // so we need to // fix up the leg's route and departure time data leg.startTime = new Date(prevState.getTimeInMillis()); leg.route = frontEdgeNarrative.getName(); leg.mode = mode.toString(); Trip trip = frontEdgeNarrative.getTrip(); if (trip != null) { leg.headsign = trip.getTripHeadsign(); leg.agencyId = trip.getId().getAgencyId(); leg.tripShortName = trip.getTripShortName(); leg.routeShortName = trip.getRoute().getShortName(); leg.routeLongName = trip.getRoute().getLongName(); } } else { // we are probably changing between walk and bike endLeg = true; } } if (endLeg) { /* finalize leg */ /* finalize prior leg if it exists */ if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i - 1)); } leg.to = makePlace(frontEdgeNarrative.getFromVertex()); leg.endTime = new Date(prevState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); /* reset coordinates */ coordinates = new CoordinateArrayListSequence(); if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } /* initialize new leg */ leg = makeLeg(nextState); if (changingToInterlinedTrip) { leg.interlineWithPreviousLeg = true; } leg.mode = mode.toString(); startWalk = -1; leg.route = backEdgeNarrative.getName(); if (mode.isOnStreetNonTransit()) { /* * on-street (walk/bike) leg mark where in edge list on-street legs begin, * so step-by-step instructions can be generated for this sublist later */ startWalk = i; } else { /* transit leg */ startWalk = -1; } itinerary.addLeg(leg); } } /* end handling mode changes */ prevState = nextState; } /* end loop over graphPath edge list */ if (leg != null) { /* finalize leg */ leg.to = makePlace(backEdgeNarrative.getToVertex()); State finalState = path.states.getLast(); leg.endTime = new Date(finalState.getTimeInMillis()); Geometry geometry = geometryFactory.createLineString(coordinates); leg.legGeometry = PolylineEncoder.createEncodings(geometry); if (startWalk != -1) { leg.walkSteps = getWalkSteps(pathService, path.states.subList(startWalk, i + 1)); } if (showIntermediateStops && leg.stop != null) { // Remove the last stop -- it's the alighting one leg.stop.remove(leg.stop.size() - 1); if (leg.stop.isEmpty()) { leg.stop = null; } } } if (itinerary.transfers == -1) { itinerary.transfers = 0; } itinerary.removeBogusLegs(); return itinerary; }