lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
mit
|
12713aee0b044f7a99ef9d8074755cc910153887
| 0
|
CS2103JAN2017-W13-B2/main,CS2103JAN2017-W13-B2/main
|
package seedu.address.model.tag;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.CollectionUtil;
/**
* A list of tags that enforces no nulls and uniqueness between its elements.
*
* Supports minimal set of list operations for the app's features.
* UniqueTagList enforces uniqueness internally rather than rasing Exception
*
* @see Tag#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTagList implements Iterable<Tag> {
private final ObservableList<Tag> internalList = FXCollections.observableArrayList();
/**
* Constructs empty TagList.
*/
public UniqueTagList() {}
/**
* Creates a UniqueTagList using given String tags.
* Enforces no nulls or duplicates.
*/
public UniqueTagList(String... tags) throws IllegalValueException {
final List<Tag> tagList = new ArrayList<Tag>();
for (String tag : tags) {
tagList.add(new Tag(tag));
}
setTags(tagList);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no nulls or duplicates.
*/
public UniqueTagList(Tag... tags) {
assert !CollectionUtil.isAnyNull((Object[]) tags);
final List<Tag> initialTags = Arrays.asList(tags);
setTags(initialTags);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no null or duplicate elements.
*/
public UniqueTagList(Collection<Tag> tags) {
this();
setTags(tags);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no nulls.
*/
public UniqueTagList(Set<Tag> tags) {
assert !CollectionUtil.isAnyNull(tags);
internalList.addAll(tags);
}
/**
* Creates a copy of the given list.
* Insulates from changes in source.
*/
public UniqueTagList(UniqueTagList source) {
internalList.addAll(source.internalList); // insulate internal list from changes in argument
}
/**
* Returns all tags in this list as a Set.
* This set is mutable and change-insulated against the internal list.
*/
public Set<Tag> toSet() {
return new HashSet<>(internalList);
}
/**
* Replaces the Tags in this list with those in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
this.internalList.setAll(replacement.internalList);
}
public void setTags(Collection<Tag> tags) {
assert !CollectionUtil.isAnyNull(tags);
assert CollectionUtil.elementsAreUnique(tags);
this.internalList.setAll(tags);
}
/**
* Ensures every tag in the argument list exists in this object.
*/
public void mergeFrom(UniqueTagList from) {
final Set<Tag> alreadyInside = this.toSet();
from.internalList.stream()
.filter(tag -> !alreadyInside.contains(tag))
.forEach(internalList::add);
}
/**
* Returns true if the list contains an equivalent Tag as the given argument.
*/
public boolean contains(Tag toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/** Adds a Tag to the list. */
public void add(Tag toAdd) {
assert toAdd != null;
if (!contains(toAdd)) {
internalList.add(toAdd);
}
}
/** Adds a list of Tags to the list. */
public void addTags(List<Tag> tags) {
tags.forEach(this::add);
}
@Override
public Iterator<Tag> iterator() {
return internalList.iterator();
}
public UnmodifiableObservableList<Tag> asObservableList() {
return new UnmodifiableObservableList<>(internalList);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTagList // instanceof handles nulls
&& this.internalList.equals(
((UniqueTagList) other).internalList));
}
public boolean equalsOrderInsensitive(UniqueTagList other) {
return this == other || new HashSet<>(this.internalList).equals(new HashSet<>(other.internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
public String getTags() {
String tags = "";
for (Tag tag:internalList) {
tags = tags.concat(tag.tagName);
tags = tags.concat(" ");
}
return tags;
}
}
|
src/main/java/seedu/address/model/tag/UniqueTagList.java
|
package seedu.address.model.tag;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.commons.util.CollectionUtil;
/**
* A list of tags that enforces no nulls and uniqueness between its elements.
*
* Supports minimal set of list operations for the app's features.
* UniqueTagList enforces uniqueness internally rather than rasing Exception
*
* @see Tag#equals(Object)
* @see CollectionUtil#elementsAreUnique(Collection)
*/
public class UniqueTagList implements Iterable<Tag> {
private final ObservableList<Tag> internalList = FXCollections.observableArrayList();
/**
* Constructs empty TagList.
*/
public UniqueTagList() {}
/**
* Creates a UniqueTagList using given String tags.
* Enforces no nulls or duplicates.
*/
public UniqueTagList(String... tags) throws IllegalValueException {
final List<Tag> tagList = new ArrayList<Tag>();
for (String tag : tags) {
tagList.add(new Tag(tag));
}
setTags(tagList);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no nulls or duplicates.
*/
public UniqueTagList(Tag... tags) {
assert !CollectionUtil.isAnyNull((Object[]) tags);
final List<Tag> initialTags = Arrays.asList(tags);
setTags(initialTags);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no null or duplicate elements.
*/
public UniqueTagList(Collection<Tag> tags) {
this();
setTags(tags);
}
/**
* Creates a UniqueTagList using given tags.
* Enforces no nulls.
*/
public UniqueTagList(Set<Tag> tags) {
assert !CollectionUtil.isAnyNull(tags);
internalList.addAll(tags);
}
/**
* Creates a copy of the given list.
* Insulates from changes in source.
*/
public UniqueTagList(UniqueTagList source) {
internalList.addAll(source.internalList); // insulate internal list from changes in argument
}
/**
* Returns all tags in this list as a Set.
* This set is mutable and change-insulated against the internal list.
*/
public Set<Tag> toSet() {
return new HashSet<>(internalList);
}
/**
* Replaces the Tags in this list with those in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
this.internalList.setAll(replacement.internalList);
}
public void setTags(Collection<Tag> tags) {
assert !CollectionUtil.isAnyNull(tags);
assert CollectionUtil.elementsAreUnique(tags);
this.internalList.setAll(tags);
}
/**
* Ensures every tag in the argument list exists in this object.
*/
public void mergeFrom(UniqueTagList from) {
final Set<Tag> alreadyInside = this.toSet();
from.internalList.stream()
.filter(tag -> !alreadyInside.contains(tag))
.forEach(internalList::add);
}
/**
* Returns true if the list contains an equivalent Tag as the given argument.
*/
public boolean contains(Tag toCheck) {
assert toCheck != null;
return internalList.contains(toCheck);
}
/** Adds a Tag to the list. */
public void add(Tag toAdd) {
assert toAdd != null;
if (!contains(toAdd)) {
internalList.add(toAdd);
}
}
/** Adds a list of Tags to the list. */
public void addTags(List<Tag> tags) {
tags.forEach(this::add);
}
@Override
public Iterator<Tag> iterator() {
return internalList.iterator();
}
public UnmodifiableObservableList<Tag> asObservableList() {
return new UnmodifiableObservableList<>(internalList);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof UniqueTagList // instanceof handles nulls
&& this.internalList.equals(
((UniqueTagList) other).internalList));
}
public boolean equalsOrderInsensitive(UniqueTagList other) {
return this == other || new HashSet<>(this.internalList).equals(new HashSet<>(other.internalList));
}
@Override
public int hashCode() {
return internalList.hashCode();
}
}
|
add getTags method in UniqueTagList
|
src/main/java/seedu/address/model/tag/UniqueTagList.java
|
add getTags method in UniqueTagList
|
|
Java
|
epl-1.0
|
fb35fb90b223364e01295a3c9827926457fa109b
| 0
|
matias-burgos/Trabajo-Practico-Final---Hotel
|
Conserje.java
|
package Paquete;
public class Conserje extends UserHotel
{
int permiso;
public int getPermisos()
{
return permiso;
}
public void setPermisos(int permiso)
{
this.permiso = permiso;
}
}
|
Delete Conserje.java
|
Conserje.java
|
Delete Conserje.java
|
||
Java
|
mpl-2.0
|
6619b9bb660b18b2a16ce5eaa992da2295c91552
| 0
|
slidewiki/nlp-service,slidewiki/nlp-service,slidewiki/nlp-service,slidewiki/nlp-service
|
package controllers;
import javax.inject.Inject;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import play.Logger;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;
import services.nlp.NLPComponent;
import services.nlp.dbpediaspotlight.DBPediaSpotlightUtil;
import services.nlp.html.IHtmlToText;
import services.nlp.languagedetection.ILanguageDetector;
import services.nlp.ner.INERLanguageDependent;
import services.nlp.stopwords.IStopwordRemover;
import services.nlp.tfidf.IDocFrequencyProviderTypeDependent;
import services.nlp.tokenization.ITokenizerLanguageDependent;
import services.util.NLPStorageUtil;
@Api(value = "/nlp")
public class NLPController extends Controller{
private NLPComponent nlpComponent;
@Inject
public NLPController(IHtmlToText htmlToText, ILanguageDetector languageDetector, ITokenizerLanguageDependent tokenizer, IStopwordRemover stopwordRemover,
INERLanguageDependent ner, DBPediaSpotlightUtil dbPediaSpotlightUtil, IDocFrequencyProviderTypeDependent docFrequencyProvider, NLPStorageUtil nlpStorageUtil) {
super();
this.nlpComponent = new NLPComponent(htmlToText, languageDetector, tokenizer, stopwordRemover, ner, dbPediaSpotlightUtil, docFrequencyProvider, nlpStorageUtil);
}
@Inject
public NLPController(NLPComponent nlpComponent) {
super();
this.nlpComponent = nlpComponent;
}
@javax.ws.rs.Path(value = "/htmlToText")
@ApiOperation(value = "html to text", notes = "")
public Result htmlToText(
@ApiParam(required = true, value = "input text") String inputText) {
ObjectNode result = Json.newObject();
result = nlpComponent.getPlainTextFromHTML(inputText, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/language")
@ApiOperation(value = "returns language detection result for given input", notes = "language detection performed for given input")
public Result detectLanguage(
@ApiParam(value = "input text") String inputText) {
ObjectNode result = Json.newObject();
result = nlpComponent.detectLanguage(inputText, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/tokenize")
@ApiOperation(value = "returns tokens for given input", notes = "tokens are calculated for the given input")
public Result tokenize(
@ApiParam(required = true, value = "input text") String inputText,
@ApiParam(required = true, value = "language") String language) {
ObjectNode result = Json.newObject();
result = nlpComponent.tokenize(inputText, language, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/nlp")
@ApiOperation(value = "performs different available nlp steps", notes = "different nlp steps are performed, currently: language detection, tokenization, NER and tfidf (top 10)")
public Result performNLP(
@ApiParam(value = "input text") String inputText) {
ObjectNode result = Json.newObject();
double dbpediaSpotlightConfidence = DBPediaSpotlightUtil.dbpediaspotlightdefaultConfidence; // TODO: make this conigurable
result = nlpComponent.performNLP(inputText, result, dbpediaSpotlightConfidence);
return ok(result);
}
@javax.ws.rs.Path(value = "/nlpForDeck")
@ApiOperation(
value = "performs different available nlp steps for content of deck",
notes = "different nlp steps are performed, currently: language detection, tokenization, NER, DBPedia Spotlight, tfidf (top 10) for tokens and dbPediaSpotlight")
@ApiResponses(
value = {
@ApiResponse(code = 404, message = "Problem while retrieving slides for given deck id via deck service. Slides for given deck id not found. Probably this deck id does not exist."),
@ApiResponse(code = 500, message = "Problem occured during calling spotlight service. For more information see details provided.")
})
public Result performNlpForDeck(
@ApiParam(required = true, value = "deckId") String deckId,
@ApiParam(required = true, defaultValue = "0.6", value = "dbpediaSpotlightConfidenceForSlide (use a value>1 to skip spotlight processing per slides)") double dbpediaSpotlightConfidenceForSlide,
@ApiParam(required = true, defaultValue = "0.6", value = "dbpediaSpotlightConfidenceForDeck (use a value>1 to skip spotlight processing per deck (=text of deck as input to spotlight). Spotlight per slide will be still processed.") double dbpediaSpotlightConfidenceForDeck) {
try{
ObjectNode resultNode = nlpComponent.processDeck(deckId, dbpediaSpotlightConfidenceForSlide, dbpediaSpotlightConfidenceForDeck);
Result r = Results.ok(resultNode);
return r;
}catch (WebApplicationException e) {
return createResultForExceptionalResponseCausedByWebApllicationException(e);
}catch(ProcessingException f){
String message = "Processing was interupted. Problem occured during Processing. For more information see details provided.";
return createResultForProcessingException(500, f, message);
}
}
@javax.ws.rs.Path(value = "/dbpediaspotlight")
@ApiOperation(
value = "returns results for dbpedia spotlight", // displayed next to path
notes = "returns result of dbpedia spotlight for the given input",// displayed under "Implementation notes"
nickname = "spotlight",
httpMethod = "GET"
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "Please provide a confidence value in the range of 0 to 1"),
@ApiResponse(code = 500, message = "Problem occured during calling spotlight service. For more information see details provided.")}
)
public Result dbpediaSpotlight(
@ApiParam(required = true, value = "input text") String inputText,
@ApiParam(required = true, defaultValue = "0.6", value = "confidence (in range of 0 to 1, e.g. 0.6)") double confidence) {
Logger.debug("confidence set to " + confidence);
if(confidence>1 || confidence < 0 ){
return badRequest("Please provide a confidence value in the range of 0 to 1");
}
Response response;
try{
response = nlpComponent.performDBpediaSpotlight(inputText, confidence);
if(response.getStatus()!=200){
return createResultForResponseObject(response, "Problem occured during calling spotlight service. For more information see details provided.");
}else{
return createResultForResponseObject(response, "");
}
}catch(ProcessingException e){
return createResultForProcessingException(500, e, "Problem occured during calling spotlight service. For more information see details provided.");
}
}
/**
* Creates a Result for a {@link WebApplicationException} which is thrown when other called service do not return expected result.
* Creates a Result with the same status code like returned by the called service.
* @param e
* @return
*/
public static Result createResultForExceptionalResponseCausedByWebApllicationException(WebApplicationException e){
ObjectNode responseContent = Json.newObject();
String message = e.getMessage();
responseContent.put("message", message);
Response response = e.getResponse();
int status = response.getStatus();
responseContent.put("status", status);
String responseAsString = response.readEntity(String.class);
JsonNode responseAsJsonNode = Json.parse(responseAsString);
responseContent.set("Response", responseAsJsonNode);
Result result = Results.status(status, responseContent);
return result;
}
public static Result createResultForResponseObject(Response response, String optionalMessage){
ObjectNode responseContent = Json.newObject();
if(optionalMessage!=null && optionalMessage.length()>0){
responseContent.put("message", optionalMessage);
}
int status = response.getStatus();
responseContent.put("status", status);
String responseAsString = response.readEntity(String.class);
try{
JsonNode responseAsJsonNode = Json.parse(responseAsString);
responseContent.set("Response", responseAsJsonNode);
}
catch(RuntimeException e){// problem parsing json
responseContent.put("Response", responseAsString);
}
Result result = Results.status(status, responseContent);
return result;
}
public static Result createResultForProcessingException(int statusToReturn, Exception e, String optionalMessage){
ObjectNode responseContent = Json.newObject();
responseContent.put("status", statusToReturn);
if(optionalMessage!=null && optionalMessage.length()>0){
responseContent.put("message", optionalMessage);
}
responseContent.put("detailsErrorMessage", e.getMessage());
if(e.getCause()!=null){
responseContent.put("detailsErrorCause", e.getCause().toString());
}
return Results.status(statusToReturn, responseContent);
}
}
|
app/controllers/NLPController.java
|
package controllers;
import javax.inject.Inject;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import play.Logger;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results;
import services.nlp.NLPComponent;
import services.nlp.dbpediaspotlight.DBPediaSpotlightUtil;
import services.nlp.html.IHtmlToText;
import services.nlp.languagedetection.ILanguageDetector;
import services.nlp.ner.INERLanguageDependent;
import services.nlp.stopwords.IStopwordRemover;
import services.nlp.tfidf.IDocFrequencyProviderTypeDependent;
import services.nlp.tokenization.ITokenizerLanguageDependent;
@Api(value = "/nlp")
public class NLPController extends Controller{
private NLPComponent nlpComponent;
@Inject
public NLPController(IHtmlToText htmlToText, ILanguageDetector languageDetector, ITokenizerLanguageDependent tokenizer, IStopwordRemover stopwordRemover,
INERLanguageDependent ner, DBPediaSpotlightUtil dbPediaSpotlightUtil, IDocFrequencyProviderTypeDependent docFrequencyProvider) {
super();
this.nlpComponent = new NLPComponent(htmlToText, languageDetector, tokenizer, stopwordRemover, ner, dbPediaSpotlightUtil, docFrequencyProvider);
}
@Inject
public NLPController(NLPComponent nlpComponent) {
super();
this.nlpComponent = nlpComponent;
}
@javax.ws.rs.Path(value = "/htmlToText")
@ApiOperation(value = "html to text", notes = "")
public Result htmlToText(
@ApiParam(required = true, value = "input text") String inputText) {
ObjectNode result = Json.newObject();
result = nlpComponent.getPlainTextFromHTML(inputText, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/language")
@ApiOperation(value = "returns language detection result for given input", notes = "language detection performed for given input")
public Result detectLanguage(
@ApiParam(value = "input text") String inputText) {
ObjectNode result = Json.newObject();
result = nlpComponent.detectLanguage(inputText, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/tokenize")
@ApiOperation(value = "returns tokens for given input", notes = "tokens are calculated for the given input")
public Result tokenize(
@ApiParam(required = true, value = "input text") String inputText,
@ApiParam(required = true, value = "language") String language) {
ObjectNode result = Json.newObject();
result = nlpComponent.tokenize(inputText, language, result);
return ok(result);
}
@javax.ws.rs.Path(value = "/nlp")
@ApiOperation(value = "performs different available nlp steps", notes = "different nlp steps are performed, currently: language detection, tokenization, NER and tfidf (top 10)")
public Result performNLP(
@ApiParam(value = "input text") String inputText) {
ObjectNode result = Json.newObject();
double dbpediaSpotlightConfidence = DBPediaSpotlightUtil.dbpediaspotlightdefaultConfidence; // TODO: make this conigurable
result = nlpComponent.performNLP(inputText, result, dbpediaSpotlightConfidence);
return ok(result);
}
@javax.ws.rs.Path(value = "/nlpForDeck")
@ApiOperation(
value = "performs different available nlp steps for content of deck",
notes = "different nlp steps are performed, currently: language detection, tokenization, NER, DBPedia Spotlight, tfidf (top 10) for tokens and dbPediaSpotlight")
@ApiResponses(
value = {
@ApiResponse(code = 404, message = "Problem while retrieving slides for given deck id via deck service. Slides for given deck id not found. Probably this deck id does not exist."),
@ApiResponse(code = 500, message = "Problem occured during calling spotlight service. For more information see details provided.")
})
public Result performNlpForDeck(
@ApiParam(required = true, value = "deckId") String deckId,
@ApiParam(required = true, defaultValue = "0.6", value = "dbpediaSpotlightConfidenceForSlide (use a value>1 to skip spotlight processing per slides)") double dbpediaSpotlightConfidenceForSlide,
@ApiParam(required = true, defaultValue = "0.6", value = "dbpediaSpotlightConfidenceForDeck (use a value>1 to skip spotlight processing per deck (=text of deck as input to spotlight). Spotlight per slide will be still processed.") double dbpediaSpotlightConfidenceForDeck) {
try{
ObjectNode resultNode = nlpComponent.processDeck(deckId, dbpediaSpotlightConfidenceForSlide, dbpediaSpotlightConfidenceForDeck);
Result r = Results.ok(resultNode);
return r;
}catch (WebApplicationException e) {
return createResultForExceptionalResponseCausedByWebApllicationException(e);
}catch(ProcessingException f){
String message = "Processing was interupted. Problem occured during Processing. For more information see details provided.";
return createResultForProcessingException(500, f, message);
}
}
@javax.ws.rs.Path(value = "/dbpediaspotlight")
@ApiOperation(
value = "returns results for dbpedia spotlight", // displayed next to path
notes = "returns result of dbpedia spotlight for the given input",// displayed under "Implementation notes"
nickname = "spotlight",
httpMethod = "GET"
)
@ApiResponses(
value = {
@ApiResponse(code = 400, message = "Please provide a confidence value in the range of 0 to 1"),
@ApiResponse(code = 500, message = "Problem occured during calling spotlight service. For more information see details provided.")}
)
public Result dbpediaSpotlight(
@ApiParam(required = true, value = "input text") String inputText,
@ApiParam(required = true, defaultValue = "0.6", value = "confidence (in range of 0 to 1, e.g. 0.6)") double confidence) {
Logger.debug("confidence set to " + confidence);
if(confidence>1 || confidence < 0 ){
return badRequest("Please provide a confidence value in the range of 0 to 1");
}
Response response;
try{
response = nlpComponent.performDBpediaSpotlight(inputText, confidence);
if(response.getStatus()!=200){
return createResultForResponseObject(response, "Problem occured during calling spotlight service. For more information see details provided.");
}else{
return createResultForResponseObject(response, "");
}
}catch(ProcessingException e){
return createResultForProcessingException(500, e, "Problem occured during calling spotlight service. For more information see details provided.");
}
}
/**
* Creates a Result for a {@link WebApplicationException} which is thrown when other called service do not return expected result.
* Creates a Result with the same status code like returned by the called service.
* @param e
* @return
*/
public static Result createResultForExceptionalResponseCausedByWebApllicationException(WebApplicationException e){
ObjectNode responseContent = Json.newObject();
String message = e.getMessage();
responseContent.put("message", message);
Response response = e.getResponse();
int status = response.getStatus();
responseContent.put("status", status);
String responseAsString = response.readEntity(String.class);
JsonNode responseAsJsonNode = Json.parse(responseAsString);
responseContent.set("Response", responseAsJsonNode);
Result result = Results.status(status, responseContent);
return result;
}
public static Result createResultForResponseObject(Response response, String optionalMessage){
ObjectNode responseContent = Json.newObject();
if(optionalMessage!=null && optionalMessage.length()>0){
responseContent.put("message", optionalMessage);
}
int status = response.getStatus();
responseContent.put("status", status);
String responseAsString = response.readEntity(String.class);
try{
JsonNode responseAsJsonNode = Json.parse(responseAsString);
responseContent.set("Response", responseAsJsonNode);
}
catch(RuntimeException e){// problem parsing json
responseContent.put("Response", responseAsString);
}
Result result = Results.status(status, responseContent);
return result;
}
public static Result createResultForProcessingException(int statusToReturn, Exception e, String optionalMessage){
ObjectNode responseContent = Json.newObject();
responseContent.put("status", statusToReturn);
if(optionalMessage!=null && optionalMessage.length()>0){
responseContent.put("message", optionalMessage);
}
responseContent.put("detailsErrorMessage", e.getMessage());
if(e.getCause()!=null){
responseContent.put("detailsErrorCause", e.getCause().toString());
}
return Results.status(statusToReturn, responseContent);
}
}
|
NLPController: added NLPStorageUtil
|
app/controllers/NLPController.java
|
NLPController: added NLPStorageUtil
|
|
Java
|
lgpl-2.1
|
54746c55d146f1d8906bad957de7e045cdc02b25
| 0
|
joshkh/intermine,tomck/intermine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,tomck/intermine,drhee/toxoMine,drhee/toxoMine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,JoeCarlson/intermine,zebrafishmine/intermine,elsiklab/intermine,tomck/intermine,elsiklab/intermine,elsiklab/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,elsiklab/intermine,joshkh/intermine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,tomck/intermine,justincc/intermine,justincc/intermine,joshkh/intermine,drhee/toxoMine,kimrutherford/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,zebrafishmine/intermine,JoeCarlson/intermine,joshkh/intermine,elsiklab/intermine,drhee/toxoMine,JoeCarlson/intermine,drhee/toxoMine,zebrafishmine/intermine,zebrafishmine/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,tomck/intermine,elsiklab/intermine,zebrafishmine/intermine,JoeCarlson/intermine,justincc/intermine,drhee/toxoMine,kimrutherford/intermine,justincc/intermine,kimrutherford/intermine,joshkh/intermine,elsiklab/intermine,JoeCarlson/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,JoeCarlson/intermine,kimrutherford/intermine
|
package samples;
/*
* Copyright (C) 2002-2009 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.webservice.client.core.ServiceFactory;
import org.intermine.webservice.client.services.ModelService;
import org.intermine.webservice.client.services.QueryService;
/**
* Calculate the coverage of BindingSites over Chromosomes.
*
* @author Matthew Wakeling
**/
public class ChromosomeCoverage
{
private static String serviceRootUrl = "http://intermine.modencode.org/release-14/service";
/**
* Executes a query and prints out the coverage of the given type of object over the given
* chromosomes.
*
* @param args command line arguments
*/
public static void main(String[] args) {
calculate("7227", "BindingSite", null);
}
private static void calculate(String taxonId, String featureType, String chromosomeId) {
QueryService service =
new ServiceFactory(serviceRootUrl, "ChromosomeCoverage").getQueryService();
Model model = getModel();
PathQuery query = new PathQuery(model);
query.setView("Chromosome.primaryIdentifier Chromosome.length");
query.addConstraint("Chromosome.organism.taxonId", Constraints.eq(taxonId));
if (chromosomeId != null) {
query.addConstraint("Chromosome.primaryIdentifier", Constraints.eq(chromosomeId));
}
List<List<String>> result = service.getResult(query, 100000);
Map<String, Integer> chromosomeSizes = new HashMap<String, Integer>();
for (List<String> row : result) {
if (row.size() == 2) {
chromosomeSizes.put(row.get(0), Integer.parseInt(row.get(1)));
}
}
query = new PathQuery(model);
query.setView(featureType + ".chromosome.primaryIdentifier " + featureType
+ ".chromosomeLocation.start " + featureType + ".chromosomeLocation.end");
query.setOrderBy(featureType + ".chromosome.primaryIdentifier " + featureType
+ ".chromosomeLocation.start");
query.addConstraint(featureType + ".chromosome.organism.taxonId", Constraints.eq(taxonId));
if (chromosomeId != null) {
query.addConstraint(featureType + ".chromosome.primaryIdentifier",
Constraints.eq(chromosomeId));
}
String currentChromosome = null;
int coverage = 0;
int lastEnd = Integer.MIN_VALUE;
int lastStart = Integer.MIN_VALUE;
result = service.getResult(query, 10000000);
if (result.size() >= 10000000) {
throw new IllegalArgumentException("There are too many rows for the web service");
}
for (List<String> row : result) {
String chromosome = row.get(0);
int start = Integer.parseInt(row.get(1));
int end = Integer.parseInt(row.get(2));
if ((currentChromosome != null) && !currentChromosome.equals(chromosome)) {
printStatus(currentChromosome, coverage, chromosomeSizes);
coverage = 0;
lastEnd = Integer.MIN_VALUE;
lastStart = Integer.MIN_VALUE;
}
currentChromosome = chromosome;
if (start < lastStart) {
throw new IllegalArgumentException("Features are not sorted by start position");
}
lastStart = start;
if (end > lastEnd) {
start = Math.max(start, lastEnd);
coverage += end - start;
lastEnd = end;
}
}
printStatus(currentChromosome, coverage, chromosomeSizes);
}
private static Model getModel() {
ModelService service = new ServiceFactory(serviceRootUrl, "ClientAPI").getModelService();
return service.getModel();
}
private static void printStatus(String chromosome, int coverage,
Map<String, Integer> chromosomeSizes) {
if (chromosomeSizes.containsKey(chromosome)) {
System.out.println("Chromosome " + chromosome + " has coverage " + coverage
+ " with size " + chromosomeSizes.get(chromosome)
+ " equals coverage of " + (Math.round(((10000.0 * coverage)
/ chromosomeSizes.get(chromosome))) / 100.0) + "%");
}
}
}
|
flymine-private/src/reports/ChromosomeCoverage/src/samples/ChromosomeCoverage.java
|
package samples;
/*
* Copyright (C) 2002-2009 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.webservice.client.core.ServiceFactory;
import org.intermine.webservice.client.services.ModelService;
import org.intermine.webservice.client.services.QueryService;
/**
* Calculate the coverage of BindingSites over Chromosomes.
*
* @author Matthew Wakeling
**/
public class ChromosomeCoverage
{
private static String serviceRootUrl = "http://intermine.modencode.org/release-14/service";
/**
*
* @param args command line arguments
* @throws IOException
*/
public static void main(String[] args) {
QueryService service =
new ServiceFactory(serviceRootUrl, "ChromosomeCoverage").getQueryService();
Model model = getModel();
PathQuery query = new PathQuery(model);
query.setView("Chromosome.primaryIdentifier Chromosome.length");
List<List<String>> result = service.getResult(query, 100000);
Map<String, Integer> chromosomeSizes = new HashMap<String, Integer>();
for (List<String> row : result) {
if (row.size() == 2) {
chromosomeSizes.put(row.get(0), Integer.parseInt(row.get(1)));
}
}
query = new PathQuery(model);
query.setView("BindingSite.chromosome.primaryIdentifier BindingSite.chromosomeLocation.start BindingSite.chromosomeLocation.end");
query.setOrderBy("BindingSite.chromosome.primaryIdentifier BindingSite.chromosomeLocation.start");
String currentChromosome = null;
int coverage = 0;
int lastEnd = Integer.MIN_VALUE;
int lastStart = Integer.MIN_VALUE;
result = service.getResult(query, 10000000);
if (result.size() >= 10000000) {
throw new IllegalArgumentException("There are too many rows for the web service");
}
for (List<String> row : result) {
String chromosome = row.get(0);
int start = Integer.parseInt(row.get(1));
int end = Integer.parseInt(row.get(2));
if ((currentChromosome != null) && !currentChromosome.equals(chromosome)) {
printStatus(currentChromosome, coverage, chromosomeSizes);
coverage = 0;
lastEnd = Integer.MIN_VALUE;
lastStart = Integer.MIN_VALUE;
}
currentChromosome = chromosome;
if (start < lastStart) {
throw new IllegalArgumentException("Features are not sorted by start position");
}
lastStart = start;
if (end > lastEnd) {
start = Math.max(start, lastEnd);
coverage += end - start;
lastEnd = end;
}
}
printStatus(currentChromosome, coverage, chromosomeSizes);
}
private static Model getModel() {
ModelService service = new ServiceFactory(serviceRootUrl, "ClientAPI").getModelService();
return service.getModel();
}
private static void printStatus(String chromosome, int coverage, Map<String, Integer> chromosomeSizes) {
if (chromosomeSizes.containsKey(chromosome)) {
System.out.println("Chromosome " + chromosome + " has coverage " + coverage
+ " with size " + chromosomeSizes.get(chromosome)
+ " equals coverage of "
+ (Math.round(((10000.0 * coverage) / chromosomeSizes.get(chromosome))) / 100.0) + "%");
}
}
}
|
Moved calculation into separate method.
|
flymine-private/src/reports/ChromosomeCoverage/src/samples/ChromosomeCoverage.java
|
Moved calculation into separate method.
|
|
Java
|
lgpl-2.1
|
a5edba19151ee79c8c7770f58bcdc906c0197407
| 0
|
pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.plugin.activitystream.eventstreambridge;
import java.net.MalformedURLException;
import java.net.URL;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.xwiki.component.annotation.Component;
import org.xwiki.eventstream.Event;
import org.xwiki.eventstream.EventFactory;
import org.xwiki.eventstream.EventStatus;
import org.xwiki.eventstream.internal.DefaultEventStatus;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.WikiReference;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEvent;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEventStatus;
import com.xpn.xwiki.plugin.activitystream.impl.ActivityEventImpl;
import com.xpn.xwiki.plugin.activitystream.impl.ActivityEventStatusImpl;
/**
* Internal helper that convert some objects from the Event Stream module to objects of the Activity Stream module
* (which is used for the storage) and the opposite.
*
* @version $Id$
* @since 9.2RC1
*/
@Component(roles = EventConverter.class)
@Singleton
public class EventConverter
{
/** Needed for creating raw events. */
@Inject
private EventFactory eventFactory;
/** Needed for serializing document names. */
@Inject
private EntityReferenceSerializer<String> serializer;
/** Needed for serializing the wiki and space references. */
@Inject
@Named("local")
private EntityReferenceSerializer<String> localSerializer;
/** Needed for deserializing document names. */
@Inject
private EntityReferenceResolver<String> resolver;
/** Needed for deserializing related entities. */
@Inject
@Named("explicit")
private EntityReferenceResolver<String> explicitResolver;
/**
* Converts a new {@link Event} to the old {@link ActivityEvent}.
*
* @param e the event to transform
* @return the equivalent activity event
*/
public ActivityEvent convertEventToActivity(Event e)
{
ActivityEvent result = new ActivityEventImpl();
result.setApplication(e.getApplication());
result.setBody(e.getBody());
result.setDate(e.getDate());
result.setEventId(e.getId());
result.setPage(this.localSerializer.serialize(e.getDocument()));
if (e.getDocumentTitle() != null) {
result.setParam1(e.getDocumentTitle());
}
if (e.getRelatedEntity() != null) {
result.setParam2(this.serializer.serialize(e.getRelatedEntity()));
}
result.setPriority((e.getImportance().ordinal() + 1) * 10);
result.setRequestId(e.getGroupId());
result.setSpace(this.localSerializer.serialize(e.getSpace()));
result.setStream(e.getStream());
result.setTitle(e.getTitle());
result.setType(e.getType());
if (e.getUrl() != null) {
result.setUrl(e.getUrl().toString());
}
result.setUser(this.serializer.serialize(e.getUser()));
result.setVersion(e.getDocumentVersion());
result.setWiki(this.serializer.serialize(e.getWiki()));
result.setParameters(e.getParameters());
result.setTarget(e.getTarget());
return result;
}
/**
* Convert an old {@link ActivityEvent} to the new {@link Event}.
*
* @param e the activity event to transform
* @return the equivalent event
*/
public Event convertActivityToEvent(ActivityEvent e)
{
Event result = this.eventFactory.createRawEvent();
result.setApplication(e.getApplication());
result.setBody(e.getBody());
result.setDate(e.getDate());
result.setDocument(new DocumentReference(this.resolver.resolve(e.getPage(), EntityType.DOCUMENT,
new WikiReference(e.getWiki()))));
result.setId(e.getEventId());
result.setDocumentTitle(e.getParam1());
if (StringUtils.isNotEmpty(e.getParam2())) {
if (StringUtils.endsWith(e.getType(), "Attachment")) {
result.setRelatedEntity(this.explicitResolver.resolve(e.getParam2(), EntityType.ATTACHMENT,
result.getDocument()));
} else if (StringUtils.endsWith(e.getType(), "Comment")
|| StringUtils.endsWith(e.getType(), "Annotation")) {
result.setRelatedEntity(this.explicitResolver.resolve(e.getParam2(), EntityType.OBJECT,
result.getDocument()));
}
}
result.setImportance(Event.Importance.MEDIUM);
if (e.getPriority() > 0) {
int priority = e.getPriority() / 10 - 1;
if (priority >= 0 && priority < Event.Importance.values().length) {
result.setImportance(Event.Importance.values()[priority]);
}
}
result.setGroupId(e.getRequestId());
result.setStream(e.getStream());
result.setTitle(e.getTitle());
result.setType(e.getType());
if (StringUtils.isNotBlank(e.getUrl())) {
try {
result.setUrl(new URL(e.getUrl()));
} catch (MalformedURLException ex) {
// Should not happen
}
}
result.setUser(new DocumentReference(this.resolver.resolve(e.getUser(), EntityType.DOCUMENT)));
result.setDocumentVersion(e.getVersion());
result.setParameters(e.getParameters());
return result;
}
/**
* Convert an {@link EventStatus} to an {@link ActivityEventStatus}.
*
* @param eventStatus the status to transform
* @return the equivalent activity event status
*/
public ActivityEventStatus convertEventStatusToActivityStatus(EventStatus eventStatus)
{
ActivityEventStatusImpl activityStatus = new ActivityEventStatusImpl();
activityStatus.setActivityEvent(convertEventToActivity(eventStatus.getEvent()));
activityStatus.setEntityId(eventStatus.getEntityId());
activityStatus.setRead(eventStatus.isRead());
return activityStatus;
}
/**
* Convert an {@link ActivityEventStatus} to an {@link EventStatus}.
*
* @param eventStatus the activity event status to transform
* @return the equivalent event status
*/
public EventStatus convertActivityStatusToEventStatus(ActivityEventStatus eventStatus)
{
return new DefaultEventStatus(
convertActivityToEvent(eventStatus.getActivityEvent()),
eventStatus.getEntityId(),
eventStatus.isRead()
);
}
}
|
xwiki-platform-core/xwiki-platform-activitystream/xwiki-platform-activitystream-api/src/main/java/com/xpn/xwiki/plugin/activitystream/eventstreambridge/EventConverter.java
|
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.plugin.activitystream.eventstreambridge;
import java.net.MalformedURLException;
import java.net.URL;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.xwiki.component.annotation.Component;
import org.xwiki.eventstream.Event;
import org.xwiki.eventstream.EventFactory;
import org.xwiki.eventstream.EventStatus;
import org.xwiki.eventstream.internal.DefaultEventStatus;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEvent;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEventStatus;
import com.xpn.xwiki.plugin.activitystream.impl.ActivityEventImpl;
import com.xpn.xwiki.plugin.activitystream.impl.ActivityEventStatusImpl;
/**
* Internal helper that convert some objects from the Event Stream module to objects of the Activity Stream module
* (which is used for the storage) and the opposite.
*
* @version $Id$
* @since 9.2RC1
*/
@Component(roles = EventConverter.class)
@Singleton
public class EventConverter
{
/** Needed for creating raw events. */
@Inject
private EventFactory eventFactory;
/** Needed for serializing document names. */
@Inject
private EntityReferenceSerializer<String> serializer;
/** Needed for serializing the wiki and space references. */
@Inject
@Named("local")
private EntityReferenceSerializer<String> localSerializer;
/** Needed for deserializing document names. */
@Inject
private EntityReferenceResolver<String> resolver;
/** Needed for deserializing related entities. */
@Inject
@Named("explicit")
private EntityReferenceResolver<String> explicitResolver;
/**
* Converts a new {@link Event} to the old {@link ActivityEvent}.
*
* @param e the event to transform
* @return the equivalent activity event
*/
public ActivityEvent convertEventToActivity(Event e)
{
ActivityEvent result = new ActivityEventImpl();
result.setApplication(e.getApplication());
result.setBody(e.getBody());
result.setDate(e.getDate());
result.setEventId(e.getId());
result.setPage(this.serializer.serialize(e.getDocument()));
if (e.getDocumentTitle() != null) {
result.setParam1(e.getDocumentTitle());
}
if (e.getRelatedEntity() != null) {
result.setParam2(this.serializer.serialize(e.getRelatedEntity()));
}
result.setPriority((e.getImportance().ordinal() + 1) * 10);
result.setRequestId(e.getGroupId());
result.setSpace(this.localSerializer.serialize(e.getSpace()));
result.setStream(e.getStream());
result.setTitle(e.getTitle());
result.setType(e.getType());
if (e.getUrl() != null) {
result.setUrl(e.getUrl().toString());
}
result.setUser(this.serializer.serialize(e.getUser()));
result.setVersion(e.getDocumentVersion());
result.setWiki(this.serializer.serialize(e.getWiki()));
result.setParameters(e.getParameters());
result.setTarget(e.getTarget());
return result;
}
/**
* Convert an old {@link ActivityEvent} to the new {@link Event}.
*
* @param e the activity event to transform
* @return the equivalent event
*/
public Event convertActivityToEvent(ActivityEvent e)
{
Event result = this.eventFactory.createRawEvent();
result.setApplication(e.getApplication());
result.setBody(e.getBody());
result.setDate(e.getDate());
result.setDocument(new DocumentReference(this.resolver.resolve(e.getPage(), EntityType.DOCUMENT)));
result.setId(e.getEventId());
result.setDocumentTitle(e.getParam1());
if (StringUtils.isNotEmpty(e.getParam2())) {
if (StringUtils.endsWith(e.getType(), "Attachment")) {
result.setRelatedEntity(this.explicitResolver.resolve(e.getParam2(), EntityType.ATTACHMENT,
result.getDocument()));
} else if (StringUtils.endsWith(e.getType(), "Comment")
|| StringUtils.endsWith(e.getType(), "Annotation")) {
result.setRelatedEntity(this.explicitResolver.resolve(e.getParam2(), EntityType.OBJECT,
result.getDocument()));
}
}
result.setImportance(Event.Importance.MEDIUM);
if (e.getPriority() > 0) {
int priority = e.getPriority() / 10 - 1;
if (priority >= 0 && priority < Event.Importance.values().length) {
result.setImportance(Event.Importance.values()[priority]);
}
}
result.setGroupId(e.getRequestId());
result.setStream(e.getStream());
result.setTitle(e.getTitle());
result.setType(e.getType());
if (StringUtils.isNotBlank(e.getUrl())) {
try {
result.setUrl(new URL(e.getUrl()));
} catch (MalformedURLException ex) {
// Should not happen
}
}
result.setUser(new DocumentReference(this.resolver.resolve(e.getUser(), EntityType.DOCUMENT)));
result.setDocumentVersion(e.getVersion());
result.setParameters(e.getParameters());
return result;
}
/**
* Convert an {@link EventStatus} to an {@link ActivityEventStatus}.
*
* @param eventStatus the status to transform
* @return the equivalent activity event status
*/
public ActivityEventStatus convertEventStatusToActivityStatus(EventStatus eventStatus)
{
ActivityEventStatusImpl activityStatus = new ActivityEventStatusImpl();
activityStatus.setActivityEvent(convertEventToActivity(eventStatus.getEvent()));
activityStatus.setEntityId(eventStatus.getEntityId());
activityStatus.setRead(eventStatus.isRead());
return activityStatus;
}
/**
* Convert an {@link ActivityEventStatus} to an {@link EventStatus}.
*
* @param eventStatus the activity event status to transform
* @return the equivalent event status
*/
public EventStatus convertActivityStatusToEventStatus(ActivityEventStatus eventStatus)
{
return new DefaultEventStatus(
convertActivityToEvent(eventStatus.getActivityEvent()),
eventStatus.getEntityId(),
eventStatus.isRead()
);
}
}
|
XWIKI-14172: Exception in the log when viewing the user profile after the install.
|
xwiki-platform-core/xwiki-platform-activitystream/xwiki-platform-activitystream-api/src/main/java/com/xpn/xwiki/plugin/activitystream/eventstreambridge/EventConverter.java
|
XWIKI-14172: Exception in the log when viewing the user profile after the install.
|
|
Java
|
lgpl-2.1
|
32b5b509d06b7ff7d38f67a2a3319dd82c5c5bc8
| 0
|
OlliV/titokone,titokone/koski,OlliV/titokone,titokone/titokone,dezgeg/titokone,titokone/titokone,titokone/koski
|
/** */
public class RunInfo extends DebugInfo{
public static final short NOOPERATION = 0;
public static final short DATA_TRANSFER_OPERATION = 1;
public static final short ALU_OPERATION = 2;
public static final short JUMP_OPERATION = 3;
public static final short STACK_OPERATION = 4;
public static final short SUB_OPERATION = 5;
public static final short SERVICE_OPERATION = 6;
public static final short IMMEDIATE = 0;
public static final short DIRECT = 1;
public static final short DIRECT_REGISTER = 2;
public static final short INDIRECT_REGISTER = 3;
public static final short INDEXED_DIRECT = 4;
public static final short INDEXED_INDIRECT= 5;
public static final short INDEXED_DIRECT_REGISTER = 6;
public static final short INDEXED_INDERECT_REGISTER = 7;
private int operationType;
/**This field contains line number.*/
private int lineNumber;
/** This field contains contents of the line, */
private String lineContents;
/** This field contains the command in binary format. */
private int binaryCommand;
private String statusMessage;
private String comments;
private int memoryFetchType;
private int numberOfMemoryfetches;
private int oldSP;
private int oldFP;
private int SP;
private int FP;
private int commandValue;
/** This field contains first operand of the command. */
private int Rj;
/** This field contains index register. */
private int Ri;
private String index;
private int aluResult;
private int[] registerArray;
public RunInfo(int lineNumber, String lineContents, int binary, int oldSP,
int oldFP, int SP, int FP){}
/** This method tells GUIBrain what kind of operation happened.
@returns int value which represents operation type.*/
public int whatOperationHappened(){}
/** This method tells GUIBrain what was statusMessage. */
public String returnStatusMessage(){}
/** This method tells GUIBrain what the comments were. */
public String returnComments(){}
/** This method returns both old and new SP and FP. */
public int[] returnPointers(){}
/** This methot tells GUIBrain how many memoryfetches were made. */
public int returnMemoryfetches(){}
/** This method tells what kind of memoryfetch was made.*/
public int returnFetchType(){}
/** */
Public int returnLineNumber(){}
/** */
public String returnLineContents(){}
/** */
public int returnBinaryCommand(){}
/** This method tells GUIBrain which registers changed and what is new
value.*/
public int[] whatRegisterChanged(){}
/** This method tells GUIBrain which line in data area changed and what is
new value.*/
public int[] whatMemoryLineChanged(){}
/** This method tells GUIBrain what was result of an OUT command (device and
value).*/
public int[] whatOUT(){}
/** This method tells GUIBrain what was result of an IN command (device and
*value.*/
public int[] whatIN(){}
public int[] returnAllRegisters(){}
public
}
|
RunInfo.java
|
/** */
public class RunInfo extends DebugInfo{
public static final short NOOPERATION = 0;
public static final short DATA_TRANSFER_OPERATION = 1;
public static final short ALU_OPERATION = 2;
public static final short JUMP_OPERATION = 3;
public static final short STACK_OPERATION = 4;
public static final short SUB_OPERATION = 5;
public static final short SERVICE_OPERATION = 6;
private int operationType;
/**This field contains line number.*/
private int lineNumber;
/** This field contains contents of the line, */
private String lineContents;
/** This field contains the command in binary format. */
private int binaryCommand;
private String statusMessage;
private String comments;
private int memoryFetchType;
private int oldSP;
private int oldFP;
private int SP;
private int FP;
private int commandValue;
/** This field contains first operand of the command. */
private int Rj;
/** This field contains index register. */
private int Ri;
private String index;
private int aluResult;
private int[] registerArray;
public RunInfo(int lineNumber, String lineContents, int binary, int oldSP,
int oldFP, int SP, int FP){}
/** This method tells GUIBrain what kind of operation happened.
@returns int value which represents operation type.*/
public int whatOperationHappened(){}
/** This method tells GUIBrain what was statusMessage. */
public String returnStatusMessage(){}
/** This method tells GUIBrain what the comments were. */
public String returnComments(){}
/** This method returns both old and new SP and FP. */
public int[] returnPointers(){}
/** */
Public int returnLineNumber(){}
/** */
public String returnLineContents(){}
/** */
public int returnBinaryCommand(){}
/** This method tells GUIBrain which registers changed and what is new
value.*/
public int[] whatRegisterChanged(){}
/** This method tells GUIBrain which line in data area changed and what is
new value.*/
public int[] whatMemoryLineChanged(){}
/** This method tells GUIBrain what was result of an OUT command (device and
value).*/
public int[] whatOUT(){}
/** This method tells GUIBrain what was result of an IN command (device and
*value.*/
public int[] whatIN(){}
public int[]
}
|
edited 1.3 2:03
|
RunInfo.java
|
edited 1.3 2:03
|
|
Java
|
lgpl-2.1
|
7c40964aba9ba82cf528b4497b6c0bff310fa04e
| 0
|
Anaphory/beast2,Anaphory/beast2,tgvaughan/beast2,CompEvol/beast2,tgvaughan/beast2,CompEvol/beast2,Anaphory/beast2,Anaphory/beast2,tgvaughan/beast2,CompEvol/beast2,CompEvol/beast2,tgvaughan/beast2
|
package beast.app.util;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
*/
public class Utils {
/**
* This function takes a file name and an array of extensions (specified
* without the leading '.'). If the file name ends with one of the extensions
* then it is returned with this trimmed off. Otherwise the file name is
* return as it is.
*
* @param fileName String
* @param extensions String[]
* @return the trimmed filename
*/
public static String trimExtensions(String fileName, String[] extensions) {
String newName = null;
for (String extension : extensions) {
final String ext = "." + extension;
if (fileName.toUpperCase().endsWith(ext.toUpperCase())) {
newName = fileName.substring(0, fileName.length() - ext.length());
}
}
return (newName != null) ? newName : fileName;
}
/**
* @param caller Object
* @param name String
* @return a named image from file or resource bundle.
*/
public static Image getImage(Object caller, String name) {
java.net.URL url = caller.getClass().getResource(name);
if (url != null) {
return Toolkit.getDefaultToolkit().createImage(url);
} else {
if (caller instanceof Component) {
Component c = (Component) caller;
Image i = c.createImage(100, 20);
Graphics g = c.getGraphics();
g.drawString("Not found!", 1, 15);
return i;
} else return null;
}
}
public static File getCWD() {
final String f = System.getProperty("user.dir");
return new File(f);
}
public static void loadUIManager() {
boolean lafLoaded = false;
if (isMac()) {
System.setProperty("apple.awt.graphics.UseQuartz", "true");
System.setProperty("apple.awt.antialiasing","true");
System.setProperty("apple.awt.rendering","VALUE_RENDER_QUALITY");
System.setProperty("apple.laf.useScreenMenuBar","true");
System.setProperty("apple.awt.draggableWindowBackground","true");
System.setProperty("apple.awt.showGrowBox","true");
try {
try {
// We need to do this using dynamic class loading to avoid other platforms
// having to link to this class. If the Quaqua library is not on the classpath
// it simply won't be used.
Class<?> qm = Class.forName("ch.randelshofer.quaqua.QuaquaManager");
Method method = qm.getMethod("setExcludedUIs", Set.class);
Set<String> excludes = new HashSet<String>();
excludes.add("Button");
excludes.add("ToolBar");
method.invoke(null, excludes);
}
catch (Throwable e) {
}
//set the Quaqua Look and Feel in the UIManager
UIManager.setLookAndFeel(
"ch.randelshofer.quaqua.QuaquaLookAndFeel"
);
lafLoaded = true;
} catch (Exception e) {
}
UIManager.put("SystemFont", new Font("Lucida Grande", Font.PLAIN, 13));
UIManager.put("SmallSystemFont", new Font("Lucida Grande", Font.PLAIN, 11));
}
try {
if (!lafLoaded) {
UIManager.setLookAndFeel("javax.swing.plaf.metal");
//UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception e) {
}
}
public static boolean isMac() {
return System.getProperty("os.name").toLowerCase().startsWith("mac");
}
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}
public static boolean isLinux() {
return System.getProperty("os.name").toLowerCase().startsWith("linux");
}
public static File getLoadFile(String message) {
return getLoadFile(message, null, null, (String[]) null);
}
public static File getSaveFile(String message) {
return getSaveFile(message, null, null, (String[]) null);
}
public static File getLoadFile(String message, File defaultFileOrDir, String description, final String... extensions) {
File [] files = getFile(message, true, defaultFileOrDir, false, description, extensions);
if (files == null) {
return null;
} else {
return files[0];
}
}
public static File getSaveFile(String message, File defaultFileOrDir, String description, final String... extensions) {
File [] files = getFile(message, false, defaultFileOrDir, false, description, extensions);
if (files == null) {
return null;
} else {
return files[0];
}
}
public static File [] getLoadFiles(String message, File defaultFileOrDir, String description, final String... extensions) {
return getFile(message, true, defaultFileOrDir, true, description, extensions);
}
public static File [] getSaveFiles(String message, File defaultFileOrDir, String description, final String... extensions) {
return getFile(message, false, defaultFileOrDir, true, description, extensions);
}
public static File [] getFile(String message, boolean bLoadNotSave, File defaultFileOrDir, boolean bAllowMultipleSelection, String description, final String... extensions) {
if (isMac()) {
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message,
(bLoadNotSave? java.awt.FileDialog.LOAD : java.awt.FileDialog.SAVE));
if (defaultFileOrDir != null) {
if (defaultFileOrDir.isDirectory()) {
chooser.setDirectory(defaultFileOrDir.getAbsolutePath());
} else {
chooser.setFile(defaultFileOrDir.getAbsolutePath());
}
}
if (description != null) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (int i = 0; i < extensions.length; i++) {
if (name.toLowerCase().endsWith(extensions[i].toLowerCase())) {
return true;
}
}
return false;
}
};
chooser.setFilenameFilter(filter);
}
// chooser.show();
chooser.setVisible(true);
if (chooser.getFile() == null) return null;
java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return new File[]{file};
} else {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
frame.setTitle(message);
final JFileChooser chooser = new JFileChooser(defaultFileOrDir);
chooser.setMultiSelectionEnabled(bAllowMultipleSelection);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (description != null) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
}
if (bLoadNotSave) {
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[]{chooser.getSelectedFile()};
}
}
} else {
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[]{chooser.getSelectedFile()};
}
}
}
}
return null;
}
}
|
src/beast/app/util/Utils.java
|
package beast.app.util;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
*/
public class Utils {
/**
* This function takes a file name and an array of extensions (specified
* without the leading '.'). If the file name ends with one of the extensions
* then it is returned with this trimmed off. Otherwise the file name is
* return as it is.
*
* @param fileName String
* @param extensions String[]
* @return the trimmed filename
*/
public static String trimExtensions(String fileName, String[] extensions) {
String newName = null;
for (String extension : extensions) {
final String ext = "." + extension;
if (fileName.toUpperCase().endsWith(ext.toUpperCase())) {
newName = fileName.substring(0, fileName.length() - ext.length());
}
}
return (newName != null) ? newName : fileName;
}
/**
* @param caller Object
* @param name String
* @return a named image from file or resource bundle.
*/
public static Image getImage(Object caller, String name) {
java.net.URL url = caller.getClass().getResource(name);
if (url != null) {
return Toolkit.getDefaultToolkit().createImage(url);
} else {
if (caller instanceof Component) {
Component c = (Component) caller;
Image i = c.createImage(100, 20);
Graphics g = c.getGraphics();
g.drawString("Not found!", 1, 15);
return i;
} else return null;
}
}
public static File getCWD() {
final String f = System.getProperty("user.dir");
return new File(f);
}
public static void loadUIManager() {
boolean lafLoaded = false;
if (isMac()) {
System.setProperty("apple.awt.graphics.UseQuartz", "true");
System.setProperty("apple.awt.antialiasing","true");
System.setProperty("apple.awt.rendering","VALUE_RENDER_QUALITY");
System.setProperty("apple.laf.useScreenMenuBar","true");
System.setProperty("apple.awt.draggableWindowBackground","true");
System.setProperty("apple.awt.showGrowBox","true");
try {
try {
// We need to do this using dynamic class loading to avoid other platforms
// having to link to this class. If the Quaqua library is not on the classpath
// it simply won't be used.
Class<?> qm = Class.forName("ch.randelshofer.quaqua.QuaquaManager");
Method method = qm.getMethod("setExcludedUIs", Set.class);
Set<String> excludes = new HashSet<String>();
excludes.add("Button");
excludes.add("ToolBar");
method.invoke(null, excludes);
}
catch (Throwable e) {
}
//set the Quaqua Look and Feel in the UIManager
UIManager.setLookAndFeel(
"ch.randelshofer.quaqua.QuaquaLookAndFeel"
);
lafLoaded = true;
} catch (Exception e) {
}
UIManager.put("SystemFont", new Font("Lucida Grande", Font.PLAIN, 13));
UIManager.put("SmallSystemFont", new Font("Lucida Grande", Font.PLAIN, 11));
}
try {
if (!lafLoaded) {
UIManager.setLookAndFeel("javax.swing.plaf.metal");
//UIManager.getSystemLookAndFeelClassName());
}
} catch (Exception e) {
}
}
public static boolean isMac() {
return !(isWindows() || isLinux());
//return jam.mac.Utils.isMacOSX();//System.getProperty("os.name").startsWith("Windows");
}
public static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}
public static boolean isLinux() {
return System.getProperty("os.name").toLowerCase().startsWith("linux");
}
public static File getLoadFile(String message) {
return getLoadFile(message, null, null, (String[]) null);
}
public static File getSaveFile(String message) {
return getSaveFile(message, null, null, (String[]) null);
}
public static File getLoadFile(String message, File defaultFileOrDir, String description, final String... extensions) {
File [] files = getFile(message, true, defaultFileOrDir, false, description, extensions);
if (files == null) {
return null;
} else {
return files[0];
}
}
public static File getSaveFile(String message, File defaultFileOrDir, String description, final String... extensions) {
File [] files = getFile(message, false, defaultFileOrDir, false, description, extensions);
if (files == null) {
return null;
} else {
return files[0];
}
}
public static File [] getLoadFiles(String message, File defaultFileOrDir, String description, final String... extensions) {
return getFile(message, true, defaultFileOrDir, true, description, extensions);
}
public static File [] getSaveFiles(String message, File defaultFileOrDir, String description, final String... extensions) {
return getFile(message, false, defaultFileOrDir, true, description, extensions);
}
public static File [] getFile(String message, boolean bLoadNotSave, File defaultFileOrDir, boolean bAllowMultipleSelection, String description, final String... extensions) {
if (isMac()) {
java.awt.Frame frame = new java.awt.Frame();
java.awt.FileDialog chooser = new java.awt.FileDialog(frame, message,
(bLoadNotSave? java.awt.FileDialog.LOAD : java.awt.FileDialog.SAVE));
if (defaultFileOrDir != null) {
if (defaultFileOrDir.isDirectory()) {
chooser.setDirectory(defaultFileOrDir.getAbsolutePath());
} else {
chooser.setFile(defaultFileOrDir.getAbsolutePath());
}
}
if (description != null) {
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
for (int i = 0; i < extensions.length; i++) {
if (name.toLowerCase().endsWith(extensions[i].toLowerCase())) {
return true;
}
}
return false;
}
};
chooser.setFilenameFilter(filter);
}
// chooser.show();
chooser.setVisible(true);
if (chooser.getFile() == null) return null;
java.io.File file = new java.io.File(chooser.getDirectory(), chooser.getFile());
chooser.dispose();
frame.dispose();
return new File[]{file};
} else {
// No file name in the arguments so throw up a dialog box...
java.awt.Frame frame = new java.awt.Frame();
frame.setTitle(message);
final JFileChooser chooser = new JFileChooser(defaultFileOrDir);
chooser.setMultiSelectionEnabled(bAllowMultipleSelection);
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if (description != null) {
FileNameExtensionFilter filter = new FileNameExtensionFilter(description, extensions);
chooser.setFileFilter(filter);
}
if (bLoadNotSave) {
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[]{chooser.getSelectedFile()};
}
}
} else {
if (chooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
frame.dispose();
if (bAllowMultipleSelection) {
return chooser.getSelectedFiles();
} else {
if (chooser.getSelectedFile() == null) {
return null;
}
return new File[]{chooser.getSelectedFile()};
}
}
}
}
return null;
}
}
|
More consistent isMac() function.
|
src/beast/app/util/Utils.java
|
More consistent isMac() function.
|
|
Java
|
apache-2.0
|
9eaf734dd0f219aef47afc9b518ec94919ff07ad
| 0
|
gregorydgraham/DBvolution
|
/*
* Copyright 2014 Gregory Graham.
*
* 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 nz.co.gregs.dbvolution.databases.definitions;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import nz.co.gregs.dbvolution.datatypes.DBBoolean;
import nz.co.gregs.dbvolution.datatypes.DBBooleanArray;
import nz.co.gregs.dbvolution.datatypes.DBDate;
import nz.co.gregs.dbvolution.datatypes.DBJavaObject;
import nz.co.gregs.dbvolution.datatypes.DBString;
import nz.co.gregs.dbvolution.datatypes.QueryableDatatype;
import nz.co.gregs.dbvolution.query.QueryOptions;
/**
* Defines the features of all Oracle databases that differ from the standard
* database.
*
* <p>
* This DBDefinition is sub-classed by {@link Oracle11DBDefinition} and
* {@link Oracle12DBDefinition} to provide the full set of features required to
* use an Oracle database.
*
* @author Gregory Graham
*/
public class OracleDBDefinition extends DBDefinition {
String dateFormatStr = "yyyy-M-d HH:mm:ss Z";
String oracleDateFormatStr = "YYYY-MM-DD HH24:MI:SS TZHTZM";
SimpleDateFormat javaToStringFormatter = new SimpleDateFormat(dateFormatStr);
private static final String[] reservedWordsArray = new String[]{"ACCESS", "ACCOUNT", "ACTIVATE", "ADD", "ADMIN", "ADVISE", "AFTER", "ALL", "ALL_ROWS", "ALLOCATE", "ALTER", "ANALYZE", "AND", "ANY", "ARCHIVE", "ARCHIVELOG", "ARRAY", "AS", "ASC", "AT", "AUDIT", "AUTHENTICATED", "AUTHORIZATION", "AUTOEXTEND", "AUTOMATIC", "BACKUP", "BECOME", "BEFORE", "BEGIN", "BETWEEN", "BFILE", "BITMAP", "BLOB", "BLOCK", "BODY", "BY", "CACHE", "CACHE_INSTANCES", "CANCEL", "CASCADE", "CAST", "CFILE", "CHAINED", "CHANGE", "CHAR", "CHAR_CS", "CHARACTER", "CHECK", "CHECKPOINT", "CHOOSE", "CHUNK", "CLEAR", "CLOB", "CLONE", "CLOSE", "CLOSE_CACHED_OPEN_CURSORS", "CLUSTER", "COALESCE", "COLUMN", "COLUMNS", "COMMENT", "COMMIT", "COMMITTED", "COMPATIBILITY", "COMPILE", "COMPLETE", "COMPOSITE_LIMIT", "COMPRESS", "COMPUTE", "CONNECT", "CONNECT_TIME", "CONSTRAINT", "CONSTRAINTS", "CONTENTS", "CONTINUE", "CONTROLFILE", "CONVERT", "COST", "CPU_PER_CALL", "CPU_PER_SESSION", "CREATE", "CURRENT", "CURRENT_SCHEMA", "CURREN_USER", "CURSOR", "CYCLE", "DANGLING", "DATABASE", "DATAFILE", "DATAFILES", "DATAOBJNO", "DATE", "DBA", "DBHIGH", "DBLOW", "DBMAC", "DEALLOCATE", "DEBUG", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DEGREE", "DELETE", "DEREF", "DESC", "DIRECTORY", "DISABLE", "DISCONNECT", "DISMOUNT", "DISTINCT", "DISTRIBUTED", "DML", "DOUBLE", "DROP", "DUMP", "EACH", "ELSE", "ENABLE", "END", "ENFORCE", "ENTRY", "ESCAPE", "EXCEPT", "EXCEPTIONS", "EXCHANGE", "EXCLUDING", "EXCLUSIVE", "EXECUTE", "EXISTS", "EXPIRE", "EXPLAIN", "EXTENT", "EXTENTS", "EXTERNALLY", "FAILED_LOGIN_ATTEMPTS", "FALSE", "FAST", "FILE", "FIRST_ROWS", "FLAGGER", "FLOAT", "FLOB", "FLUSH", "FOR", "FORCE", "FOREIGN", "FREELIST", "FREELISTS", "FROM", "FULL", "FUNCTION", "GLOBAL", "GLOBALLY", "GLOBAL_NAME", "GRANT", "GROUP", "GROUPS", "HASH", "HASHKEYS", "HAVING", "HEADER", "HEAP", "IDENTIFIED", "IDGENERATORS", "IDLE_TIME", "IF", "IMMEDIATE", "IN", "INCLUDING", "INCREMENT", "INDEX", "INDEXED", "INDEXES", "INDICATOR", "IND_PARTITION", "INITIAL", "INITIALLY", "INITRANS", "INSERT", "INSTANCE", "INSTANCES", "INSTEAD", "INT", "INTEGER", "INTERMEDIATE", "INTERSECT", "INTO", "IS", "ISOLATION", "ISOLATION_LEVEL", "KEEP", "KEY", "KILL", "LABEL", "LAYER", "LESS", "LEVEL", "LIBRARY", "LIKE", "LIMIT", "LINK", "LIST", "LOB", "LOCAL", "LOCK", "LOCKED", "LOG", "LOGFILE", "LOGGING", "LOGICAL_READS_PER_CALL", "LOGICAL_READS_PER_SESSION", "LONG", "MANAGE", "MASTER", "MAX", "MAXARCHLOGS", "MAXDATAFILES", "MAXEXTENTS", "MAXINSTANCES", "MAXLOGFILES", "MAXLOGHISTORY", "MAXLOGMEMBERS", "MAXSIZE", "MAXTRANS", "MAXVALUE", "MIN", "MEMBER", "MINIMUM", "MINEXTENTS", "MINUS", "MINVALUE", "MLSLABEL", "MLS_LABEL_FORMAT", "MODE", "MODIFY", "MOUNT", "MOVE", "MTS_DISPATCHERS", "MULTISET", "NATIONAL", "NCHAR", "NCHAR_CS", "NCLOB", "NEEDED", "NESTED", "NETWORK", "NEW", "NEXT", "NOARCHIVELOG", "NOAUDIT", "NOCACHE", "NOCOMPRESS", "NOCYCLE", "NOFORCE", "NOLOGGING", "NOMAXVALUE", "NOMINVALUE", "NONE", "NOORDER", "NOOVERRIDE", "NOPARALLEL", "NOPARALLEL", "NOREVERSE", "NORMAL", "NOSORT", "NOT", "NOTHING", "NOWAIT", "NULL", "NUMBER", "NUMERIC", "NVARCHAR2", "OBJECT", "OBJNO", "OBJNO_REUSE", "OF", "OFF", "OFFLINE", "OID", "OIDINDEX", "OLD", "ON", "ONLINE", "ONLY", "OPCODE", "OPEN", "OPTIMAL", "OPTIMIZER_GOAL", "OPTION", "OR", "ORDER", "ORGANIZATION", "OSLABEL", "OVERFLOW", "OWN", "PACKAGE", "PARALLEL", "PARTITION", "PASSWORD", "PASSWORD_GRACE_TIME", "PASSWORD_LIFE_TIME", "PASSWORD_LOCK_TIME", "PASSWORD_REUSE_MAX", "PASSWORD_REUSE_TIME", "PASSWORD_VERIFY_FUNCTION", "PCTFREE", "PCTINCREASE", "PCTTHRESHOLD", "PCTUSED", "PCTVERSION", "PERCENT", "PERMANENT", "PLAN", "PLSQL_DEBUG", "POST_TRANSACTION", "PRECISION", "PRESERVE", "PRIMARY", "PRIOR", "PRIVATE", "PRIVATE_SGA", "PRIVILEGE", "PRIVILEGES", "PROCEDURE", "PROFILE", "PUBLIC", "PURGE", "QUEUE", "QUOTA", "RANGE", "RAW", "RBA", "READ", "READUP", "REAL", "REBUILD", "RECOVER", "RECOVERABLE", "RECOVERY", "REF", "REFERENCES", "REFERENCING", "REFRESH", "RENAME", "REPLACE", "RESET", "RESETLOGS", "RESIZE", "RESOURCE", "RESTRICTED", "RETURN", "RETURNING", "REUSE", "REVERSE", "REVOKE", "ROLE", "ROLES", "ROLLBACK", "ROW", "ROWID", "ROWNUM", "ROWS", "RULE", "SAMPLE", "SAVEPOINT", "SB4", "SCAN_INSTANCES", "SCHEMA", "SCN", "SCOPE", "SD_ALL", "SD_INHIBIT", "SD_SHOW", "SEGMENT", "SEG_BLOCK", "SEG_FILE", "SELECT", "SEQUENCE", "SERIALIZABLE", "SESSION", "SESSION_CACHED_CURSORS", "SESSIONS_PER_USER", "SET", "SHARE", "SHARED", "SHARED_POOL", "SHRINK", "SIZE", "SKIP", "SKIP_UNUSABLE_INDEXES", "SMALLINT", "SNAPSHOT", "SOME", "SORT", "SPECIFICATION", "SPLIT", "SQL_TRACE", "STANDBY", "START", "STATEMENT_ID", "STATISTICS", "STOP", "STORAGE", "STORE", "STRUCTURE", "SUCCESSFUL", "SWITCH", "SYS_OP_ENFORCE_NOT_NULL$", "SYS_OP_NTCIMG$", "SYNONYM", "SYSDATE", "SYSDBA", "SYSOPER", "SYSTEM", "TABLE", "TABLES", "TABLESPACE", "TABLESPACE_NO", "TABNO", "TEMPORARY", "THAN", "THE", "THEN", "THREAD", "TIMESTAMP", "TIME", "TO", "TOPLEVEL", "TRACE", "TRACING", "TRANSACTION", "TRANSITIONAL", "TRIGGER", "TRIGGERS", "TRUE", "TRUNCATE", "TX", "TYPE", "UB2", "UBA", "UID", "UNARCHIVED", "UNDO", "UNION", "UNIQUE", "UNLIMITED", "UNLOCK", "UNRECOVERABLE", "UNTIL", "UNUSABLE", "UNUSED", "UPDATABLE", "UPDATE", "USAGE", "USE", "USER", "USING", "VALIDATE", "VALIDATION", "VALUE", "VALUES", "VARCHAR", "VARCHAR2", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WITHOUT", "WORK", "WRITE", "WRITEDOWN", "WRITEUP", "XID", "YEAR", "ZONE"};
private static final List<String> reservedWords = Arrays.asList(reservedWordsArray);
@Override
public String getDateFormattedForQuery(Date date) {
if (date == null) {
return getNull();
}
// yyyy-MM-dd hh:mm:ss[.nnnnnnnnn]
return " TO_TIMESTAMP_TZ('" + javaToStringFormatter.format(date) + "','" + oracleDateFormatStr + "') ";
//return "'"+strToDateFormat.format(date)+"'";
}
@Override
protected String formatNameForDatabase(final String sqlObjectName) {
if (sqlObjectName.length() < 30 && !(reservedWords.contains(sqlObjectName.toUpperCase()))) {
return sqlObjectName.replaceAll("^[_-]", "O").replaceAll("-", "_");
} else {
return ("O" + sqlObjectName.hashCode()).replaceAll("^[_-]", "O").replaceAll("-", "_");
}
}
@Override
public String formatTableAlias(String suggestedTableAlias) {
return "\"" + suggestedTableAlias.replaceAll("-", "_") + "\"";
}
@Override
public String formatForColumnAlias(final String actualName) {
String formattedName = actualName.replaceAll("\\.", "__");
return ("DB" + formattedName.hashCode()).replaceAll("-", "_") + "";
}
@Override
public String beginTableAlias() {
return " ";
}
@Override
public String getSQLTypeOfDBDatatype(QueryableDatatype qdt) {
if (qdt instanceof DBBoolean) {
return " NUMBER(1)";
} else if (qdt instanceof DBString) {
return " VARCHAR(1000) ";
} else if (qdt instanceof DBDate) {
return " TIMESTAMP ";
} else if (qdt instanceof DBJavaObject) {
return " BLOB ";
} else if (qdt instanceof DBBooleanArray) {
return " VARCHAR(64) ";
} else {
return qdt.getSQLDatatype();
}
}
@Override
public boolean supportsArraysNatively() {
return false;
}
// @Override
// public boolean prefersIndexBasedGroupByClause() {
// return true;
// }
@Override
public Object endSQLStatement() {
return "";
}
@Override
public String endInsertLine() {
return "";
}
@Override
public String endDeleteLine() {
return "";
}
@Override
public Object getLimitRowsSubClauseAfterWhereClause(QueryOptions options) {
return "";
}
@Override
public String getCurrentUserFunctionName() {
return "USER";
}
@Override
public String doPositionInStringTransform(String originalString, String stringToFind) {
return "INSTR(" + originalString + "," + stringToFind + ")";
}
@Override
public String getIfNullFunctionName() {
return "NVL"; //To change body of generated methods, choose Tools | Templates.
}
@Override
public String doStringIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return "DECODE(" + possiblyNullValue + ","
+ "NULL," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ ",''," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ "," + possiblyNullValue + ")";
}
@Override
public String doNumberIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return "DECODE(" + possiblyNullValue
+ ",NULL," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ "," + possiblyNullValue + ")";
}
@Override
public String doDateIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return doNumberIfNullTransform(possiblyNullValue, alternativeIfNull);
}
@Override
public String getStringLengthFunctionName() {
return "LENGTH";
}
@Override
public String doSubstringTransform(String originalString, String start, String length) {
return " SUBSTR("
+ originalString
+ ", "
+ start
+ (length.trim().isEmpty() ? "" : ", " + length)
+ ") ";
}
@Override
public boolean supportsRadiansFunction() {
return false;
}
@Override
public boolean supportsDegreesFunction() {
return false;
}
@Override
public String doModulusTransform(String firstNumber, String secondNumber) {
return " remainder(" + firstNumber + ", " + secondNumber + ")";
}
@Override
public String doAddSecondsTransform(String dateValue, String numberOfSeconds) {
return "(" + dateValue + " + numtodsinterval( " + numberOfSeconds + ", 'SECOND'))";
}
@Override
public String doAddMinutesTransform(String dateValue, String numberOfSeconds) {
return "(" + dateValue + " + numtodsinterval( " + numberOfSeconds + ", 'MINUTE'))";
}
@Override
public String doAddHoursTransform(String dateValue, String numberOfHours) {
return "(" + dateValue + " + numtodsinterval( " + numberOfHours + ", 'HOUR'))";
}
@Override
public String doAddDaysTransform(String dateValue, String numberOfDays) {
return "((" + dateValue + ")+(" + numberOfDays + "))";
}
@Override
public String doAddWeeksTransform(String dateValue, String numberOfWeeks) {
return doAddDaysTransform(dateValue, "(" + numberOfWeeks + ")*7");
}
@Override
public String doAddMonthsTransform(String dateValue, String numberOfMonths) {
return "ADD_MONTHS(" + dateValue + ", " + numberOfMonths + ")";
}
@Override
public String doAddYearsTransform(String dateValue, String numberOfYears) {
return doAddMonthsTransform(dateValue, "(" + numberOfYears + ")*12");
}
@Override
public String doCurrentDateOnlyTransform() {
return getCurrentDateOnlyFunctionName().trim();
}
@Override
public String doDayDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(DAY FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP))))";
}
@Override
public String doWeekDifferenceTransform(String dateValue, String otherDateValue) {
return "(" + doDayDifferenceTransform(dateValue, otherDateValue) + "/7)";
}
@Override
public String doMonthDifferenceTransform(String dateValue, String otherDateValue) {
return "MONTHS_BETWEEN(" + otherDateValue + "," + dateValue + ")";
}
@Override
public String doYearDifferenceTransform(String dateValue, String otherDateValue) {
return "(MONTHS_BETWEEN(" + otherDateValue + "," + dateValue + ")/12)";
}
@Override
public String doHourDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(HOUR FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doDayDifferenceTransform(dateValue, otherDateValue) + "*24))";
}
@Override
public String doMinuteDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(MINUTE FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doHourDifferenceTransform(dateValue, otherDateValue) + "*60))";
}
@Override
public String doSecondDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(SECOND FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doMinuteDifferenceTransform(dateValue, otherDateValue) + "*60))";
}
@Override
public String doMillisecondDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(MILLISECOND FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doSecondDifferenceTransform(dateValue, otherDateValue) + "*1000))";
}
@Override
public String doInTransform(String column, List<String> values) {
StringBuilder builder = new StringBuilder();
builder.append("(")
.append(column)
.append(" IN ( ");
String separator = "";
for (String val : values) {
if (val != null && !val.equals(getEmptyString())) {
builder.append(separator).append(val);
separator = ", ";
}
}
builder.append("))");
return builder.toString();
}
@Override
public Object getOrderByDirectionClause(Boolean sortOrder) {
if (sortOrder == null) {
return "";
} else if (sortOrder) {
return " ASC NULLS FIRST";
} else {
return " DESC NULLS LAST";
}
}
@Override
public String beginWithClause() {
return " WITH ";
}
@Override
public String doSelectFromRecursiveTable(String recursiveTableAlias, String recursiveAliases) {
return " SELECT " + recursiveAliases +", "+getRecursiveQueryDepthColumnName()+ " FROM " + recursiveTableAlias + " ORDER BY "+getRecursiveQueryDepthColumnName()+" ASC ";
}
/**
* Creates a pattern that will exclude system tables during DBRow class
* generation i.e. {@link DBTableClassGenerator}.
*
* <p>
* By default this method returns null as system tables are not a problem
* for most databases.
*
* @return
*/
@Override
public String getSystemTableExclusionPattern() {
return "^[^$]*$"; //"^(.*(?!\\$)\\b)*$";
}
@Override
public String doDayOfWeekTransform(String dateSQL) {
return " (TO_CHAR("+dateSQL+",'D')+1)";
}
@Override
public boolean supportsCotangentFunction() {
return false;
}
}
|
src/main/java/nz/co/gregs/dbvolution/databases/definitions/OracleDBDefinition.java
|
/*
* Copyright 2014 Gregory Graham.
*
* 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 nz.co.gregs.dbvolution.databases.definitions;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import nz.co.gregs.dbvolution.datatypes.DBBoolean;
import nz.co.gregs.dbvolution.datatypes.DBDate;
import nz.co.gregs.dbvolution.datatypes.DBJavaObject;
import nz.co.gregs.dbvolution.datatypes.DBString;
import nz.co.gregs.dbvolution.datatypes.QueryableDatatype;
import nz.co.gregs.dbvolution.query.QueryOptions;
/**
* Defines the features of all Oracle databases that differ from the standard
* database.
*
* <p>
* This DBDefinition is sub-classed by {@link Oracle11DBDefinition} and
* {@link Oracle12DBDefinition} to provide the full set of features required to
* use an Oracle database.
*
* @author Gregory Graham
*/
public class OracleDBDefinition extends DBDefinition {
String dateFormatStr = "yyyy-M-d HH:mm:ss Z";
String oracleDateFormatStr = "YYYY-MM-DD HH24:MI:SS TZHTZM";
SimpleDateFormat javaToStringFormatter = new SimpleDateFormat(dateFormatStr);
private static final String[] reservedWordsArray = new String[]{"ACCESS", "ACCOUNT", "ACTIVATE", "ADD", "ADMIN", "ADVISE", "AFTER", "ALL", "ALL_ROWS", "ALLOCATE", "ALTER", "ANALYZE", "AND", "ANY", "ARCHIVE", "ARCHIVELOG", "ARRAY", "AS", "ASC", "AT", "AUDIT", "AUTHENTICATED", "AUTHORIZATION", "AUTOEXTEND", "AUTOMATIC", "BACKUP", "BECOME", "BEFORE", "BEGIN", "BETWEEN", "BFILE", "BITMAP", "BLOB", "BLOCK", "BODY", "BY", "CACHE", "CACHE_INSTANCES", "CANCEL", "CASCADE", "CAST", "CFILE", "CHAINED", "CHANGE", "CHAR", "CHAR_CS", "CHARACTER", "CHECK", "CHECKPOINT", "CHOOSE", "CHUNK", "CLEAR", "CLOB", "CLONE", "CLOSE", "CLOSE_CACHED_OPEN_CURSORS", "CLUSTER", "COALESCE", "COLUMN", "COLUMNS", "COMMENT", "COMMIT", "COMMITTED", "COMPATIBILITY", "COMPILE", "COMPLETE", "COMPOSITE_LIMIT", "COMPRESS", "COMPUTE", "CONNECT", "CONNECT_TIME", "CONSTRAINT", "CONSTRAINTS", "CONTENTS", "CONTINUE", "CONTROLFILE", "CONVERT", "COST", "CPU_PER_CALL", "CPU_PER_SESSION", "CREATE", "CURRENT", "CURRENT_SCHEMA", "CURREN_USER", "CURSOR", "CYCLE", "DANGLING", "DATABASE", "DATAFILE", "DATAFILES", "DATAOBJNO", "DATE", "DBA", "DBHIGH", "DBLOW", "DBMAC", "DEALLOCATE", "DEBUG", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DEGREE", "DELETE", "DEREF", "DESC", "DIRECTORY", "DISABLE", "DISCONNECT", "DISMOUNT", "DISTINCT", "DISTRIBUTED", "DML", "DOUBLE", "DROP", "DUMP", "EACH", "ELSE", "ENABLE", "END", "ENFORCE", "ENTRY", "ESCAPE", "EXCEPT", "EXCEPTIONS", "EXCHANGE", "EXCLUDING", "EXCLUSIVE", "EXECUTE", "EXISTS", "EXPIRE", "EXPLAIN", "EXTENT", "EXTENTS", "EXTERNALLY", "FAILED_LOGIN_ATTEMPTS", "FALSE", "FAST", "FILE", "FIRST_ROWS", "FLAGGER", "FLOAT", "FLOB", "FLUSH", "FOR", "FORCE", "FOREIGN", "FREELIST", "FREELISTS", "FROM", "FULL", "FUNCTION", "GLOBAL", "GLOBALLY", "GLOBAL_NAME", "GRANT", "GROUP", "GROUPS", "HASH", "HASHKEYS", "HAVING", "HEADER", "HEAP", "IDENTIFIED", "IDGENERATORS", "IDLE_TIME", "IF", "IMMEDIATE", "IN", "INCLUDING", "INCREMENT", "INDEX", "INDEXED", "INDEXES", "INDICATOR", "IND_PARTITION", "INITIAL", "INITIALLY", "INITRANS", "INSERT", "INSTANCE", "INSTANCES", "INSTEAD", "INT", "INTEGER", "INTERMEDIATE", "INTERSECT", "INTO", "IS", "ISOLATION", "ISOLATION_LEVEL", "KEEP", "KEY", "KILL", "LABEL", "LAYER", "LESS", "LEVEL", "LIBRARY", "LIKE", "LIMIT", "LINK", "LIST", "LOB", "LOCAL", "LOCK", "LOCKED", "LOG", "LOGFILE", "LOGGING", "LOGICAL_READS_PER_CALL", "LOGICAL_READS_PER_SESSION", "LONG", "MANAGE", "MASTER", "MAX", "MAXARCHLOGS", "MAXDATAFILES", "MAXEXTENTS", "MAXINSTANCES", "MAXLOGFILES", "MAXLOGHISTORY", "MAXLOGMEMBERS", "MAXSIZE", "MAXTRANS", "MAXVALUE", "MIN", "MEMBER", "MINIMUM", "MINEXTENTS", "MINUS", "MINVALUE", "MLSLABEL", "MLS_LABEL_FORMAT", "MODE", "MODIFY", "MOUNT", "MOVE", "MTS_DISPATCHERS", "MULTISET", "NATIONAL", "NCHAR", "NCHAR_CS", "NCLOB", "NEEDED", "NESTED", "NETWORK", "NEW", "NEXT", "NOARCHIVELOG", "NOAUDIT", "NOCACHE", "NOCOMPRESS", "NOCYCLE", "NOFORCE", "NOLOGGING", "NOMAXVALUE", "NOMINVALUE", "NONE", "NOORDER", "NOOVERRIDE", "NOPARALLEL", "NOPARALLEL", "NOREVERSE", "NORMAL", "NOSORT", "NOT", "NOTHING", "NOWAIT", "NULL", "NUMBER", "NUMERIC", "NVARCHAR2", "OBJECT", "OBJNO", "OBJNO_REUSE", "OF", "OFF", "OFFLINE", "OID", "OIDINDEX", "OLD", "ON", "ONLINE", "ONLY", "OPCODE", "OPEN", "OPTIMAL", "OPTIMIZER_GOAL", "OPTION", "OR", "ORDER", "ORGANIZATION", "OSLABEL", "OVERFLOW", "OWN", "PACKAGE", "PARALLEL", "PARTITION", "PASSWORD", "PASSWORD_GRACE_TIME", "PASSWORD_LIFE_TIME", "PASSWORD_LOCK_TIME", "PASSWORD_REUSE_MAX", "PASSWORD_REUSE_TIME", "PASSWORD_VERIFY_FUNCTION", "PCTFREE", "PCTINCREASE", "PCTTHRESHOLD", "PCTUSED", "PCTVERSION", "PERCENT", "PERMANENT", "PLAN", "PLSQL_DEBUG", "POST_TRANSACTION", "PRECISION", "PRESERVE", "PRIMARY", "PRIOR", "PRIVATE", "PRIVATE_SGA", "PRIVILEGE", "PRIVILEGES", "PROCEDURE", "PROFILE", "PUBLIC", "PURGE", "QUEUE", "QUOTA", "RANGE", "RAW", "RBA", "READ", "READUP", "REAL", "REBUILD", "RECOVER", "RECOVERABLE", "RECOVERY", "REF", "REFERENCES", "REFERENCING", "REFRESH", "RENAME", "REPLACE", "RESET", "RESETLOGS", "RESIZE", "RESOURCE", "RESTRICTED", "RETURN", "RETURNING", "REUSE", "REVERSE", "REVOKE", "ROLE", "ROLES", "ROLLBACK", "ROW", "ROWID", "ROWNUM", "ROWS", "RULE", "SAMPLE", "SAVEPOINT", "SB4", "SCAN_INSTANCES", "SCHEMA", "SCN", "SCOPE", "SD_ALL", "SD_INHIBIT", "SD_SHOW", "SEGMENT", "SEG_BLOCK", "SEG_FILE", "SELECT", "SEQUENCE", "SERIALIZABLE", "SESSION", "SESSION_CACHED_CURSORS", "SESSIONS_PER_USER", "SET", "SHARE", "SHARED", "SHARED_POOL", "SHRINK", "SIZE", "SKIP", "SKIP_UNUSABLE_INDEXES", "SMALLINT", "SNAPSHOT", "SOME", "SORT", "SPECIFICATION", "SPLIT", "SQL_TRACE", "STANDBY", "START", "STATEMENT_ID", "STATISTICS", "STOP", "STORAGE", "STORE", "STRUCTURE", "SUCCESSFUL", "SWITCH", "SYS_OP_ENFORCE_NOT_NULL$", "SYS_OP_NTCIMG$", "SYNONYM", "SYSDATE", "SYSDBA", "SYSOPER", "SYSTEM", "TABLE", "TABLES", "TABLESPACE", "TABLESPACE_NO", "TABNO", "TEMPORARY", "THAN", "THE", "THEN", "THREAD", "TIMESTAMP", "TIME", "TO", "TOPLEVEL", "TRACE", "TRACING", "TRANSACTION", "TRANSITIONAL", "TRIGGER", "TRIGGERS", "TRUE", "TRUNCATE", "TX", "TYPE", "UB2", "UBA", "UID", "UNARCHIVED", "UNDO", "UNION", "UNIQUE", "UNLIMITED", "UNLOCK", "UNRECOVERABLE", "UNTIL", "UNUSABLE", "UNUSED", "UPDATABLE", "UPDATE", "USAGE", "USE", "USER", "USING", "VALIDATE", "VALIDATION", "VALUE", "VALUES", "VARCHAR", "VARCHAR2", "VARYING", "VIEW", "WHEN", "WHENEVER", "WHERE", "WITH", "WITHOUT", "WORK", "WRITE", "WRITEDOWN", "WRITEUP", "XID", "YEAR", "ZONE"};
private static final List<String> reservedWords = Arrays.asList(reservedWordsArray);
@Override
public String getDateFormattedForQuery(Date date) {
if (date == null) {
return getNull();
}
// yyyy-MM-dd hh:mm:ss[.nnnnnnnnn]
return " TO_TIMESTAMP_TZ('" + javaToStringFormatter.format(date) + "','" + oracleDateFormatStr + "') ";
//return "'"+strToDateFormat.format(date)+"'";
}
@Override
protected String formatNameForDatabase(final String sqlObjectName) {
if (sqlObjectName.length() < 30 && !(reservedWords.contains(sqlObjectName.toUpperCase()))) {
return sqlObjectName.replaceAll("^[_-]", "O").replaceAll("-", "_");
} else {
return ("O" + sqlObjectName.hashCode()).replaceAll("^[_-]", "O").replaceAll("-", "_");
}
}
@Override
public String formatTableAlias(String suggestedTableAlias) {
return "\"" + suggestedTableAlias.replaceAll("-", "_") + "\"";
}
@Override
public String formatForColumnAlias(final String actualName) {
String formattedName = actualName.replaceAll("\\.", "__");
return ("DB" + formattedName.hashCode()).replaceAll("-", "_") + "";
}
@Override
public String beginTableAlias() {
return " ";
}
@Override
public String getSQLTypeOfDBDatatype(QueryableDatatype qdt) {
if (qdt instanceof DBBoolean) {
return " NUMBER(1)";
} else if (qdt instanceof DBString) {
return " VARCHAR(1000) ";
} else if (qdt instanceof DBDate) {
return " TIMESTAMP ";
} else if (qdt instanceof DBJavaObject) {
return " BLOB ";
} else {
return qdt.getSQLDatatype();
}
}
// @Override
// public boolean prefersIndexBasedGroupByClause() {
// return true;
// }
@Override
public Object endSQLStatement() {
return "";
}
@Override
public String endInsertLine() {
return "";
}
@Override
public String endDeleteLine() {
return "";
}
@Override
public Object getLimitRowsSubClauseAfterWhereClause(QueryOptions options) {
return "";
}
@Override
public String getCurrentUserFunctionName() {
return "USER";
}
@Override
public String doPositionInStringTransform(String originalString, String stringToFind) {
return "INSTR(" + originalString + "," + stringToFind + ")";
}
@Override
public String getIfNullFunctionName() {
return "NVL"; //To change body of generated methods, choose Tools | Templates.
}
@Override
public String doStringIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return "DECODE(" + possiblyNullValue + ","
+ "NULL," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ ",''," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ "," + possiblyNullValue + ")";
}
@Override
public String doNumberIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return "DECODE(" + possiblyNullValue
+ ",NULL," + (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ "," + possiblyNullValue + ")";
}
@Override
public String doDateIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return doNumberIfNullTransform(possiblyNullValue, alternativeIfNull);
}
@Override
public String getStringLengthFunctionName() {
return "LENGTH";
}
@Override
public String doSubstringTransform(String originalString, String start, String length) {
return " SUBSTR("
+ originalString
+ ", "
+ start
+ (length.trim().isEmpty() ? "" : ", " + length)
+ ") ";
}
@Override
public boolean supportsRadiansFunction() {
return false;
}
@Override
public boolean supportsDegreesFunction() {
return false;
}
@Override
public String doModulusTransform(String firstNumber, String secondNumber) {
return " remainder(" + firstNumber + ", " + secondNumber + ")";
}
@Override
public String doAddSecondsTransform(String dateValue, String numberOfSeconds) {
return "(" + dateValue + " + numtodsinterval( " + numberOfSeconds + ", 'SECOND'))";
}
@Override
public String doAddMinutesTransform(String dateValue, String numberOfSeconds) {
return "(" + dateValue + " + numtodsinterval( " + numberOfSeconds + ", 'MINUTE'))";
}
@Override
public String doAddHoursTransform(String dateValue, String numberOfHours) {
return "(" + dateValue + " + numtodsinterval( " + numberOfHours + ", 'HOUR'))";
}
@Override
public String doAddDaysTransform(String dateValue, String numberOfDays) {
return "((" + dateValue + ")+(" + numberOfDays + "))";
}
@Override
public String doAddWeeksTransform(String dateValue, String numberOfWeeks) {
return doAddDaysTransform(dateValue, "(" + numberOfWeeks + ")*7");
}
@Override
public String doAddMonthsTransform(String dateValue, String numberOfMonths) {
return "ADD_MONTHS(" + dateValue + ", " + numberOfMonths + ")";
}
@Override
public String doAddYearsTransform(String dateValue, String numberOfYears) {
return doAddMonthsTransform(dateValue, "(" + numberOfYears + ")*12");
}
@Override
public String doCurrentDateOnlyTransform() {
return getCurrentDateOnlyFunctionName().trim();
}
@Override
public String doDayDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(DAY FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP))))";
}
@Override
public String doWeekDifferenceTransform(String dateValue, String otherDateValue) {
return "(" + doDayDifferenceTransform(dateValue, otherDateValue) + "/7)";
}
@Override
public String doMonthDifferenceTransform(String dateValue, String otherDateValue) {
return "MONTHS_BETWEEN(" + otherDateValue + "," + dateValue + ")";
}
@Override
public String doYearDifferenceTransform(String dateValue, String otherDateValue) {
return "(MONTHS_BETWEEN(" + otherDateValue + "," + dateValue + ")/12)";
}
@Override
public String doHourDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(HOUR FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doDayDifferenceTransform(dateValue, otherDateValue) + "*24))";
}
@Override
public String doMinuteDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(MINUTE FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doHourDifferenceTransform(dateValue, otherDateValue) + "*60))";
}
@Override
public String doSecondDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(SECOND FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doMinuteDifferenceTransform(dateValue, otherDateValue) + "*60))";
}
@Override
public String doMillisecondDifferenceTransform(String dateValue, String otherDateValue) {
return "(EXTRACT(MILLISECOND FROM (CAST(" + otherDateValue + " AS TIMESTAMP) - CAST(" + dateValue + " AS TIMESTAMP)))"
+ "+(" + doSecondDifferenceTransform(dateValue, otherDateValue) + "*1000))";
}
@Override
public String doInTransform(String column, List<String> values) {
StringBuilder builder = new StringBuilder();
builder.append("(")
.append(column)
.append(" IN ( ");
String separator = "";
for (String val : values) {
if (val != null && !val.equals(getEmptyString())) {
builder.append(separator).append(val);
separator = ", ";
}
}
builder.append("))");
return builder.toString();
}
@Override
public Object getOrderByDirectionClause(Boolean sortOrder) {
if (sortOrder == null) {
return "";
} else if (sortOrder) {
return " ASC NULLS FIRST";
} else {
return " DESC NULLS LAST";
}
}
@Override
public String beginWithClause() {
return " WITH ";
}
@Override
public String doSelectFromRecursiveTable(String recursiveTableAlias, String recursiveAliases) {
return " SELECT " + recursiveAliases +", "+getRecursiveQueryDepthColumnName()+ " FROM " + recursiveTableAlias + " ORDER BY "+getRecursiveQueryDepthColumnName()+" ASC ";
}
/**
* Creates a pattern that will exclude system tables during DBRow class
* generation i.e. {@link DBTableClassGenerator}.
*
* <p>
* By default this method returns null as system tables are not a problem
* for most databases.
*
* @return
*/
@Override
public String getSystemTableExclusionPattern() {
return "^[^$]*$"; //"^(.*(?!\\$)\\b)*$";
}
@Override
public String doDayOfWeekTransform(String dateSQL) {
return " (TO_CHAR("+dateSQL+",'D')+1)";
}
@Override
public boolean supportsCotangentFunction() {
return false;
}
}
|
Possible fix for Oracle BooleanArray support
|
src/main/java/nz/co/gregs/dbvolution/databases/definitions/OracleDBDefinition.java
|
Possible fix for Oracle BooleanArray support
|
|
Java
|
apache-2.0
|
50e20ca0efcdef1c7a382b045ab5974485109058
| 0
|
apache/camel,cunningt/camel,pax95/camel,tdiesler/camel,christophd/camel,adessaigne/camel,pax95/camel,christophd/camel,christophd/camel,cunningt/camel,tadayosi/camel,pax95/camel,adessaigne/camel,apache/camel,apache/camel,pax95/camel,tdiesler/camel,tdiesler/camel,apache/camel,adessaigne/camel,cunningt/camel,christophd/camel,tdiesler/camel,tadayosi/camel,tadayosi/camel,cunningt/camel,adessaigne/camel,tdiesler/camel,pax95/camel,apache/camel,tadayosi/camel,adessaigne/camel,cunningt/camel,tadayosi/camel,pax95/camel,apache/camel,christophd/camel,christophd/camel,tadayosi/camel,adessaigne/camel,tdiesler/camel,cunningt/camel
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.catalog.impl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.camel.catalog.ConfigurationPropertiesValidationResult;
import org.apache.camel.catalog.EndpointValidationResult;
import org.apache.camel.catalog.JSonSchemaResolver;
import org.apache.camel.catalog.LanguageValidationResult;
import org.apache.camel.catalog.SuggestionStrategy;
import org.apache.camel.tooling.model.ApiMethodModel;
import org.apache.camel.tooling.model.ApiModel;
import org.apache.camel.tooling.model.BaseModel;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.tooling.model.DataFormatModel;
import org.apache.camel.tooling.model.EipModel;
import org.apache.camel.tooling.model.JsonMapper;
import org.apache.camel.tooling.model.LanguageModel;
import org.apache.camel.tooling.model.MainModel;
import org.apache.camel.tooling.model.OtherModel;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
/**
* Base class for both the runtime RuntimeCamelCatalog from camel-core and the complete CamelCatalog from camel-catalog.
*/
@SuppressWarnings("unused")
public abstract class AbstractCamelCatalog {
// CHECKSTYLE:OFF
private static final Pattern SYNTAX_PATTERN = Pattern.compile("([\\w.]+)");
private static final Pattern ENV_OR_SYS_PATTERN = Pattern.compile("\\{\\{(env|sys):\\w+\\}\\}");
private static final Pattern SYNTAX_DASH_PATTERN = Pattern.compile("([\\w.-]+)");
private static final Pattern COMPONENT_SYNTAX_PARSER = Pattern.compile("([^\\w-]*)([\\w-]+)");
private SuggestionStrategy suggestionStrategy;
private JSonSchemaResolver jsonSchemaResolver;
public String componentJSonSchema(String name) {
return jsonSchemaResolver.getComponentJSonSchema(name);
}
public String modelJSonSchema(String name) {
return getJSonSchemaResolver().getModelJSonSchema(name);
}
public EipModel eipModel(String name) {
String json = modelJSonSchema(name);
return json != null ? JsonMapper.generateEipModel(json) : null;
}
public ComponentModel componentModel(String name) {
String json = componentJSonSchema(name);
return json != null ? JsonMapper.generateComponentModel(json) : null;
}
public String dataFormatJSonSchema(String name) {
return getJSonSchemaResolver().getDataFormatJSonSchema(name);
}
public DataFormatModel dataFormatModel(String name) {
String json = dataFormatJSonSchema(name);
return json != null ? JsonMapper.generateDataFormatModel(json) : null;
}
public String languageJSonSchema(String name) {
// if we try to look method then its in the bean.json file
if ("method".equals(name)) {
name = "bean";
}
return getJSonSchemaResolver().getLanguageJSonSchema(name);
}
public LanguageModel languageModel(String name) {
String json = languageJSonSchema(name);
return json != null ? JsonMapper.generateLanguageModel(json) : null;
}
public String otherJSonSchema(String name) {
return getJSonSchemaResolver().getOtherJSonSchema(name);
}
public OtherModel otherModel(String name) {
String json = otherJSonSchema(name);
return json != null ? JsonMapper.generateOtherModel(json) : null;
}
public String mainJSonSchema() {
return getJSonSchemaResolver().getMainJsonSchema();
}
public MainModel mainModel() {
String json = mainJSonSchema();
return json != null ? JsonMapper.generateMainModel(json) : null;
}
public SuggestionStrategy getSuggestionStrategy() {
return suggestionStrategy;
}
public void setSuggestionStrategy(SuggestionStrategy suggestionStrategy) {
this.suggestionStrategy = suggestionStrategy;
}
public JSonSchemaResolver getJSonSchemaResolver() {
return jsonSchemaResolver;
}
public void setJSonSchemaResolver(JSonSchemaResolver resolver) {
this.jsonSchemaResolver = resolver;
}
public boolean validateTimePattern(String pattern) {
return validateDuration(pattern);
}
public EndpointValidationResult validateEndpointProperties(String uri) {
return validateEndpointProperties(uri, false, false, false);
}
public EndpointValidationResult validateEndpointProperties(String uri, boolean ignoreLenientProperties) {
return validateEndpointProperties(uri, ignoreLenientProperties, false, false);
}
public EndpointValidationResult validateProperties(String scheme, Map<String, String> properties) {
boolean lenient = Boolean.getBoolean(properties.getOrDefault("lenient", "false"));
return validateProperties(scheme, properties, lenient, false, false);
}
private EndpointValidationResult validateProperties(String scheme, Map<String, String> properties,
boolean lenient, boolean consumerOnly,
boolean producerOnly) {
EndpointValidationResult result = new EndpointValidationResult(scheme);
ComponentModel model = componentModel(scheme);
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getApiSyntax());
String key = properties.get(apiSyntax[0]);
String key2 = apiSyntax.length > 1 ? properties.get(apiSyntax[1]) : null;
Map<String, BaseOptionModel> apiProperties = extractApiProperties(model, key, key2);
rows.putAll(apiProperties);
}
// the dataformat component refers to a data format so lets add the properties for the selected
// data format to the list of rows
if ("dataformat".equals(scheme)) {
String dfName = properties.get("name");
if (dfName != null) {
DataFormatModel dfModel = dataFormatModel(dfName);
if (dfModel != null) {
dfModel.getOptions().forEach(o -> rows.put(o.getName(), o));
}
}
}
for (Map.Entry<String, String> property : properties.entrySet()) {
String value = property.getValue();
String originalName = property.getKey();
// the name may be using an optional prefix, so lets strip that because the options
// in the schema are listed without the prefix
String name = stripOptionalPrefixFromName(rows, originalName);
// the name may be using a prefix, so lets see if we can find the real property name
String propertyName = getPropertyNameFromNameWithPrefix(rows, name);
if (propertyName != null) {
name = propertyName;
}
BaseOptionModel row = rows.get(name);
if (row == null) {
// unknown option
// only add as error if the component is not lenient properties, or not stub component
// and the name is not a property placeholder for one or more values
boolean namePlaceholder = name.startsWith("{{") && name.endsWith("}}");
if (!namePlaceholder && !"stub".equals(scheme)) {
if (lenient) {
// as if we are lenient then the option is a dynamic extra option which we cannot validate
result.addLenient(name);
} else {
// its unknown
result.addUnknown(name);
if (suggestionStrategy != null) {
String[] suggestions = suggestionStrategy.suggestEndpointOptions(rows.keySet(), name);
if (suggestions != null) {
result.addUnknownSuggestions(name, suggestions);
}
}
}
}
} else {
if ("parameter".equals(row.getKind())) {
// consumer only or producer only mode for parameters
String label = row.getLabel();
if (consumerOnly) {
if (label != null && label.contains("producer")) {
// the option is only for producer so you cannot use it in consumer mode
result.addNotConsumerOnly(name);
}
} else if (producerOnly) {
if (label != null && label.contains("consumer")) {
// the option is only for consumer so you cannot use it in producer mode
result.addNotProducerOnly(name);
}
}
}
String prefix = row.getPrefix();
boolean valuePlaceholder = value.startsWith("{{") || value.startsWith("${") || value.startsWith("$simple{");
boolean lookup = value.startsWith("#") && value.length() > 1;
// we cannot evaluate multi values as strict as the others, as we don't know their expected types
boolean multiValue = prefix != null && originalName.startsWith(prefix)
&& row.isMultiValue();
// default value
Object defaultValue = row.getDefaultValue();
if (defaultValue != null) {
result.addDefaultValue(name, defaultValue.toString());
}
// is required but the value is empty
if (row.isRequired() && URISupport.isEmpty(value)) {
result.addRequired(name);
}
// is the option deprecated
boolean deprecated = row.isDeprecated();
if (deprecated) {
result.addDeprecated(name);
}
// is enum but the value is not within the enum range
// but we can only check if the value is not a placeholder
List<String> enums = row.getEnums();
if (!multiValue && !valuePlaceholder && !lookup && enums != null) {
boolean found = false;
for (String s : enums) {
String dashEC = StringHelper.camelCaseToDash(value);
String valueEC = StringHelper.asEnumConstantValue(value);
if (value.equalsIgnoreCase(s) || dashEC.equalsIgnoreCase(s) || valueEC.equalsIgnoreCase(s)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(name, value);
result.addInvalidEnumChoices(name, enums.toArray(new String[0]));
if (suggestionStrategy != null) {
Set<String> names = new LinkedHashSet<>(enums);
String[] suggestions = suggestionStrategy.suggestEndpointOptions(names, value);
if (suggestions != null) {
result.addInvalidEnumSuggestions(name, suggestions);
}
}
}
}
// is reference lookup of bean (not applicable for @UriPath, enums, or multi-valued)
if (!multiValue && enums == null && !"path".equals(row.getKind()) && "object".equals(row.getType())) {
// must start with # and be at least 2 characters
if (!value.startsWith("#") || value.length() <= 1) {
result.addInvalidReference(name, value);
}
}
// is boolean
if (!multiValue && !valuePlaceholder && !lookup && "boolean".equals(row.getType())) {
// value must be a boolean
boolean bool = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
if (!bool) {
result.addInvalidBoolean(name, value);
}
}
// is duration
if (!multiValue && !valuePlaceholder && !lookup && "duration".equals(row.getType())) {
// value must be convertable to a duration
boolean valid = validateDuration(value);
if (!valid) {
result.addInvalidDuration(name, value);
}
}
// is integer
if (!multiValue && !valuePlaceholder && !lookup && "integer".equals(row.getType())) {
// value must be an integer
boolean valid = validateInteger(value);
if (!valid) {
result.addInvalidInteger(name, value);
}
}
// is number
if (!multiValue && !valuePlaceholder && !lookup && "number".equals(row.getType())) {
// value must be an number
boolean valid = false;
try {
valid = !Double.valueOf(value).isNaN() || !Float.valueOf(value).isNaN();
} catch (Exception e) {
// ignore
}
if (!valid) {
result.addInvalidNumber(name, value);
}
}
}
}
// for api component then check that the apiName/methodName combo is valid
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getApiSyntax());
String key1 = properties.get(apiSyntax[0]);
String key2 = apiSyntax.length > 1 ? properties.get(apiSyntax[1]) : null;
if (key1 != null && key2 != null) {
ApiModel api = model.getApiOptions().stream().filter(o -> o.getName().equalsIgnoreCase(key1)).findFirst().orElse(null);
if (api == null) {
result.addInvalidEnum(apiSyntax[0], key1);
List<String> choices = model.getApiOptions().stream().map(ApiModel::getName).collect(Collectors.toList());
result.addInvalidEnumChoices(apiSyntax[0], choices.toArray(new String[choices.size()]));
} else {
// walk each method and match against its name/alias
boolean found = false;
for (ApiMethodModel m : api.getMethods()) {
String key3 = apiMethodAlias(api, m);
if (m.getName().equalsIgnoreCase(key2) || key2.equalsIgnoreCase(key3)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(apiSyntax[1], key2);
List<String> choices = api.getMethods().stream()
.map(m -> {
// favour using method alias in choices
String answer = apiMethodAlias(api, m);
if (answer == null) {
answer = m.getName();
}
return answer;
})
.collect(Collectors.toList());
result.addInvalidEnumChoices(apiSyntax[1], choices.toArray(new String[choices.size()]));
}
}
}
}
// now check if all required values are there, and that a default value does not exists
for (BaseOptionModel row : rows.values()) {
if (row.isRequired()) {
String name = row.getName();
Object value = properties.get(name);
if (URISupport.isEmpty(value)) {
value = row.getDefaultValue();
}
if (URISupport.isEmpty(value)) {
result.addRequired(name);
}
}
}
return result;
}
public EndpointValidationResult validateEndpointProperties(String uri, boolean ignoreLenientProperties, boolean consumerOnly, boolean producerOnly) {
try {
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
ComponentModel model = scheme != null ? componentModel(scheme) : null;
if (model == null) {
EndpointValidationResult result = new EndpointValidationResult(uri);
if (uri.startsWith("{{")) {
result.addIncapable(uri);
} else if (scheme != null) {
result.addUnknownComponent(scheme);
} else {
result.addUnknownComponent(uri);
}
return result;
}
Map<String, String> properties = endpointProperties(uri);
boolean lenient;
if (!model.isConsumerOnly() && !model.isProducerOnly() && consumerOnly) {
// lenient properties is not support in consumer only mode if the component can do both of them
lenient = false;
} else {
// only enable lenient properties if we should not ignore
lenient = !ignoreLenientProperties && model.isLenientProperties();
}
return validateProperties(scheme, properties, lenient, consumerOnly, producerOnly);
} catch (URISyntaxException e) {
EndpointValidationResult result = new EndpointValidationResult(uri);
result.addSyntaxError(e.getMessage());
return result;
}
}
public Map<String, String> endpointProperties(String uri) throws URISyntaxException {
// need to normalize uri first
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
// grab the syntax
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
String syntax = model.getSyntax();
String alternativeSyntax = model.getAlternativeSyntax();
if (syntax == null) {
throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema");
}
// only if we support alternative syntax, and the uri contains the username and password in the authority
// part of the uri, then we would need some special logic to capture that information and strip those
// details from the uri, so we can continue parsing the uri using the normal syntax
Map<String, String> userInfoOptions = new LinkedHashMap<>();
if (alternativeSyntax != null && alternativeSyntax.contains("@")) {
// clip the scheme from the syntax
alternativeSyntax = CatalogHelper.after(alternativeSyntax, ":");
// trim so only userinfo
int idx = alternativeSyntax.indexOf('@');
String fields = alternativeSyntax.substring(0, idx);
String[] names = fields.split(":");
// grab authority part and grab username and/or password
String authority = u.getAuthority();
if (authority != null && authority.contains("@")) {
String username = null;
String password = null;
// grab unserinfo part before @
String userInfo = authority.substring(0, authority.indexOf('@'));
String[] parts = userInfo.split(":");
if (parts.length == 2) {
username = parts[0];
password = parts[1];
} else {
// only username
username = userInfo;
}
// remember the username and/or password which we add later to the options
if (names.length == 2) {
userInfoOptions.put(names[0], username);
if (password != null) {
// password is optional
userInfoOptions.put(names[1], password);
}
}
}
}
// clip the scheme from the syntax
syntax = CatalogHelper.after(syntax, ":");
// clip the scheme from the uri
uri = CatalogHelper.after(uri, ":");
String uriPath = URISupport.stripQuery(uri);
// the uri path may use {{env:xxx}} or {{sys:xxx}} placeholders so ignore those
Matcher matcher = ENV_OR_SYS_PATTERN.matcher(uriPath);
uriPath = matcher.replaceAll("");
// strip user info from uri path
if (!userInfoOptions.isEmpty()) {
int idx = uriPath.indexOf('@');
if (idx > -1) {
uriPath = uriPath.substring(idx + 1);
}
}
// strip double slash in the start
if (uriPath != null && uriPath.startsWith("//")) {
uriPath = uriPath.substring(2);
}
// parse the syntax and find the names of each option
matcher = SYNTAX_PATTERN.matcher(syntax);
List<String> word = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
if (!scheme.equals(s)) {
word.add(s);
}
}
// parse the syntax and find each token between each option
String[] tokens = SYNTAX_PATTERN.split(syntax);
// find the position where each option start/end
List<String> word2 = new ArrayList<>();
int prev = 0;
int prevPath = 0;
// special for activemq/jms where the enum for destinationType causes a token issue as it includes a colon
// for 'temp:queue' and 'temp:topic' values
if ("activemq".equals(scheme) || "jms".equals(scheme)) {
if (uriPath.startsWith("temp:")) {
prevPath = 5;
}
}
for (String token : tokens) {
if (token.isEmpty()) {
continue;
}
// special for some tokens where :// can be used also, eg http://foo
int idx = -1;
int len = 0;
if (":".equals(token)) {
idx = uriPath.indexOf("://", prevPath);
len = 3;
}
if (idx == -1) {
idx = uriPath.indexOf(token, prevPath);
len = token.length();
}
if (idx > 0) {
String option = uriPath.substring(prev, idx);
word2.add(option);
prev = idx + len;
prevPath = prev;
}
}
// special for last or if we did not add anyone
if (prev > 0 || word2.isEmpty()) {
String option = uriPath.substring(prev);
word2.add(option);
}
boolean defaultValueAdded = false;
// now parse the uri to know which part isw what
Map<String, String> options = new LinkedHashMap<>();
// include the username and password from the userinfo section
if (!userInfoOptions.isEmpty()) {
options.putAll(userInfoOptions);
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// is this an api component then there may be additional options
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getSyntax());
int pos = word.indexOf(apiSyntax[0]);
if (pos != -1) {
String key = word2.size() > pos ? word2.get(pos) : null;
// key2 should be null as its fine to get all the options for api name
Map<String, BaseOptionModel> apiProperties = extractApiProperties(model, key, null);
rows.putAll(apiProperties);
}
}
// word contains the syntax path elements
Iterator<String> it = word2.iterator();
for (int i = 0; i < word.size(); i++) {
String key = word.get(i);
BaseOptionModel option = rows.get(key);
boolean allOptions = word.size() == word2.size();
// we have all options so no problem
if (allOptions) {
String value = it.next();
options.put(key, value);
} else {
// we have a little problem as we do not not have all options
if (!option.isRequired()) {
Object value = null;
boolean last = i == word.size() - 1;
if (last) {
// if its the last value then use it instead of the default value
value = it.hasNext() ? it.next() : null;
if (value != null) {
options.put(key, value.toString());
} else {
value = option.getDefaultValue();
}
}
if (value != null) {
options.put(key, value.toString());
defaultValueAdded = true;
}
} else {
String value = it.hasNext() ? it.next() : null;
if (value != null) {
options.put(key, value);
}
}
}
}
Map<String, String> answer = new LinkedHashMap<>();
// remove all options which are using default values and are not required
for (Map.Entry<String, String> entry : options.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
BaseOptionModel row = rows.get(key);
if (defaultValueAdded) {
boolean required = row.isRequired();
Object defaultValue = row.getDefaultValue();
if (!required && defaultValue != null) {
if (defaultValue.toString().equals(value)) {
continue;
}
}
}
// we should keep this in the answer
answer.put(key, value);
}
// now parse the uri parameters
Map<String, Object> parameters = URISupport.parseParameters(u);
// and covert the values to String so its JMX friendly
while (!parameters.isEmpty()) {
Map.Entry<String, Object> entry = parameters.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue() != null ? entry.getValue().toString() : "";
BaseOptionModel row = rows.get(key);
if (row != null && row.isMultiValue()) {
String prefix = row.getPrefix();
if (prefix != null) {
// extra all the multi valued options
Map<String, Object> values = URISupport.extractProperties(parameters, prefix);
// build a string with the extra multi valued options with the prefix and & as separator
String csb = values.entrySet().stream()
.map(multi -> prefix + multi.getKey() + "=" + (multi.getValue() != null ? multi.getValue().toString() : ""))
.collect(Collectors.joining("&"));
// append the extra multi-values to the existing (which contains the first multi value)
if (!csb.isEmpty()) {
value = value + "&" + csb;
}
}
}
answer.put(key, value);
// remove the parameter as we run in a while loop until no more parameters
parameters.remove(key);
}
return answer;
}
private Map<String, BaseOptionModel> extractApiProperties(ComponentModel model, String key, String key2) {
Map<String, BaseOptionModel> answer = new LinkedHashMap<>();
if (key != null) {
String matchKey = null;
String dashKey = StringHelper.camelCaseToDash(key);
String ecKey = StringHelper.asEnumConstantValue(key);
String dashKey2 = StringHelper.camelCaseToDash(key2);
String ecKey2 = StringHelper.asEnumConstantValue(key2);
for (ApiModel am : model.getApiOptions()) {
String aKey = am.getName();
if (aKey.equalsIgnoreCase("DEFAULT") || aKey.equalsIgnoreCase(key) || aKey.equalsIgnoreCase(ecKey) || aKey.equalsIgnoreCase(dashKey)) {
am.getMethods().stream()
.filter(m -> {
if (key2 == null) {
// no api method so match all
return true;
}
String name = m.getName();
if (name.equalsIgnoreCase(key2) || name.equalsIgnoreCase(ecKey2) || name.equalsIgnoreCase(dashKey2)) {
return true;
}
// is there an alias then we need to compute the alias key and compare against the key2
String key3 = apiMethodAlias(am, m);
if (key3 != null) {
String dashKey3 = StringHelper.camelCaseToDash(key3);
String ecKey3 = StringHelper.asEnumConstantValue(key3);
if (key2.equalsIgnoreCase(key3) || ecKey2.equalsIgnoreCase(ecKey3) || dashKey2.equalsIgnoreCase(dashKey3)) {
return true;
}
}
return false;
})
.forEach(m -> m.getOptions()
.forEach(o -> answer.put(o.getName(), o)));
}
}
}
return answer;
}
private static String apiMethodAlias(ApiModel api, ApiMethodModel method) {
String name = method.getName();
for (String alias : api.getAliases()) {
int pos = alias.indexOf('=');
String pattern = alias.substring(0, pos);
String aliasMethod = alias.substring(pos + 1);
// match ignore case
if (Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(name).matches()) {
return aliasMethod;
}
}
return null;
}
public Map<String, String> endpointLenientProperties(String uri) throws URISyntaxException {
// need to normalize uri first
// parse the uri
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// now parse the uri parameters
Map<String, Object> parameters = URISupport.parseParameters(u);
// all the known options
Set<String> names = rows.keySet();
Map<String, String> answer = new LinkedHashMap<>();
// and covert the values to String so its JMX friendly
parameters.forEach((k, v) -> {
String key = k;
String value = v != null ? v.toString() : "";
// is the key a prefix property
int dot = key.indexOf('.');
if (dot != -1) {
String prefix = key.substring(0, dot + 1); // include dot in prefix
String option = getPropertyNameFromNameWithPrefix(rows, prefix);
if (option == null || !rows.get(option).isMultiValue()) {
answer.put(key, value);
}
} else if (!names.contains(key)) {
answer.put(key, value);
}
});
return answer;
}
public String endpointComponentName(String uri) {
if (uri != null) {
int idx = uri.indexOf(':');
if (idx > 0) {
return uri.substring(0, idx);
}
}
return null;
}
public String asEndpointUri(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException {
return doAsEndpointUri(scheme, properties, "&", encode);
}
public String asEndpointUriXml(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException {
return doAsEndpointUri(scheme, properties, "&", encode);
}
String doAsEndpointUri(String scheme, Map<String, String> properties, String ampersand, boolean encode) throws URISyntaxException {
// grab the syntax
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
String originalSyntax = model.getSyntax();
if (originalSyntax == null) {
throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema");
}
// do any properties filtering which can be needed for some special components
properties = filterProperties(scheme, properties);
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// clip the scheme from the syntax
String syntax = "";
if (originalSyntax.contains(":")) {
originalSyntax = CatalogHelper.after(originalSyntax, ":");
}
// build at first according to syntax (use a tree map as we want the uri options sorted)
Map<String, String> copy = new TreeMap<>(properties);
Matcher syntaxMatcher = COMPONENT_SYNTAX_PARSER.matcher(originalSyntax);
while (syntaxMatcher.find()) {
syntax += syntaxMatcher.group(1);
String propertyName = syntaxMatcher.group(2);
String propertyValue = copy.remove(propertyName);
syntax += propertyValue != null ? propertyValue : propertyName;
}
// do we have all the options the original syntax needs (easy way)
String[] keys = syntaxKeys(originalSyntax);
boolean hasAllKeys = properties.keySet().containsAll(Arrays.asList(keys));
// build endpoint uri
StringBuilder sb = new StringBuilder();
// add scheme later as we need to take care if there is any context-path or query parameters which
// affect how the URI should be constructed
if (hasAllKeys) {
// we have all the keys for the syntax so we can build the uri the easy way
sb.append(syntax);
if (!copy.isEmpty()) {
// wrap secret values with RAW to avoid breaking URI encoding in case of encoded values
copy.replaceAll((key, val) -> {
if (val == null) {
return val;
}
BaseOptionModel option = rows.get(key);
if (option == null) {
return val;
}
if (option.isSecret() && !val.startsWith("#") && !val.startsWith("RAW(")) {
return "RAW(" + val + ")";
}
return val;
});
boolean hasQuestionMark = sb.toString().contains("?");
// the last option may already contain a ? char, if so we should use & instead of ?
sb.append(hasQuestionMark ? ampersand : '?');
String query = URISupport.createQueryString(copy, ampersand, encode);
sb.append(query);
}
} else {
// TODO: revisit this and see if we can do this in another way
// oh darn some options is missing, so we need a complex way of building the uri
// the tokens between the options in the path
String[] tokens = SYNTAX_DASH_PATTERN.split(syntax);
// parse the syntax into each options
Matcher matcher = SYNTAX_PATTERN.matcher(originalSyntax);
List<String> options = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
options.add(s);
}
// need to preserve {{ and }} from the syntax
// (we need to use words only as its provisional placeholders)
syntax = syntax.replace("{{", "BEGINCAMELPLACEHOLDER");
syntax = syntax.replace("}}", "ENDCAMELPLACEHOLDER");
// parse the syntax into each options
Matcher matcher2 = SYNTAX_DASH_PATTERN.matcher(syntax);
List<String> options2 = new ArrayList<>();
while (matcher2.find()) {
String s = matcher2.group(1);
s = s.replace("BEGINCAMELPLACEHOLDER", "{{");
s = s.replace("ENDCAMELPLACEHOLDER", "}}");
options2.add(s);
}
// build the endpoint
int range = 0;
boolean first = true;
boolean hasQuestionmark = false;
for (int i = 0; i < options.size(); i++) {
String key = options.get(i);
String key2 = options2.get(i);
String token = null;
if (tokens.length > i) {
token = tokens[i];
}
boolean contains = properties.containsKey(key);
if (!contains) {
// if the key are similar we have no explicit value and can try to find a default value if the option is required
BaseOptionModel row = rows.get(key);
if (row != null && row.isRequired()) {
Object value = row.getDefaultValue();
if (!URISupport.isEmpty(value)) {
properties.put(key, key2 = value.toString());
}
}
}
// was the option provided?
if (properties.containsKey(key)) {
if (!first && token != null) {
sb.append(token);
}
hasQuestionmark |= key.contains("?") || (token != null && token.contains("?"));
sb.append(key2);
first = false;
}
range++;
}
// append any extra options that was in surplus for the last
while (range < options2.size()) {
String token = null;
if (tokens.length > range) {
token = tokens[range];
}
String key2 = options2.get(range);
sb.append(token);
sb.append(key2);
hasQuestionmark |= key2.contains("?") || (token != null && token.contains("?"));
range++;
}
if (!copy.isEmpty()) {
// wrap secret values with RAW to avoid breaking URI encoding in case of encoded values
copy.replaceAll(new BiFunction<String, String, String>() {
@Override
public String apply(String key, String val) {
if (val == null) {
return val;
}
BaseOptionModel option = rows.get(key);
if (option == null) {
return val;
}
if (option.isSecret() && !val.startsWith("#") && !val.startsWith("RAW(")) {
return "RAW(" + val + ")";
}
return val;
}
});
// the last option may already contain a ? char, if so we should use & instead of ?
sb.append(hasQuestionmark ? ampersand : '?');
String query = URISupport.createQueryString(copy, ampersand, encode);
sb.append(query);
}
}
String remainder = sb.toString();
boolean queryOnly = remainder.startsWith("?");
if (queryOnly) {
// it has only query parameters
return scheme + remainder;
} else if (!remainder.isEmpty()) {
// it has context path and possible query parameters
return scheme + ":" + remainder;
} else {
// its empty without anything
return scheme;
}
}
private static String[] syntaxKeys(String syntax) {
// build tokens between the separators
List<String> tokens = new ArrayList<>();
if (syntax != null) {
StringBuilder current = new StringBuilder();
for (int i = 0; i < syntax.length(); i++) {
char ch = syntax.charAt(i);
if (Character.isLetterOrDigit(ch)) {
current.append(ch);
} else {
// reset for new current tokens
if (current.length() > 0) {
tokens.add(current.toString());
current = new StringBuilder();
}
}
}
// anything left over?
if (current.length() > 0) {
tokens.add(current.toString());
}
}
return tokens.toArray(new String[tokens.size()]);
}
public ConfigurationPropertiesValidationResult validateConfigurationProperty(String line) {
String longKey = CatalogHelper.before(line, "=");
String key = longKey;
String value = CatalogHelper.after(line, "=");
// trim values
if (longKey != null) {
longKey = longKey.trim();
}
if (key != null) {
key = key.trim();
}
if (value != null) {
value = value.trim();
}
ConfigurationPropertiesValidationResult result = new ConfigurationPropertiesValidationResult();
boolean accept = acceptConfigurationPropertyKey(key);
if (!accept) {
result.setAccepted(false);
return result;
} else {
result.setAccepted(true);
}
// skip camel.
key = key.substring("camel.".length());
Function<String, ? extends BaseModel<?>> loader = null;
if (key.startsWith("component.")) {
key = key.substring("component.".length());
loader = this::componentModel;
} else if (key.startsWith("dataformat.")) {
key = key.substring("dataformat.".length());
loader = this::dataFormatModel;
} else if (key.startsWith("language.")) {
key = key.substring("language.".length());
loader = this::languageModel;
}
if (loader != null) {
int idx = key.indexOf('.');
String name = key.substring(0, idx);
String option = key.substring(idx + 1);
if (value != null) {
BaseModel<?> model = loader.apply(name);
if (model == null) {
result.addUnknownComponent(name);
return result;
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getOptions().forEach(o -> rows.put(o.getName(), o));
// lower case option and remove dash
String nOption = option.replace("-", "").toLowerCase(Locale.ENGLISH);
String suffix = null;
int posDot = nOption.indexOf('.');
int posBracket = nOption.indexOf('[');
if (posDot > 0 && posBracket > 0) {
int first = Math.min(posDot, posBracket);
suffix = nOption.substring(first);
nOption = nOption.substring(0, first);
} else if (posDot > 0) {
suffix = nOption.substring(posDot);
nOption = nOption.substring(0, posDot);
} else if (posBracket > 0) {
suffix = nOption.substring(posBracket);
nOption = nOption.substring(0, posBracket);
}
doValidateConfigurationProperty(result, rows, name, value, longKey, nOption, suffix);
}
} else if (key.startsWith("main.")
|| key.startsWith("hystrix.")
|| key.startsWith("resilience4j.")
|| key.startsWith("faulttolerance.")
|| key.startsWith("threadpool.")
|| key.startsWith("lra.")
|| key.startsWith("health.")
|| key.startsWith("rest.")) {
int idx = key.indexOf('.');
String name = key.substring(0, idx);
String option = key.substring(idx + 1);
if (value != null) {
MainModel model = mainModel();
if (model == null) {
result.addIncapable("camel-main not detected on classpath");
return result;
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getOptions().forEach(o -> rows.put(dashToCamelCase(o.getName()), o));
// lower case option and remove dash
String nOption = longKey.replace("-", "").toLowerCase(Locale.ENGLISH);
// look for suffix or array index after 2nd dot
int secondDot = nOption.indexOf('.', nOption.indexOf('.') + 1) + 1;
String suffix = null;
int posDot = nOption.indexOf('.', secondDot);
int posBracket = nOption.indexOf('[', secondDot);
if (posDot > 0 && posBracket > 0) {
int first = Math.min(posDot, posBracket);
suffix = nOption.substring(first);
nOption = nOption.substring(0, first);
} else if (posDot > 0) {
suffix = nOption.substring(posDot);
nOption = nOption.substring(0, posDot);
} else if (posBracket > 0) {
suffix = nOption.substring(posBracket);
nOption = nOption.substring(0, posBracket);
}
doValidateConfigurationProperty(result, rows, name, value, longKey, nOption, suffix);
}
}
return result;
}
private void doValidateConfigurationProperty(ConfigurationPropertiesValidationResult result,
Map<String, BaseOptionModel> rows,
String name, String value, String longKey,
String lookupKey, String suffix) {
// find option
String rowKey = rows.keySet().stream()
.filter(n -> n.toLowerCase(Locale.ENGLISH).equals(lookupKey)).findFirst().orElse(null);
if (rowKey == null) {
// unknown option
result.addUnknown(longKey);
if (suggestionStrategy != null) {
String[] suggestions = suggestionStrategy.suggestEndpointOptions(rows.keySet(), name);
if (suggestions != null) {
result.addUnknownSuggestions(name, suggestions);
}
}
} else {
boolean optionPlaceholder = value.startsWith("{{") || value.startsWith("${") || value.startsWith("$simple{");
boolean lookup = value.startsWith("#") && value.length() > 1;
// deprecated
BaseOptionModel row = rows.get(rowKey);
if (!optionPlaceholder && !lookup && row.isDeprecated()) {
result.addDeprecated(longKey);
}
// is boolean
if (!optionPlaceholder && !lookup && "boolean".equals(row.getType())) {
// value must be a boolean
boolean bool = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
if (!bool) {
result.addInvalidBoolean(longKey, value);
}
}
// is duration
if (!optionPlaceholder && !lookup && "duration".equals(row.getType())) {
// value must be convertable to a duration
boolean valid = validateDuration(value);
if (!valid) {
result.addInvalidDuration(longKey, value);
}
}
// is integer
if (!optionPlaceholder && !lookup && "integer".equals(row.getType())) {
// value must be an integer
boolean valid = validateInteger(value);
if (!valid) {
result.addInvalidInteger(longKey, value);
}
}
// is number
if (!optionPlaceholder && !lookup && "number".equals(row.getType())) {
// value must be an number
boolean valid = false;
try {
valid = !Double.valueOf(value).isNaN() || !Float.valueOf(value).isNaN();
} catch (Exception e) {
// ignore
}
if (!valid) {
result.addInvalidNumber(longKey, value);
}
}
// is enum
List<String> enums = row.getEnums();
if (!optionPlaceholder && !lookup && enums != null) {
boolean found = false;
String dashEC = StringHelper.camelCaseToDash(value);
String valueEC = StringHelper.asEnumConstantValue(value);
for (String s : enums) {
// equals as is or using the enum naming style
if (value.equalsIgnoreCase(s) || dashEC.equalsIgnoreCase(s) || valueEC.equalsIgnoreCase(s)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(longKey, value);
result.addInvalidEnumChoices(longKey, enums.toArray(new String[0]));
if (suggestionStrategy != null) {
Set<String> names = new LinkedHashSet<>(enums);
String[] suggestions = suggestionStrategy.suggestEndpointOptions(names, value);
if (suggestions != null) {
result.addInvalidEnumSuggestions(longKey, suggestions);
}
}
}
}
String javaType = row.getJavaType();
if (!optionPlaceholder && !lookup && javaType != null
&& (javaType.startsWith("java.util.Map") || javaType.startsWith("java.util.Properties"))) {
// there must be a valid suffix
if (suffix == null || suffix.isEmpty() || suffix.equals(".")) {
result.addInvalidMap(longKey, value);
} else if (suffix.startsWith("[") && !suffix.contains("]")) {
result.addInvalidMap(longKey, value);
}
}
if (!optionPlaceholder && !lookup && javaType != null && "array".equals(row.getType())) {
// there must be a suffix and it must be using [] style
if (suffix == null || suffix.isEmpty() || suffix.equals(".")) {
result.addInvalidArray(longKey, value);
} else if (!suffix.startsWith("[") && !suffix.contains("]")) {
result.addInvalidArray(longKey, value);
} else {
String index = CatalogHelper.before(suffix.substring(1), "]");
// value must be an integer
boolean valid = validateInteger(index);
if (!valid) {
result.addInvalidInteger(longKey, index);
}
}
}
}
}
private static boolean acceptConfigurationPropertyKey(String key) {
if (key == null) {
return false;
}
return key.startsWith("camel.component.")
|| key.startsWith("camel.dataformat.")
|| key.startsWith("camel.language.")
|| key.startsWith("camel.main.")
|| key.startsWith("camel.hystrix.")
|| key.startsWith("camel.resilience4j.")
|| key.startsWith("camel.faulttolerance.")
|| key.startsWith("camel.threadpool.")
|| key.startsWith("camel.health.")
|| key.startsWith("camel.lra.")
|| key.startsWith("camel.rest.");
}
private LanguageValidationResult doValidateSimple(ClassLoader classLoader, String simple, boolean predicate) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
// if there are {{ }}} property placeholders then we need to resolve them to something else
// as the simple parse cannot resolve them before parsing as we dont run the actual Camel application
// with property placeholders setup so we need to dummy this by replace the {{ }} to something else
// therefore we use an more unlikely character: {{XXX}} to ~^XXX^~
String resolved = simple.replaceAll("\\{\\{(.+)\\}\\}", "~^$1^~");
LanguageValidationResult answer = new LanguageValidationResult(simple);
Object context = null;
Object instance = null;
Class<?> clazz = null;
try {
// need a simple camel context for the simple language parser to be able to parse
clazz = classLoader.loadClass("org.apache.camel.impl.engine.SimpleCamelContext");
context = clazz.getDeclaredConstructor(boolean.class).newInstance(false);
clazz = classLoader.loadClass("org.apache.camel.language.simple.SimpleLanguage");
instance = clazz.getDeclaredConstructor().newInstance();
clazz = classLoader.loadClass("org.apache.camel.CamelContext");
instance.getClass().getMethod("setCamelContext", clazz).invoke(instance, context);
} catch (Exception e) {
clazz = null;
answer.setError(e.getMessage());
}
if (clazz != null && context != null && instance != null) {
Throwable cause = null;
try {
if (predicate) {
instance.getClass().getMethod("createPredicate", String.class).invoke(instance, resolved);
} else {
instance.getClass().getMethod("createExpression", String.class).invoke(instance, resolved);
}
} catch (InvocationTargetException e) {
cause = e.getTargetException();
} catch (Exception e) {
cause = e;
}
if (cause != null) {
// reverse ~^XXX^~ back to {{XXX}}
String errMsg = cause.getMessage();
errMsg = errMsg.replaceAll("\\~\\^(.+)\\^\\~", "{{$1}}");
answer.setError(errMsg);
// is it simple parser exception then we can grab the index where the problem is
if (cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleIllegalSyntaxException")
|| cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleParserException")) {
try {
// we need to grab the index field from those simple parser exceptions
Method method = cause.getClass().getMethod("getIndex");
Object result = method.invoke(cause);
if (result != null) {
int index = (int) result;
answer.setIndex(index);
}
} catch (Throwable i) {
// ignore
}
}
// we need to grab the short message field from this simple syntax exception
if (cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleIllegalSyntaxException")) {
try {
Method method = cause.getClass().getMethod("getShortMessage");
Object result = method.invoke(cause);
if (result != null) {
String msg = (String) result;
answer.setShortError(msg);
}
} catch (Throwable i) {
// ignore
}
if (answer.getShortError() == null) {
// fallback and try to make existing message short instead
String msg = answer.getError();
// grab everything before " at location " which would be regarded as the short message
int idx = msg.indexOf(" at location ");
if (idx > 0) {
msg = msg.substring(0, idx);
answer.setShortError(msg);
}
}
}
}
}
return answer;
}
public LanguageValidationResult validateLanguagePredicate(ClassLoader classLoader, String language, String text) {
if ("simple".equals(language)) {
return doValidateSimple(classLoader, text, true);
} else {
return doValidateLanguage(classLoader, language, text, true);
}
}
public LanguageValidationResult validateLanguageExpression(ClassLoader classLoader, String language, String text) {
if ("simple".equals(language)) {
return doValidateSimple(classLoader, text, false);
} else {
return doValidateLanguage(classLoader, language, text, false);
}
}
private LanguageValidationResult doValidateLanguage(ClassLoader classLoader, String language, String text, boolean predicate) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
LanguageValidationResult answer = new LanguageValidationResult(text);
LanguageModel model = languageModel(language);
if (model == null) {
answer.setError("Unknown language " + language);
return answer;
}
String className = model.getJavaType();
if (className == null) {
answer.setError("Cannot find javaType for language " + language);
return answer;
}
Object instance = null;
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(className);
instance = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
// ignore
}
if (clazz != null && instance != null) {
Throwable cause = null;
Object obj;
try {
try {
// favour using the validate method if present as this is for tooling usage
if (predicate) {
instance.getClass().getMethod("validatePredicate", String.class).invoke(instance, text);
} else {
instance.getClass().getMethod("validateExpression", String.class).invoke(instance, text);
}
} catch (NoSuchMethodException e) {
// ignore
}
// optional validate
if (predicate) {
instance.getClass().getMethod("createPredicate", String.class).invoke(instance, text);
} else {
instance.getClass().getMethod("createExpression", String.class).invoke(instance, text);
}
} catch (InvocationTargetException e) {
cause = e.getTargetException();
} catch (Exception e) {
cause = e;
}
if (cause != null) {
answer.setError(cause.getMessage());
}
}
return answer;
}
/**
* Special logic for log endpoints to deal when showAll=true
*/
private Map<String, String> filterProperties(String scheme, Map<String, String> options) {
if ("log".equals(scheme)) {
String showAll = options.get("showAll");
if ("true".equals(showAll)) {
Map<String, String> filtered = new LinkedHashMap<>();
// remove all the other showXXX options when showAll=true
for (Map.Entry<String, String> entry : options.entrySet()) {
String key = entry.getKey();
boolean skip = key.startsWith("show") && !key.equals("showAll");
if (!skip) {
filtered.put(key, entry.getValue());
}
}
return filtered;
}
}
// use as-is
return options;
}
private static boolean validateInteger(String value) {
boolean valid = false;
try {
Integer.parseInt(value);
valid = true;
} catch (Exception e) {
// ignore
}
return valid;
}
private static boolean validateDuration(String value) {
boolean valid = false;
try {
Long.parseLong(value);
valid = true;
} catch (Exception e) {
// ignore
}
if (!valid) {
try {
if (value.startsWith("P") || value.startsWith("-P") || value.startsWith("p") || value.startsWith("-p")) {
// its a duration
Duration.parse(value);
} else {
// it may be a time pattern, such as 5s for 5 seconds = 5000
TimePatternConverter.toMilliSeconds(value);
}
valid = true;
} catch (Exception e) {
// ignore
}
}
return valid;
}
private static String stripOptionalPrefixFromName(Map<String, BaseOptionModel> rows, String name) {
for (BaseOptionModel row : rows.values()) {
String optionalPrefix = row.getOptionalPrefix();
if (ObjectHelper.isNotEmpty(optionalPrefix) && name.startsWith(optionalPrefix)) {
// try again
return stripOptionalPrefixFromName(rows, name.substring(optionalPrefix.length()));
} else {
if (name.equalsIgnoreCase(row.getName())) {
break;
}
}
}
return name;
}
private static String getPropertyNameFromNameWithPrefix(Map<String, BaseOptionModel> rows, String name) {
for (BaseOptionModel row : rows.values()) {
String prefix = row.getPrefix();
if (ObjectHelper.isNotEmpty(prefix) && name.startsWith(prefix)) {
return row.getName();
}
}
return null;
}
/**
* Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld)
*
* @param text the string
* @return the string camel cased
*/
private static String dashToCamelCase(String text) {
if (text == null) {
return null;
}
int length = text.length();
if (length == 0) {
return text;
}
if (text.indexOf('-') == -1) {
return text;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '-') {
i++;
sb.append(Character.toUpperCase(text.charAt(i)));
} else {
sb.append(c);
}
}
return sb.toString();
}
// CHECKSTYLE:ON
}
|
core/camel-core-catalog/src/main/java/org/apache/camel/catalog/impl/AbstractCamelCatalog.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.catalog.impl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.camel.CamelContext;
import org.apache.camel.catalog.ConfigurationPropertiesValidationResult;
import org.apache.camel.catalog.EndpointValidationResult;
import org.apache.camel.catalog.JSonSchemaResolver;
import org.apache.camel.catalog.LanguageValidationResult;
import org.apache.camel.catalog.SuggestionStrategy;
import org.apache.camel.tooling.model.ApiMethodModel;
import org.apache.camel.tooling.model.ApiModel;
import org.apache.camel.tooling.model.BaseModel;
import org.apache.camel.tooling.model.BaseOptionModel;
import org.apache.camel.tooling.model.ComponentModel;
import org.apache.camel.tooling.model.DataFormatModel;
import org.apache.camel.tooling.model.EipModel;
import org.apache.camel.tooling.model.JsonMapper;
import org.apache.camel.tooling.model.LanguageModel;
import org.apache.camel.tooling.model.MainModel;
import org.apache.camel.tooling.model.OtherModel;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
/**
* Base class for both the runtime RuntimeCamelCatalog from camel-core and the complete CamelCatalog from camel-catalog.
*/
@SuppressWarnings("unused")
public abstract class AbstractCamelCatalog {
// CHECKSTYLE:OFF
private static final Pattern SYNTAX_PATTERN = Pattern.compile("([\\w.]+)");
private static final Pattern ENV_OR_SYS_PATTERN = Pattern.compile("\\{\\{(env|sys):\\w+\\}\\}");
private static final Pattern SYNTAX_DASH_PATTERN = Pattern.compile("([\\w.-]+)");
private static final Pattern COMPONENT_SYNTAX_PARSER = Pattern.compile("([^\\w-]*)([\\w-]+)");
private SuggestionStrategy suggestionStrategy;
private JSonSchemaResolver jsonSchemaResolver;
public String componentJSonSchema(String name) {
return jsonSchemaResolver.getComponentJSonSchema(name);
}
public String modelJSonSchema(String name) {
return getJSonSchemaResolver().getModelJSonSchema(name);
}
public EipModel eipModel(String name) {
String json = modelJSonSchema(name);
return json != null ? JsonMapper.generateEipModel(json) : null;
}
public ComponentModel componentModel(String name) {
String json = componentJSonSchema(name);
return json != null ? JsonMapper.generateComponentModel(json) : null;
}
public String dataFormatJSonSchema(String name) {
return getJSonSchemaResolver().getDataFormatJSonSchema(name);
}
public DataFormatModel dataFormatModel(String name) {
String json = dataFormatJSonSchema(name);
return json != null ? JsonMapper.generateDataFormatModel(json) : null;
}
public String languageJSonSchema(String name) {
// if we try to look method then its in the bean.json file
if ("method".equals(name)) {
name = "bean";
}
return getJSonSchemaResolver().getLanguageJSonSchema(name);
}
public LanguageModel languageModel(String name) {
String json = languageJSonSchema(name);
return json != null ? JsonMapper.generateLanguageModel(json) : null;
}
public String otherJSonSchema(String name) {
return getJSonSchemaResolver().getOtherJSonSchema(name);
}
public OtherModel otherModel(String name) {
String json = otherJSonSchema(name);
return json != null ? JsonMapper.generateOtherModel(json) : null;
}
public String mainJSonSchema() {
return getJSonSchemaResolver().getMainJsonSchema();
}
public MainModel mainModel() {
String json = mainJSonSchema();
return json != null ? JsonMapper.generateMainModel(json) : null;
}
public SuggestionStrategy getSuggestionStrategy() {
return suggestionStrategy;
}
public void setSuggestionStrategy(SuggestionStrategy suggestionStrategy) {
this.suggestionStrategy = suggestionStrategy;
}
public JSonSchemaResolver getJSonSchemaResolver() {
return jsonSchemaResolver;
}
public void setJSonSchemaResolver(JSonSchemaResolver resolver) {
this.jsonSchemaResolver = resolver;
}
public boolean validateTimePattern(String pattern) {
return validateDuration(pattern);
}
public EndpointValidationResult validateEndpointProperties(String uri) {
return validateEndpointProperties(uri, false, false, false);
}
public EndpointValidationResult validateEndpointProperties(String uri, boolean ignoreLenientProperties) {
return validateEndpointProperties(uri, ignoreLenientProperties, false, false);
}
public EndpointValidationResult validateProperties(String scheme, Map<String, String> properties) {
boolean lenient = Boolean.getBoolean(properties.getOrDefault("lenient", "false"));
return validateProperties(scheme, properties, lenient, false, false);
}
private EndpointValidationResult validateProperties(String scheme, Map<String, String> properties,
boolean lenient, boolean consumerOnly,
boolean producerOnly) {
EndpointValidationResult result = new EndpointValidationResult(scheme);
ComponentModel model = componentModel(scheme);
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getApiSyntax());
String key = properties.get(apiSyntax[0]);
String key2 = apiSyntax.length > 1 ? properties.get(apiSyntax[1]) : null;
Map<String, BaseOptionModel> apiProperties = extractApiProperties(model, key, key2);
rows.putAll(apiProperties);
}
// the dataformat component refers to a data format so lets add the properties for the selected
// data format to the list of rows
if ("dataformat".equals(scheme)) {
String dfName = properties.get("name");
if (dfName != null) {
DataFormatModel dfModel = dataFormatModel(dfName);
if (dfModel != null) {
dfModel.getOptions().forEach(o -> rows.put(o.getName(), o));
}
}
}
for (Map.Entry<String, String> property : properties.entrySet()) {
String value = property.getValue();
String originalName = property.getKey();
// the name may be using an optional prefix, so lets strip that because the options
// in the schema are listed without the prefix
String name = stripOptionalPrefixFromName(rows, originalName);
// the name may be using a prefix, so lets see if we can find the real property name
String propertyName = getPropertyNameFromNameWithPrefix(rows, name);
if (propertyName != null) {
name = propertyName;
}
BaseOptionModel row = rows.get(name);
if (row == null) {
// unknown option
// only add as error if the component is not lenient properties, or not stub component
// and the name is not a property placeholder for one or more values
boolean namePlaceholder = name.startsWith("{{") && name.endsWith("}}");
if (!namePlaceholder && !"stub".equals(scheme)) {
if (lenient) {
// as if we are lenient then the option is a dynamic extra option which we cannot validate
result.addLenient(name);
} else {
// its unknown
result.addUnknown(name);
if (suggestionStrategy != null) {
String[] suggestions = suggestionStrategy.suggestEndpointOptions(rows.keySet(), name);
if (suggestions != null) {
result.addUnknownSuggestions(name, suggestions);
}
}
}
}
} else {
if ("parameter".equals(row.getKind())) {
// consumer only or producer only mode for parameters
String label = row.getLabel();
if (consumerOnly) {
if (label != null && label.contains("producer")) {
// the option is only for producer so you cannot use it in consumer mode
result.addNotConsumerOnly(name);
}
} else if (producerOnly) {
if (label != null && label.contains("consumer")) {
// the option is only for consumer so you cannot use it in producer mode
result.addNotProducerOnly(name);
}
}
}
String prefix = row.getPrefix();
boolean valuePlaceholder = value.startsWith("{{") || value.startsWith("${") || value.startsWith("$simple{");
boolean lookup = value.startsWith("#") && value.length() > 1;
// we cannot evaluate multi values as strict as the others, as we don't know their expected types
boolean multiValue = prefix != null && originalName.startsWith(prefix)
&& row.isMultiValue();
// default value
Object defaultValue = row.getDefaultValue();
if (defaultValue != null) {
result.addDefaultValue(name, defaultValue.toString());
}
// is required but the value is empty
if (row.isRequired() && URISupport.isEmpty(value)) {
result.addRequired(name);
}
// is the option deprecated
boolean deprecated = row.isDeprecated();
if (deprecated) {
result.addDeprecated(name);
}
// is enum but the value is not within the enum range
// but we can only check if the value is not a placeholder
List<String> enums = row.getEnums();
if (!multiValue && !valuePlaceholder && !lookup && enums != null) {
boolean found = false;
for (String s : enums) {
String dashEC = StringHelper.camelCaseToDash(value);
String valueEC = StringHelper.asEnumConstantValue(value);
if (value.equalsIgnoreCase(s) || dashEC.equalsIgnoreCase(s) || valueEC.equalsIgnoreCase(s)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(name, value);
result.addInvalidEnumChoices(name, enums.toArray(new String[0]));
if (suggestionStrategy != null) {
Set<String> names = new LinkedHashSet<>(enums);
String[] suggestions = suggestionStrategy.suggestEndpointOptions(names, value);
if (suggestions != null) {
result.addInvalidEnumSuggestions(name, suggestions);
}
}
}
}
// is reference lookup of bean (not applicable for @UriPath, enums, or multi-valued)
if (!multiValue && enums == null && !"path".equals(row.getKind()) && "object".equals(row.getType())) {
// must start with # and be at least 2 characters
if (!value.startsWith("#") || value.length() <= 1) {
result.addInvalidReference(name, value);
}
}
// is boolean
if (!multiValue && !valuePlaceholder && !lookup && "boolean".equals(row.getType())) {
// value must be a boolean
boolean bool = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
if (!bool) {
result.addInvalidBoolean(name, value);
}
}
// is duration
if (!multiValue && !valuePlaceholder && !lookup && "duration".equals(row.getType())) {
// value must be convertable to a duration
boolean valid = validateDuration(value);
if (!valid) {
result.addInvalidDuration(name, value);
}
}
// is integer
if (!multiValue && !valuePlaceholder && !lookup && "integer".equals(row.getType())) {
// value must be an integer
boolean valid = validateInteger(value);
if (!valid) {
result.addInvalidInteger(name, value);
}
}
// is number
if (!multiValue && !valuePlaceholder && !lookup && "number".equals(row.getType())) {
// value must be an number
boolean valid = false;
try {
valid = !Double.valueOf(value).isNaN() || !Float.valueOf(value).isNaN();
} catch (Exception e) {
// ignore
}
if (!valid) {
result.addInvalidNumber(name, value);
}
}
}
}
// for api component then check that the apiName/methodName combo is valid
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getApiSyntax());
String key1 = properties.get(apiSyntax[0]);
String key2 = apiSyntax.length > 1 ? properties.get(apiSyntax[1]) : null;
if (key1 != null && key2 != null) {
ApiModel api = model.getApiOptions().stream().filter(o -> o.getName().equalsIgnoreCase(key1)).findFirst().orElse(null);
if (api == null) {
result.addInvalidEnum(apiSyntax[0], key1);
List<String> choices = model.getApiOptions().stream().map(ApiModel::getName).collect(Collectors.toList());
result.addInvalidEnumChoices(apiSyntax[0], choices.toArray(new String[choices.size()]));
} else {
// walk each method and match against its name/alias
boolean found = false;
for (ApiMethodModel m : api.getMethods()) {
String key3 = apiMethodAlias(api, m);
if (m.getName().equalsIgnoreCase(key2) || key2.equalsIgnoreCase(key3)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(apiSyntax[1], key2);
List<String> choices = api.getMethods().stream()
.map(m -> {
// favour using method alias in choices
String answer = apiMethodAlias(api, m);
if (answer == null) {
answer = m.getName();
}
return answer;
})
.collect(Collectors.toList());
result.addInvalidEnumChoices(apiSyntax[1], choices.toArray(new String[choices.size()]));
}
}
}
}
// now check if all required values are there, and that a default value does not exists
for (BaseOptionModel row : rows.values()) {
if (row.isRequired()) {
String name = row.getName();
Object value = properties.get(name);
if (URISupport.isEmpty(value)) {
value = row.getDefaultValue();
}
if (URISupport.isEmpty(value)) {
result.addRequired(name);
}
}
}
return result;
}
public EndpointValidationResult validateEndpointProperties(String uri, boolean ignoreLenientProperties, boolean consumerOnly, boolean producerOnly) {
try {
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
ComponentModel model = scheme != null ? componentModel(scheme) : null;
if (model == null) {
EndpointValidationResult result = new EndpointValidationResult(uri);
if (uri.startsWith("{{")) {
result.addIncapable(uri);
} else if (scheme != null) {
result.addUnknownComponent(scheme);
} else {
result.addUnknownComponent(uri);
}
return result;
}
Map<String, String> properties = endpointProperties(uri);
boolean lenient;
if (!model.isConsumerOnly() && !model.isProducerOnly() && consumerOnly) {
// lenient properties is not support in consumer only mode if the component can do both of them
lenient = false;
} else {
// only enable lenient properties if we should not ignore
lenient = !ignoreLenientProperties && model.isLenientProperties();
}
return validateProperties(scheme, properties, lenient, consumerOnly, producerOnly);
} catch (URISyntaxException e) {
EndpointValidationResult result = new EndpointValidationResult(uri);
result.addSyntaxError(e.getMessage());
return result;
}
}
public Map<String, String> endpointProperties(String uri) throws URISyntaxException {
// need to normalize uri first
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
// grab the syntax
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
String syntax = model.getSyntax();
String alternativeSyntax = model.getAlternativeSyntax();
if (syntax == null) {
throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema");
}
// only if we support alternative syntax, and the uri contains the username and password in the authority
// part of the uri, then we would need some special logic to capture that information and strip those
// details from the uri, so we can continue parsing the uri using the normal syntax
Map<String, String> userInfoOptions = new LinkedHashMap<>();
if (alternativeSyntax != null && alternativeSyntax.contains("@")) {
// clip the scheme from the syntax
alternativeSyntax = CatalogHelper.after(alternativeSyntax, ":");
// trim so only userinfo
int idx = alternativeSyntax.indexOf('@');
String fields = alternativeSyntax.substring(0, idx);
String[] names = fields.split(":");
// grab authority part and grab username and/or password
String authority = u.getAuthority();
if (authority != null && authority.contains("@")) {
String username = null;
String password = null;
// grab unserinfo part before @
String userInfo = authority.substring(0, authority.indexOf('@'));
String[] parts = userInfo.split(":");
if (parts.length == 2) {
username = parts[0];
password = parts[1];
} else {
// only username
username = userInfo;
}
// remember the username and/or password which we add later to the options
if (names.length == 2) {
userInfoOptions.put(names[0], username);
if (password != null) {
// password is optional
userInfoOptions.put(names[1], password);
}
}
}
}
// clip the scheme from the syntax
syntax = CatalogHelper.after(syntax, ":");
// clip the scheme from the uri
uri = CatalogHelper.after(uri, ":");
String uriPath = URISupport.stripQuery(uri);
// the uri path may use {{env:xxx}} or {{sys:xxx}} placeholders so ignore those
Matcher matcher = ENV_OR_SYS_PATTERN.matcher(uriPath);
uriPath = matcher.replaceAll("");
// strip user info from uri path
if (!userInfoOptions.isEmpty()) {
int idx = uriPath.indexOf('@');
if (idx > -1) {
uriPath = uriPath.substring(idx + 1);
}
}
// strip double slash in the start
if (uriPath != null && uriPath.startsWith("//")) {
uriPath = uriPath.substring(2);
}
// parse the syntax and find the names of each option
matcher = SYNTAX_PATTERN.matcher(syntax);
List<String> word = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
if (!scheme.equals(s)) {
word.add(s);
}
}
// parse the syntax and find each token between each option
String[] tokens = SYNTAX_PATTERN.split(syntax);
// find the position where each option start/end
List<String> word2 = new ArrayList<>();
int prev = 0;
int prevPath = 0;
// special for activemq/jms where the enum for destinationType causes a token issue as it includes a colon
// for 'temp:queue' and 'temp:topic' values
if ("activemq".equals(scheme) || "jms".equals(scheme)) {
if (uriPath.startsWith("temp:")) {
prevPath = 5;
}
}
for (String token : tokens) {
if (token.isEmpty()) {
continue;
}
// special for some tokens where :// can be used also, eg http://foo
int idx = -1;
int len = 0;
if (":".equals(token)) {
idx = uriPath.indexOf("://", prevPath);
len = 3;
}
if (idx == -1) {
idx = uriPath.indexOf(token, prevPath);
len = token.length();
}
if (idx > 0) {
String option = uriPath.substring(prev, idx);
word2.add(option);
prev = idx + len;
prevPath = prev;
}
}
// special for last or if we did not add anyone
if (prev > 0 || word2.isEmpty()) {
String option = uriPath.substring(prev);
word2.add(option);
}
boolean defaultValueAdded = false;
// now parse the uri to know which part isw what
Map<String, String> options = new LinkedHashMap<>();
// include the username and password from the userinfo section
if (!userInfoOptions.isEmpty()) {
options.putAll(userInfoOptions);
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// is this an api component then there may be additional options
if (model.isApi()) {
String[] apiSyntax = StringHelper.splitWords(model.getSyntax());
int pos = word.indexOf(apiSyntax[0]);
if (pos != -1) {
String key = word2.size() > pos ? word2.get(pos) : null;
// key2 should be null as its fine to get all the options for api name
Map<String, BaseOptionModel> apiProperties = extractApiProperties(model, key, null);
rows.putAll(apiProperties);
}
}
// word contains the syntax path elements
Iterator<String> it = word2.iterator();
for (int i = 0; i < word.size(); i++) {
String key = word.get(i);
BaseOptionModel option = rows.get(key);
boolean allOptions = word.size() == word2.size();
// we have all options so no problem
if (allOptions) {
String value = it.next();
options.put(key, value);
} else {
// we have a little problem as we do not not have all options
if (!option.isRequired()) {
Object value = null;
boolean last = i == word.size() - 1;
if (last) {
// if its the last value then use it instead of the default value
value = it.hasNext() ? it.next() : null;
if (value != null) {
options.put(key, value.toString());
} else {
value = option.getDefaultValue();
}
}
if (value != null) {
options.put(key, value.toString());
defaultValueAdded = true;
}
} else {
String value = it.hasNext() ? it.next() : null;
if (value != null) {
options.put(key, value);
}
}
}
}
Map<String, String> answer = new LinkedHashMap<>();
// remove all options which are using default values and are not required
for (Map.Entry<String, String> entry : options.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
BaseOptionModel row = rows.get(key);
if (defaultValueAdded) {
boolean required = row.isRequired();
Object defaultValue = row.getDefaultValue();
if (!required && defaultValue != null) {
if (defaultValue.toString().equals(value)) {
continue;
}
}
}
// we should keep this in the answer
answer.put(key, value);
}
// now parse the uri parameters
Map<String, Object> parameters = URISupport.parseParameters(u);
// and covert the values to String so its JMX friendly
while (!parameters.isEmpty()) {
Map.Entry<String, Object> entry = parameters.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue() != null ? entry.getValue().toString() : "";
BaseOptionModel row = rows.get(key);
if (row != null && row.isMultiValue()) {
String prefix = row.getPrefix();
if (prefix != null) {
// extra all the multi valued options
Map<String, Object> values = URISupport.extractProperties(parameters, prefix);
// build a string with the extra multi valued options with the prefix and & as separator
String csb = values.entrySet().stream()
.map(multi -> prefix + multi.getKey() + "=" + (multi.getValue() != null ? multi.getValue().toString() : ""))
.collect(Collectors.joining("&"));
// append the extra multi-values to the existing (which contains the first multi value)
if (!csb.isEmpty()) {
value = value + "&" + csb;
}
}
}
answer.put(key, value);
// remove the parameter as we run in a while loop until no more parameters
parameters.remove(key);
}
return answer;
}
private Map<String, BaseOptionModel> extractApiProperties(ComponentModel model, String key, String key2) {
Map<String, BaseOptionModel> answer = new LinkedHashMap<>();
if (key != null) {
String matchKey = null;
String dashKey = StringHelper.camelCaseToDash(key);
String ecKey = StringHelper.asEnumConstantValue(key);
String dashKey2 = StringHelper.camelCaseToDash(key2);
String ecKey2 = StringHelper.asEnumConstantValue(key2);
for (ApiModel am : model.getApiOptions()) {
String aKey = am.getName();
if (aKey.equalsIgnoreCase("DEFAULT") || aKey.equalsIgnoreCase(key) || aKey.equalsIgnoreCase(ecKey) || aKey.equalsIgnoreCase(dashKey)) {
am.getMethods().stream()
.filter(m -> {
if (key2 == null) {
// no api method so match all
return true;
}
String name = m.getName();
if (name.equalsIgnoreCase(key2) || name.equalsIgnoreCase(ecKey2) || name.equalsIgnoreCase(dashKey2)) {
return true;
}
// is there an alias then we need to compute the alias key and compare against the key2
String key3 = apiMethodAlias(am, m);
if (key3 != null) {
String dashKey3 = StringHelper.camelCaseToDash(key3);
String ecKey3 = StringHelper.asEnumConstantValue(key3);
if (key2.equalsIgnoreCase(key3) || ecKey2.equalsIgnoreCase(ecKey3) || dashKey2.equalsIgnoreCase(dashKey3)) {
return true;
}
}
return false;
})
.forEach(m -> m.getOptions()
.forEach(o -> answer.put(o.getName(), o)));
}
}
}
return answer;
}
private static String apiMethodAlias(ApiModel api, ApiMethodModel method) {
String name = method.getName();
for (String alias : api.getAliases()) {
int pos = alias.indexOf('=');
String pattern = alias.substring(0, pos);
String aliasMethod = alias.substring(pos + 1);
// match ignore case
if (Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(name).matches()) {
return aliasMethod;
}
}
return null;
}
public Map<String, String> endpointLenientProperties(String uri) throws URISyntaxException {
// need to normalize uri first
// parse the uri
URI u = URISupport.normalizeUri(uri);
String scheme = u.getScheme();
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// now parse the uri parameters
Map<String, Object> parameters = URISupport.parseParameters(u);
// all the known options
Set<String> names = rows.keySet();
Map<String, String> answer = new LinkedHashMap<>();
// and covert the values to String so its JMX friendly
parameters.forEach((k, v) -> {
String key = k;
String value = v != null ? v.toString() : "";
// is the key a prefix property
int dot = key.indexOf('.');
if (dot != -1) {
String prefix = key.substring(0, dot + 1); // include dot in prefix
String option = getPropertyNameFromNameWithPrefix(rows, prefix);
if (option == null || !rows.get(option).isMultiValue()) {
answer.put(key, value);
}
} else if (!names.contains(key)) {
answer.put(key, value);
}
});
return answer;
}
public String endpointComponentName(String uri) {
if (uri != null) {
int idx = uri.indexOf(':');
if (idx > 0) {
return uri.substring(0, idx);
}
}
return null;
}
public String asEndpointUri(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException {
return doAsEndpointUri(scheme, properties, "&", encode);
}
public String asEndpointUriXml(String scheme, Map<String, String> properties, boolean encode) throws URISyntaxException {
return doAsEndpointUri(scheme, properties, "&", encode);
}
String doAsEndpointUri(String scheme, Map<String, String> properties, String ampersand, boolean encode) throws URISyntaxException {
// grab the syntax
ComponentModel model = componentModel(scheme);
if (model == null) {
throw new IllegalArgumentException("Cannot find endpoint with scheme " + scheme);
}
String originalSyntax = model.getSyntax();
if (originalSyntax == null) {
throw new IllegalArgumentException("Endpoint with scheme " + scheme + " has no syntax defined in the json schema");
}
// do any properties filtering which can be needed for some special components
properties = filterProperties(scheme, properties);
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getComponentOptions().forEach(o -> rows.put(o.getName(), o));
// endpoint options have higher priority so overwrite component options
model.getEndpointOptions().forEach(o -> rows.put(o.getName(), o));
model.getEndpointPathOptions().forEach(o -> rows.put(o.getName(), o));
// clip the scheme from the syntax
String syntax = "";
if (originalSyntax.contains(":")) {
originalSyntax = CatalogHelper.after(originalSyntax, ":");
}
// build at first according to syntax (use a tree map as we want the uri options sorted)
Map<String, String> copy = new TreeMap<>(properties);
Matcher syntaxMatcher = COMPONENT_SYNTAX_PARSER.matcher(originalSyntax);
while (syntaxMatcher.find()) {
syntax += syntaxMatcher.group(1);
String propertyName = syntaxMatcher.group(2);
String propertyValue = copy.remove(propertyName);
syntax += propertyValue != null ? propertyValue : propertyName;
}
// do we have all the options the original syntax needs (easy way)
String[] keys = syntaxKeys(originalSyntax);
boolean hasAllKeys = properties.keySet().containsAll(Arrays.asList(keys));
// build endpoint uri
StringBuilder sb = new StringBuilder();
// add scheme later as we need to take care if there is any context-path or query parameters which
// affect how the URI should be constructed
if (hasAllKeys) {
// we have all the keys for the syntax so we can build the uri the easy way
sb.append(syntax);
if (!copy.isEmpty()) {
// wrap secret values with RAW to avoid breaking URI encoding in case of encoded values
copy.replaceAll((key, val) -> {
if (val == null) {
return val;
}
BaseOptionModel option = rows.get(key);
if (option == null) {
return val;
}
if (option.isSecret() && !val.startsWith("#") && !val.startsWith("RAW(")) {
return "RAW(" + val + ")";
}
return val;
});
boolean hasQuestionMark = sb.toString().contains("?");
// the last option may already contain a ? char, if so we should use & instead of ?
sb.append(hasQuestionMark ? ampersand : '?');
String query = URISupport.createQueryString(copy, ampersand, encode);
sb.append(query);
}
} else {
// TODO: revisit this and see if we can do this in another way
// oh darn some options is missing, so we need a complex way of building the uri
// the tokens between the options in the path
String[] tokens = SYNTAX_DASH_PATTERN.split(syntax);
// parse the syntax into each options
Matcher matcher = SYNTAX_PATTERN.matcher(originalSyntax);
List<String> options = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
options.add(s);
}
// need to preserve {{ and }} from the syntax
// (we need to use words only as its provisional placeholders)
syntax = syntax.replace("{{", "BEGINCAMELPLACEHOLDER");
syntax = syntax.replace("}}", "ENDCAMELPLACEHOLDER");
// parse the syntax into each options
Matcher matcher2 = SYNTAX_DASH_PATTERN.matcher(syntax);
List<String> options2 = new ArrayList<>();
while (matcher2.find()) {
String s = matcher2.group(1);
s = s.replace("BEGINCAMELPLACEHOLDER", "{{");
s = s.replace("ENDCAMELPLACEHOLDER", "}}");
options2.add(s);
}
// build the endpoint
int range = 0;
boolean first = true;
boolean hasQuestionmark = false;
for (int i = 0; i < options.size(); i++) {
String key = options.get(i);
String key2 = options2.get(i);
String token = null;
if (tokens.length > i) {
token = tokens[i];
}
boolean contains = properties.containsKey(key);
if (!contains) {
// if the key are similar we have no explicit value and can try to find a default value if the option is required
BaseOptionModel row = rows.get(key);
if (row != null && row.isRequired()) {
Object value = row.getDefaultValue();
if (!URISupport.isEmpty(value)) {
properties.put(key, key2 = value.toString());
}
}
}
// was the option provided?
if (properties.containsKey(key)) {
if (!first && token != null) {
sb.append(token);
}
hasQuestionmark |= key.contains("?") || (token != null && token.contains("?"));
sb.append(key2);
first = false;
}
range++;
}
// append any extra options that was in surplus for the last
while (range < options2.size()) {
String token = null;
if (tokens.length > range) {
token = tokens[range];
}
String key2 = options2.get(range);
sb.append(token);
sb.append(key2);
hasQuestionmark |= key2.contains("?") || (token != null && token.contains("?"));
range++;
}
if (!copy.isEmpty()) {
// wrap secret values with RAW to avoid breaking URI encoding in case of encoded values
copy.replaceAll(new BiFunction<String, String, String>() {
@Override
public String apply(String key, String val) {
if (val == null) {
return val;
}
BaseOptionModel option = rows.get(key);
if (option == null) {
return val;
}
if (option.isSecret() && !val.startsWith("#") && !val.startsWith("RAW(")) {
return "RAW(" + val + ")";
}
return val;
}
});
// the last option may already contain a ? char, if so we should use & instead of ?
sb.append(hasQuestionmark ? ampersand : '?');
String query = URISupport.createQueryString(copy, ampersand, encode);
sb.append(query);
}
}
String remainder = sb.toString();
boolean queryOnly = remainder.startsWith("?");
if (queryOnly) {
// it has only query parameters
return scheme + remainder;
} else if (!remainder.isEmpty()) {
// it has context path and possible query parameters
return scheme + ":" + remainder;
} else {
// its empty without anything
return scheme;
}
}
private static String[] syntaxKeys(String syntax) {
// build tokens between the separators
List<String> tokens = new ArrayList<>();
if (syntax != null) {
StringBuilder current = new StringBuilder();
for (int i = 0; i < syntax.length(); i++) {
char ch = syntax.charAt(i);
if (Character.isLetterOrDigit(ch)) {
current.append(ch);
} else {
// reset for new current tokens
if (current.length() > 0) {
tokens.add(current.toString());
current = new StringBuilder();
}
}
}
// anything left over?
if (current.length() > 0) {
tokens.add(current.toString());
}
}
return tokens.toArray(new String[tokens.size()]);
}
public ConfigurationPropertiesValidationResult validateConfigurationProperty(String line) {
String longKey = CatalogHelper.before(line, "=");
String key = longKey;
String value = CatalogHelper.after(line, "=");
// trim values
if (longKey != null) {
longKey = longKey.trim();
}
if (key != null) {
key = key.trim();
}
if (value != null) {
value = value.trim();
}
ConfigurationPropertiesValidationResult result = new ConfigurationPropertiesValidationResult();
boolean accept = acceptConfigurationPropertyKey(key);
if (!accept) {
result.setAccepted(false);
return result;
} else {
result.setAccepted(true);
}
// skip camel.
key = key.substring("camel.".length());
Function<String, ? extends BaseModel<?>> loader = null;
if (key.startsWith("component.")) {
key = key.substring("component.".length());
loader = this::componentModel;
} else if (key.startsWith("dataformat.")) {
key = key.substring("dataformat.".length());
loader = this::dataFormatModel;
} else if (key.startsWith("language.")) {
key = key.substring("language.".length());
loader = this::languageModel;
}
if (loader != null) {
int idx = key.indexOf('.');
String name = key.substring(0, idx);
String option = key.substring(idx + 1);
if (value != null) {
BaseModel<?> model = loader.apply(name);
if (model == null) {
result.addUnknownComponent(name);
return result;
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getOptions().forEach(o -> rows.put(o.getName(), o));
// lower case option and remove dash
String nOption = option.replace("-", "").toLowerCase(Locale.ENGLISH);
String suffix = null;
int posDot = nOption.indexOf('.');
int posBracket = nOption.indexOf('[');
if (posDot > 0 && posBracket > 0) {
int first = Math.min(posDot, posBracket);
suffix = nOption.substring(first);
nOption = nOption.substring(0, first);
} else if (posDot > 0) {
suffix = nOption.substring(posDot);
nOption = nOption.substring(0, posDot);
} else if (posBracket > 0) {
suffix = nOption.substring(posBracket);
nOption = nOption.substring(0, posBracket);
}
doValidateConfigurationProperty(result, rows, name, value, longKey, nOption, suffix);
}
} else if (key.startsWith("main.")
|| key.startsWith("hystrix.")
|| key.startsWith("resilience4j.")
|| key.startsWith("faulttolerance.")
|| key.startsWith("threadpool.")
|| key.startsWith("lra.")
|| key.startsWith("health.")
|| key.startsWith("rest.")) {
int idx = key.indexOf('.');
String name = key.substring(0, idx);
String option = key.substring(idx + 1);
if (value != null) {
MainModel model = mainModel();
if (model == null) {
result.addIncapable("camel-main not detected on classpath");
return result;
}
Map<String, BaseOptionModel> rows = new HashMap<>();
model.getOptions().forEach(o -> rows.put(dashToCamelCase(o.getName()), o));
// lower case option and remove dash
String nOption = longKey.replace("-", "").toLowerCase(Locale.ENGLISH);
// look for suffix or array index after 2nd dot
int secondDot = nOption.indexOf('.', nOption.indexOf('.') + 1) + 1;
String suffix = null;
int posDot = nOption.indexOf('.', secondDot);
int posBracket = nOption.indexOf('[', secondDot);
if (posDot > 0 && posBracket > 0) {
int first = Math.min(posDot, posBracket);
suffix = nOption.substring(first);
nOption = nOption.substring(0, first);
} else if (posDot > 0) {
suffix = nOption.substring(posDot);
nOption = nOption.substring(0, posDot);
} else if (posBracket > 0) {
suffix = nOption.substring(posBracket);
nOption = nOption.substring(0, posBracket);
}
doValidateConfigurationProperty(result, rows, name, value, longKey, nOption, suffix);
}
}
return result;
}
private void doValidateConfigurationProperty(ConfigurationPropertiesValidationResult result,
Map<String, BaseOptionModel> rows,
String name, String value, String longKey,
String lookupKey, String suffix) {
// find option
String rowKey = rows.keySet().stream()
.filter(n -> n.toLowerCase(Locale.ENGLISH).equals(lookupKey)).findFirst().orElse(null);
if (rowKey == null) {
// unknown option
result.addUnknown(longKey);
if (suggestionStrategy != null) {
String[] suggestions = suggestionStrategy.suggestEndpointOptions(rows.keySet(), name);
if (suggestions != null) {
result.addUnknownSuggestions(name, suggestions);
}
}
} else {
boolean optionPlaceholder = value.startsWith("{{") || value.startsWith("${") || value.startsWith("$simple{");
boolean lookup = value.startsWith("#") && value.length() > 1;
// deprecated
BaseOptionModel row = rows.get(rowKey);
if (!optionPlaceholder && !lookup && row.isDeprecated()) {
result.addDeprecated(longKey);
}
// is boolean
if (!optionPlaceholder && !lookup && "boolean".equals(row.getType())) {
// value must be a boolean
boolean bool = "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
if (!bool) {
result.addInvalidBoolean(longKey, value);
}
}
// is duration
if (!optionPlaceholder && !lookup && "duration".equals(row.getType())) {
// value must be convertable to a duration
boolean valid = validateDuration(value);
if (!valid) {
result.addInvalidDuration(longKey, value);
}
}
// is integer
if (!optionPlaceholder && !lookup && "integer".equals(row.getType())) {
// value must be an integer
boolean valid = validateInteger(value);
if (!valid) {
result.addInvalidInteger(longKey, value);
}
}
// is number
if (!optionPlaceholder && !lookup && "number".equals(row.getType())) {
// value must be an number
boolean valid = false;
try {
valid = !Double.valueOf(value).isNaN() || !Float.valueOf(value).isNaN();
} catch (Exception e) {
// ignore
}
if (!valid) {
result.addInvalidNumber(longKey, value);
}
}
// is enum
List<String> enums = row.getEnums();
if (!optionPlaceholder && !lookup && enums != null) {
boolean found = false;
String dashEC = StringHelper.camelCaseToDash(value);
String valueEC = StringHelper.asEnumConstantValue(value);
for (String s : enums) {
// equals as is or using the enum naming style
if (value.equalsIgnoreCase(s) || dashEC.equalsIgnoreCase(s) || valueEC.equalsIgnoreCase(s)) {
found = true;
break;
}
}
if (!found) {
result.addInvalidEnum(longKey, value);
result.addInvalidEnumChoices(longKey, enums.toArray(new String[0]));
if (suggestionStrategy != null) {
Set<String> names = new LinkedHashSet<>(enums);
String[] suggestions = suggestionStrategy.suggestEndpointOptions(names, value);
if (suggestions != null) {
result.addInvalidEnumSuggestions(longKey, suggestions);
}
}
}
}
String javaType = row.getJavaType();
if (!optionPlaceholder && !lookup && javaType != null
&& (javaType.startsWith("java.util.Map") || javaType.startsWith("java.util.Properties"))) {
// there must be a valid suffix
if (suffix == null || suffix.isEmpty() || suffix.equals(".")) {
result.addInvalidMap(longKey, value);
} else if (suffix.startsWith("[") && !suffix.contains("]")) {
result.addInvalidMap(longKey, value);
}
}
if (!optionPlaceholder && !lookup && javaType != null && "array".equals(row.getType())) {
// there must be a suffix and it must be using [] style
if (suffix == null || suffix.isEmpty() || suffix.equals(".")) {
result.addInvalidArray(longKey, value);
} else if (!suffix.startsWith("[") && !suffix.contains("]")) {
result.addInvalidArray(longKey, value);
} else {
String index = CatalogHelper.before(suffix.substring(1), "]");
// value must be an integer
boolean valid = validateInteger(index);
if (!valid) {
result.addInvalidInteger(longKey, index);
}
}
}
}
}
private static boolean acceptConfigurationPropertyKey(String key) {
if (key == null) {
return false;
}
return key.startsWith("camel.component.")
|| key.startsWith("camel.dataformat.")
|| key.startsWith("camel.language.")
|| key.startsWith("camel.main.")
|| key.startsWith("camel.hystrix.")
|| key.startsWith("camel.resilience4j.")
|| key.startsWith("camel.faulttolerance.")
|| key.startsWith("camel.threadpool.")
|| key.startsWith("camel.health.")
|| key.startsWith("camel.lra.")
|| key.startsWith("camel.rest.");
}
private LanguageValidationResult doValidateSimple(ClassLoader classLoader, String simple, boolean predicate) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
// if there are {{ }}} property placeholders then we need to resolve them to something else
// as the simple parse cannot resolve them before parsing as we dont run the actual Camel application
// with property placeholders setup so we need to dummy this by replace the {{ }} to something else
// therefore we use an more unlikely character: {{XXX}} to ~^XXX^~
String resolved = simple.replaceAll("\\{\\{(.+)\\}\\}", "~^$1^~");
LanguageValidationResult answer = new LanguageValidationResult(simple);
Object context = null;
Object instance = null;
Class<?> clazz = null;
try {
// need a simple camel context for the simple language parser to be able to parse
clazz = classLoader.loadClass("org.apache.camel.impl.engine.SimpleCamelContext");
context = clazz.getDeclaredConstructor(boolean.class).newInstance(false);
clazz = classLoader.loadClass("org.apache.camel.language.simple.SimpleLanguage");
instance = clazz.getDeclaredConstructor().newInstance();
instance.getClass().getMethod("setCamelContext", CamelContext.class).invoke(instance, context);
} catch (Exception e) {
// ignore
}
if (clazz != null && context != null && instance != null) {
Throwable cause = null;
try {
if (predicate) {
instance.getClass().getMethod("createPredicate", String.class).invoke(instance, resolved);
} else {
instance.getClass().getMethod("createExpression", String.class).invoke(instance, resolved);
}
} catch (InvocationTargetException e) {
cause = e.getTargetException();
} catch (Exception e) {
cause = e;
}
if (cause != null) {
// reverse ~^XXX^~ back to {{XXX}}
String errMsg = cause.getMessage();
errMsg = errMsg.replaceAll("\\~\\^(.+)\\^\\~", "{{$1}}");
answer.setError(errMsg);
// is it simple parser exception then we can grab the index where the problem is
if (cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleIllegalSyntaxException")
|| cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleParserException")) {
try {
// we need to grab the index field from those simple parser exceptions
Method method = cause.getClass().getMethod("getIndex");
Object result = method.invoke(cause);
if (result != null) {
int index = (int) result;
answer.setIndex(index);
}
} catch (Throwable i) {
// ignore
}
}
// we need to grab the short message field from this simple syntax exception
if (cause.getClass().getName().equals("org.apache.camel.language.simple.types.SimpleIllegalSyntaxException")) {
try {
Method method = cause.getClass().getMethod("getShortMessage");
Object result = method.invoke(cause);
if (result != null) {
String msg = (String) result;
answer.setShortError(msg);
}
} catch (Throwable i) {
// ignore
}
if (answer.getShortError() == null) {
// fallback and try to make existing message short instead
String msg = answer.getError();
// grab everything before " at location " which would be regarded as the short message
int idx = msg.indexOf(" at location ");
if (idx > 0) {
msg = msg.substring(0, idx);
answer.setShortError(msg);
}
}
}
}
}
return answer;
}
public LanguageValidationResult validateLanguagePredicate(ClassLoader classLoader, String language, String text) {
if ("simple".equals(language)) {
return doValidateSimple(classLoader, text, true);
} else {
return doValidateLanguage(classLoader, language, text, true);
}
}
public LanguageValidationResult validateLanguageExpression(ClassLoader classLoader, String language, String text) {
if ("simple".equals(language)) {
return doValidateSimple(classLoader, text, false);
} else {
return doValidateLanguage(classLoader, language, text, false);
}
}
private LanguageValidationResult doValidateLanguage(ClassLoader classLoader, String language, String text, boolean predicate) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
LanguageValidationResult answer = new LanguageValidationResult(text);
LanguageModel model = languageModel(language);
if (model == null) {
answer.setError("Unknown language " + language);
return answer;
}
String className = model.getJavaType();
if (className == null) {
answer.setError("Cannot find javaType for language " + language);
return answer;
}
Object instance = null;
Class<?> clazz = null;
try {
clazz = classLoader.loadClass(className);
instance = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
// ignore
}
if (clazz != null && instance != null) {
Throwable cause = null;
Object obj;
try {
try {
// favour using the validate method if present as this is for tooling usage
if (predicate) {
instance.getClass().getMethod("validatePredicate", String.class).invoke(instance, text);
} else {
instance.getClass().getMethod("validateExpression", String.class).invoke(instance, text);
}
} catch (NoSuchMethodException e) {
// ignore
}
// optional validate
if (predicate) {
instance.getClass().getMethod("createPredicate", String.class).invoke(instance, text);
} else {
instance.getClass().getMethod("createExpression", String.class).invoke(instance, text);
}
} catch (InvocationTargetException e) {
cause = e.getTargetException();
} catch (Exception e) {
cause = e;
}
if (cause != null) {
answer.setError(cause.getMessage());
}
}
return answer;
}
/**
* Special logic for log endpoints to deal when showAll=true
*/
private Map<String, String> filterProperties(String scheme, Map<String, String> options) {
if ("log".equals(scheme)) {
String showAll = options.get("showAll");
if ("true".equals(showAll)) {
Map<String, String> filtered = new LinkedHashMap<>();
// remove all the other showXXX options when showAll=true
for (Map.Entry<String, String> entry : options.entrySet()) {
String key = entry.getKey();
boolean skip = key.startsWith("show") && !key.equals("showAll");
if (!skip) {
filtered.put(key, entry.getValue());
}
}
return filtered;
}
}
// use as-is
return options;
}
private static boolean validateInteger(String value) {
boolean valid = false;
try {
Integer.parseInt(value);
valid = true;
} catch (Exception e) {
// ignore
}
return valid;
}
private static boolean validateDuration(String value) {
boolean valid = false;
try {
Long.parseLong(value);
valid = true;
} catch (Exception e) {
// ignore
}
if (!valid) {
try {
if (value.startsWith("P") || value.startsWith("-P") || value.startsWith("p") || value.startsWith("-p")) {
// its a duration
Duration.parse(value);
} else {
// it may be a time pattern, such as 5s for 5 seconds = 5000
TimePatternConverter.toMilliSeconds(value);
}
valid = true;
} catch (Exception e) {
// ignore
}
}
return valid;
}
private static String stripOptionalPrefixFromName(Map<String, BaseOptionModel> rows, String name) {
for (BaseOptionModel row : rows.values()) {
String optionalPrefix = row.getOptionalPrefix();
if (ObjectHelper.isNotEmpty(optionalPrefix) && name.startsWith(optionalPrefix)) {
// try again
return stripOptionalPrefixFromName(rows, name.substring(optionalPrefix.length()));
} else {
if (name.equalsIgnoreCase(row.getName())) {
break;
}
}
}
return name;
}
private static String getPropertyNameFromNameWithPrefix(Map<String, BaseOptionModel> rows, String name) {
for (BaseOptionModel row : rows.values()) {
String prefix = row.getPrefix();
if (ObjectHelper.isNotEmpty(prefix) && name.startsWith(prefix)) {
return row.getName();
}
}
return null;
}
/**
* Converts the string from dash format into camel case (hello-great-world -> helloGreatWorld)
*
* @param text the string
* @return the string camel cased
*/
private static String dashToCamelCase(String text) {
if (text == null) {
return null;
}
int length = text.length();
if (length == 0) {
return text;
}
if (text.indexOf('-') == -1) {
return text;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '-') {
i++;
sb.append(Character.toUpperCase(text.charAt(i)));
} else {
sb.append(c);
}
}
return sb.toString();
}
// CHECKSTYLE:ON
}
|
camel-catalog - Fix language validator classloading from external editors such as IDEA camel tooling
|
core/camel-core-catalog/src/main/java/org/apache/camel/catalog/impl/AbstractCamelCatalog.java
|
camel-catalog - Fix language validator classloading from external editors such as IDEA camel tooling
|
|
Java
|
apache-2.0
|
9fc91e488976a57ab2baa91532d277236de53e55
| 0
|
cscorley/solr-only-mirror,cscorley/solr-only-mirror,cscorley/solr-only-mirror
|
/*
* 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.solr.hadoop;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.lucene.util.Constants;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.cloud.AbstractZkTestCase;
import org.apache.solr.hadoop.dedup.NoChangeUpdateConflictResolver;
import org.apache.solr.hadoop.dedup.RetainMostRecentUpdateConflictResolver;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapReduceIndexerToolArgumentParserTest extends SolrTestCaseJ4 {
private Configuration conf;
private MapReduceIndexerTool.MyArgumentParser parser;
private MapReduceIndexerTool.Options opts;
private PrintStream oldSystemOut;
private PrintStream oldSystemErr;
private ByteArrayOutputStream bout;
private ByteArrayOutputStream berr;
private static final String RESOURCES_DIR = getFile("morphlines-core.marker").getParent();
private static final File MINIMR_INSTANCE_DIR = new File(RESOURCES_DIR + "/solr/minimr");
private static final String MORPHLINE_FILE = RESOURCES_DIR + "/test-morphlines/solrCellDocumentTypes.conf";
private static final Logger LOG = LoggerFactory.getLogger(MapReduceIndexerToolArgumentParserTest.class);
private final File solrHomeDirectory = createTempDir();
@BeforeClass
public static void beforeClass() {
assumeFalse("Does not work on Windows, because it uses UNIX shell commands or POSIX paths", Constants.WINDOWS);
assumeFalse("This test fails on UNIX with Turkish default locale (https://issues.apache.org/jira/browse/SOLR-6387)",
new Locale("tr").getLanguage().equals(Locale.getDefault().getLanguage()));
}
@Before
public void setUp() throws Exception {
super.setUp();
AbstractZkTestCase.SOLRHOME = solrHomeDirectory;
FileUtils.copyDirectory(MINIMR_INSTANCE_DIR, solrHomeDirectory);
conf = new Configuration();
parser = new MapReduceIndexerTool.MyArgumentParser();
opts = new MapReduceIndexerTool.Options();
oldSystemOut = System.out;
bout = new ByteArrayOutputStream();
System.setOut(new PrintStream(bout, true, "UTF-8"));
oldSystemErr = System.err;
berr = new ByteArrayOutputStream();
System.setErr(new PrintStream(berr, true, "UTF-8"));
}
@After
public void tearDown() throws Exception {
super.tearDown();
System.setOut(oldSystemOut);
System.setErr(oldSystemErr);
}
@Test
public void testArgsParserTypicalUse() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--morphline-id", "morphline_xyz",
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--mappers", "10",
"--reducers", "9",
"--fanout", "8",
"--max-segments", "7",
"--shards", "1",
"--verbose",
"file:///home",
"file:///dev",
};
Integer res = parser.parseArgs(args, conf, opts);
assertNull(res != null ? res.toString() : "", res);
assertEquals(Collections.singletonList(new Path("file:///tmp")), opts.inputLists);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEquals(10, opts.mappers);
assertEquals(9, opts.reducers);
assertEquals(8, opts.fanout);
assertEquals(7, opts.maxSegments);
assertEquals(new Integer(1), opts.shards);
assertEquals(null, opts.fairSchedulerPool);
assertTrue(opts.isVerbose);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(RetainMostRecentUpdateConflictResolver.class.getName(), opts.updateConflictResolver);
assertEquals(MORPHLINE_FILE, opts.morphlineFile.getPath());
assertEquals("morphline_xyz", opts.morphlineId);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserMultipleSpecsOfSameKind() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--input-list", "file:///",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(new Path("file:///tmp"), new Path("file:///")), opts.inputLists);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserTypicalUseWithEqualsSign() {
String[] args = new String[] {
"--input-list=file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir=file:/tmp/foo",
"--solr-home-dir=" + MINIMR_INSTANCE_DIR.getPath(),
"--mappers=10",
"--shards", "1",
"--verbose",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Collections.singletonList(new Path("file:///tmp")), opts.inputLists);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEquals(10, opts.mappers);
assertEquals(new Integer(1), opts.shards);
assertEquals(null, opts.fairSchedulerPool);
assertTrue(opts.isVerbose);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserMultipleSpecsOfSameKindWithEqualsSign() {
String[] args = new String[] {
"--input-list=file:///tmp",
"--input-list=file:///",
"--morphline-file", MORPHLINE_FILE,
"--output-dir=file:/tmp/foo",
"--solr-home-dir=" + MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(new Path("file:///tmp"), new Path("file:///")), opts.inputLists);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserHelp() throws UnsupportedEncodingException {
String[] args = new String[] { "--help" };
assertEquals(new Integer(0), parser.parseArgs(args, conf, opts));
String helpText = new String(bout.toByteArray(), StandardCharsets.UTF_8);
assertTrue(helpText.contains("MapReduce batch job driver that "));
assertTrue(helpText.contains("bin/hadoop command"));
assertEquals(0, berr.toByteArray().length);
}
@Test
public void testArgsParserOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(new Integer(1), opts.shards);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserUpdateConflictResolver() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--update-conflict-resolver", NoChangeUpdateConflictResolver.class.getName(),
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(NoChangeUpdateConflictResolver.class.getName(), opts.updateConflictResolver);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserUnknownArgName() throws Exception {
String[] args = new String[] {
"--xxxxxxxxinputlist", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserFileNotFound1() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/fileNotFound/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserFileNotFound2() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", "/fileNotFound",
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserIntOutOfRange() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--mappers", "-20"
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserIllegalFanout() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--fanout", "1" // must be >= 2
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserSolrHomeMustContainSolrConfigFile() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--shards", "1",
"--solr-home-dir", "/",
};
assertArgumentParserException(args);
}
@Test
public void testArgsShardUrlOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection2",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(
Collections.singletonList("http://localhost:8983/solr/collection1"),
Collections.singletonList("http://localhost:8983/solr/collection2")),
opts.shardUrls);
assertEquals(new Integer(2), opts.shards);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsShardUrlMustHaveAParam() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url",
};
assertArgumentParserException(args);
}
@Test
public void testArgsShardUrlAndShardsSucceeds() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--shard-url", "http://localhost:8983/solr/collection1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsShardUrlNoGoLive() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1"
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
assertEquals(new Integer(1), opts.shards);
}
@Test
public void testArgsShardUrlsAndZkhostAreMutuallyExclusive() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection1",
"--zk-host", "http://localhost:2185",
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveAndSolrUrl() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection1",
"--go-live"
};
Integer result = parser.parseArgs(args, conf, opts);
assertNull(result);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsZkHostNoGoLive() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--zk-host", "http://localhost:2185",
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveZkHostNoCollection() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--zk-host", "http://localhost:2185",
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveNoZkHostOrSolrUrl() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testNoSolrHomeDirOrZKHost() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testZKHostNoSolrHomeDirOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--zk-host", "http://localhost:2185",
"--collection", "collection1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
}
private void assertEmptySystemErrAndEmptySystemOut() {
assertEquals(0, bout.toByteArray().length);
assertEquals(0, berr.toByteArray().length);
}
private void assertArgumentParserException(String[] args) throws UnsupportedEncodingException {
assertEquals("should have returned fail code", new Integer(1), parser.parseArgs(args, conf, opts));
assertEquals("no sys out expected:" + new String(bout.toByteArray(), StandardCharsets.UTF_8), 0, bout.toByteArray().length);
String usageText;
usageText = new String(berr.toByteArray(), StandardCharsets.UTF_8);
assertTrue("should start with usage msg \"usage: hadoop \":" + usageText, usageText.startsWith("usage: hadoop "));
}
}
|
contrib/map-reduce/src/test/org/apache/solr/hadoop/MapReduceIndexerToolArgumentParserTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.hadoop;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.lucene.util.Constants;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.cloud.AbstractZkTestCase;
import org.apache.solr.hadoop.dedup.NoChangeUpdateConflictResolver;
import org.apache.solr.hadoop.dedup.RetainMostRecentUpdateConflictResolver;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MapReduceIndexerToolArgumentParserTest extends SolrTestCaseJ4 {
private Configuration conf;
private MapReduceIndexerTool.MyArgumentParser parser;
private MapReduceIndexerTool.Options opts;
private PrintStream oldSystemOut;
private PrintStream oldSystemErr;
private ByteArrayOutputStream bout;
private ByteArrayOutputStream berr;
private static final String RESOURCES_DIR = getFile("morphlines-core.marker").getParent();
private static final File MINIMR_INSTANCE_DIR = new File(RESOURCES_DIR + "/solr/minimr");
private static final String MORPHLINE_FILE = RESOURCES_DIR + "/test-morphlines/solrCellDocumentTypes.conf";
private static final Logger LOG = LoggerFactory.getLogger(MapReduceIndexerToolArgumentParserTest.class);
private final File solrHomeDirectory = createTempDir();
@BeforeClass
public static void beforeClass() {
assumeFalse("Does not work on Windows, because it uses UNIX shell commands or POSIX paths", Constants.WINDOWS);
}
@Before
public void setUp() throws Exception {
super.setUp();
AbstractZkTestCase.SOLRHOME = solrHomeDirectory;
FileUtils.copyDirectory(MINIMR_INSTANCE_DIR, solrHomeDirectory);
conf = new Configuration();
parser = new MapReduceIndexerTool.MyArgumentParser();
opts = new MapReduceIndexerTool.Options();
oldSystemOut = System.out;
bout = new ByteArrayOutputStream();
System.setOut(new PrintStream(bout, true, "UTF-8"));
oldSystemErr = System.err;
berr = new ByteArrayOutputStream();
System.setErr(new PrintStream(berr, true, "UTF-8"));
}
@After
public void tearDown() throws Exception {
super.tearDown();
System.setOut(oldSystemOut);
System.setErr(oldSystemErr);
}
@Test
public void testArgsParserTypicalUse() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--morphline-id", "morphline_xyz",
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--mappers", "10",
"--reducers", "9",
"--fanout", "8",
"--max-segments", "7",
"--shards", "1",
"--verbose",
"file:///home",
"file:///dev",
};
Integer res = parser.parseArgs(args, conf, opts);
assertNull(res != null ? res.toString() : "", res);
assertEquals(Collections.singletonList(new Path("file:///tmp")), opts.inputLists);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEquals(10, opts.mappers);
assertEquals(9, opts.reducers);
assertEquals(8, opts.fanout);
assertEquals(7, opts.maxSegments);
assertEquals(new Integer(1), opts.shards);
assertEquals(null, opts.fairSchedulerPool);
assertTrue(opts.isVerbose);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(RetainMostRecentUpdateConflictResolver.class.getName(), opts.updateConflictResolver);
assertEquals(MORPHLINE_FILE, opts.morphlineFile.getPath());
assertEquals("morphline_xyz", opts.morphlineId);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserMultipleSpecsOfSameKind() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--input-list", "file:///",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(new Path("file:///tmp"), new Path("file:///")), opts.inputLists);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserTypicalUseWithEqualsSign() {
String[] args = new String[] {
"--input-list=file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir=file:/tmp/foo",
"--solr-home-dir=" + MINIMR_INSTANCE_DIR.getPath(),
"--mappers=10",
"--shards", "1",
"--verbose",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Collections.singletonList(new Path("file:///tmp")), opts.inputLists);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEquals(10, opts.mappers);
assertEquals(new Integer(1), opts.shards);
assertEquals(null, opts.fairSchedulerPool);
assertTrue(opts.isVerbose);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserMultipleSpecsOfSameKindWithEqualsSign() {
String[] args = new String[] {
"--input-list=file:///tmp",
"--input-list=file:///",
"--morphline-file", MORPHLINE_FILE,
"--output-dir=file:/tmp/foo",
"--solr-home-dir=" + MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"file:///home",
"file:///dev",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(new Path("file:///tmp"), new Path("file:///")), opts.inputLists);
assertEquals(Arrays.asList(new Path("file:///home"), new Path("file:///dev")), opts.inputFiles);
assertEquals(new Path("file:/tmp/foo"), opts.outputDir);
assertEquals(new File(MINIMR_INSTANCE_DIR.getPath()), opts.solrHomeDir);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserHelp() throws UnsupportedEncodingException {
String[] args = new String[] { "--help" };
assertEquals(new Integer(0), parser.parseArgs(args, conf, opts));
String helpText = new String(bout.toByteArray(), StandardCharsets.UTF_8);
assertTrue(helpText.contains("MapReduce batch job driver that "));
assertTrue(helpText.contains("bin/hadoop command"));
assertEquals(0, berr.toByteArray().length);
}
@Test
public void testArgsParserOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(new Integer(1), opts.shards);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserUpdateConflictResolver() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--update-conflict-resolver", NoChangeUpdateConflictResolver.class.getName(),
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(NoChangeUpdateConflictResolver.class.getName(), opts.updateConflictResolver);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsParserUnknownArgName() throws Exception {
String[] args = new String[] {
"--xxxxxxxxinputlist", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserFileNotFound1() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/fileNotFound/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserFileNotFound2() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", "/fileNotFound",
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserIntOutOfRange() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--mappers", "-20"
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserIllegalFanout() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--fanout", "1" // must be >= 2
};
assertArgumentParserException(args);
}
@Test
public void testArgsParserSolrHomeMustContainSolrConfigFile() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--shards", "1",
"--solr-home-dir", "/",
};
assertArgumentParserException(args);
}
@Test
public void testArgsShardUrlOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection2",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEquals(Arrays.asList(
Collections.singletonList("http://localhost:8983/solr/collection1"),
Collections.singletonList("http://localhost:8983/solr/collection2")),
opts.shardUrls);
assertEquals(new Integer(2), opts.shards);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsShardUrlMustHaveAParam() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url",
};
assertArgumentParserException(args);
}
@Test
public void testArgsShardUrlAndShardsSucceeds() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shards", "1",
"--shard-url", "http://localhost:8983/solr/collection1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsShardUrlNoGoLive() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1"
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
assertEquals(new Integer(1), opts.shards);
}
@Test
public void testArgsShardUrlsAndZkhostAreMutuallyExclusive() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection1",
"--zk-host", "http://localhost:2185",
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveAndSolrUrl() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--shard-url", "http://localhost:8983/solr/collection1",
"--shard-url", "http://localhost:8983/solr/collection1",
"--go-live"
};
Integer result = parser.parseArgs(args, conf, opts);
assertNull(result);
assertEmptySystemErrAndEmptySystemOut();
}
@Test
public void testArgsZkHostNoGoLive() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--zk-host", "http://localhost:2185",
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveZkHostNoCollection() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--zk-host", "http://localhost:2185",
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testArgsGoLiveNoZkHostOrSolrUrl() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--solr-home-dir", MINIMR_INSTANCE_DIR.getPath(),
"--go-live"
};
assertArgumentParserException(args);
}
@Test
public void testNoSolrHomeDirOrZKHost() throws Exception {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--shards", "1",
};
assertArgumentParserException(args);
}
@Test
public void testZKHostNoSolrHomeDirOk() {
String[] args = new String[] {
"--input-list", "file:///tmp",
"--morphline-file", MORPHLINE_FILE,
"--output-dir", "file:/tmp/foo",
"--zk-host", "http://localhost:2185",
"--collection", "collection1",
};
assertNull(parser.parseArgs(args, conf, opts));
assertEmptySystemErrAndEmptySystemOut();
}
private void assertEmptySystemErrAndEmptySystemOut() {
assertEquals(0, bout.toByteArray().length);
assertEquals(0, berr.toByteArray().length);
}
private void assertArgumentParserException(String[] args) throws UnsupportedEncodingException {
assertEquals("should have returned fail code", new Integer(1), parser.parseArgs(args, conf, opts));
assertEquals("no sys out expected:" + new String(bout.toByteArray(), StandardCharsets.UTF_8), 0, bout.toByteArray().length);
String usageText;
usageText = new String(berr.toByteArray(), StandardCharsets.UTF_8);
assertTrue("should start with usage msg \"usage: hadoop \":" + usageText, usageText.startsWith("usage: hadoop "));
}
}
|
SOLR-6387: additional map-reduce test that does forking and needs 'tr' check
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1620707 13f79535-47bb-0310-9956-ffa450edef68
|
contrib/map-reduce/src/test/org/apache/solr/hadoop/MapReduceIndexerToolArgumentParserTest.java
|
SOLR-6387: additional map-reduce test that does forking and needs 'tr' check
|
|
Java
|
apache-2.0
|
813b913409ddecca7a7525cce23789be2f22c724
| 0
|
gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle
|
/*
* Copyright 2020 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.gradle.docs.samples;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.logging.configuration.WarningMode;
import org.gradle.integtests.fixtures.executer.ExecutionFailure;
import org.gradle.integtests.fixtures.executer.ExecutionResult;
import org.gradle.integtests.fixtures.executer.GradleContextualExecuter;
import org.gradle.integtests.fixtures.executer.GradleDistribution;
import org.gradle.integtests.fixtures.executer.GradleExecuter;
import org.gradle.integtests.fixtures.executer.IntegrationTestBuildContext;
import org.gradle.integtests.fixtures.executer.UnderDevelopmentGradleDistribution;
import org.gradle.samples.executor.CommandExecutor;
import org.gradle.test.fixtures.file.TestNameTestDirectoryProvider;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class IntegrationTestSamplesExecutor extends CommandExecutor {
private static final String WARNING_MODE_FLAG_PREFIX = "--warning-mode=";
private final File workingDir;
private final boolean expectFailure;
private final GradleExecuter gradle;
public IntegrationTestSamplesExecutor(File workingDir, boolean expectFailure) {
this.workingDir = workingDir;
this.expectFailure = expectFailure;
GradleDistribution distribution = new UnderDevelopmentGradleDistribution(IntegrationTestBuildContext.INSTANCE);
this.gradle = new GradleContextualExecuter(distribution, new TestNameTestDirectoryProvider(IntegrationTestSamplesExecutor.class), IntegrationTestBuildContext.INSTANCE);
}
@Override
protected int run(String executable, List<String> args, List<String> flags, OutputStream outputStream) {
List<String> filteredFlags = new ArrayList<>();
WarningMode warningMode = WarningMode.Fail;
for (String flag : flags) {
if (flag.startsWith(WARNING_MODE_FLAG_PREFIX)) {
warningMode = WarningMode.valueOf(capitalize(flag.replace(WARNING_MODE_FLAG_PREFIX, "").toLowerCase()));
} else {
filteredFlags.add(flag);
}
}
GradleExecuter executer = gradle.inDirectory(workingDir).ignoreMissingSettingsFile()
.withStacktraceDisabled()
.noDeprecationChecks()
.withWarningMode(warningMode)
.withArguments(filteredFlags)
.withTasks(args);
try {
if (expectFailure) {
ExecutionFailure result = executer.runWithFailure();
outputStream.write((result.getOutput() + result.getError()).getBytes());
} else {
ExecutionResult result = executer.run();
outputStream.write(result.getOutput().getBytes());
}
return expectFailure ? 1 : 0;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static String capitalize(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
|
subprojects/docs/src/docsTest/java/org/gradle/docs/samples/IntegrationTestSamplesExecutor.java
|
/*
* Copyright 2020 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.gradle.docs.samples;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.logging.configuration.WarningMode;
import org.gradle.integtests.fixtures.executer.ExecutionFailure;
import org.gradle.integtests.fixtures.executer.ExecutionResult;
import org.gradle.integtests.fixtures.executer.GradleContextualExecuter;
import org.gradle.integtests.fixtures.executer.GradleDistribution;
import org.gradle.integtests.fixtures.executer.GradleExecuter;
import org.gradle.integtests.fixtures.executer.IntegrationTestBuildContext;
import org.gradle.integtests.fixtures.executer.UnderDevelopmentGradleDistribution;
import org.gradle.samples.executor.CommandExecutor;
import org.gradle.test.fixtures.file.TestNameTestDirectoryProvider;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class IntegrationTestSamplesExecutor extends CommandExecutor {
private static final String WARNING_MODE_FLAG_PREFIX = "--warning-mode=";
private final File workingDir;
private final boolean expectFailure;
private final GradleExecuter gradle;
public IntegrationTestSamplesExecutor(File workingDir, boolean expectFailure) {
this.workingDir = workingDir;
this.expectFailure = expectFailure;
GradleDistribution distribution = new UnderDevelopmentGradleDistribution(getBuildContext());
this.gradle = new GradleContextualExecuter(distribution, new TestNameTestDirectoryProvider(IntegrationTestSamplesExecutor.class), getBuildContext());
}
@Override
protected int run(String executable, List<String> args, List<String> flags, OutputStream outputStream) {
List<String> filteredFlags = new ArrayList<>();
WarningMode warningMode = WarningMode.Fail;
for (String flag : flags) {
if (flag.startsWith(WARNING_MODE_FLAG_PREFIX)) {
warningMode = WarningMode.valueOf(capitalize(flag.replace(WARNING_MODE_FLAG_PREFIX, "").toLowerCase()));
} else {
filteredFlags.add(flag);
}
}
GradleExecuter executer = gradle.inDirectory(workingDir).ignoreMissingSettingsFile()
.withStacktraceDisabled()
.noDeprecationChecks()
.withWarningMode(warningMode)
.withArguments(filteredFlags)
.withTasks(args);
try {
if (expectFailure) {
ExecutionFailure result = executer.runWithFailure();
outputStream.write((result.getOutput() + result.getError()).getBytes());
} else {
ExecutionResult result = executer.run();
outputStream.write(result.getOutput().getBytes());
}
return expectFailure ? 1 : 0;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static IntegrationTestBuildContext getBuildContext() {
return IntegrationTestBuildContext.INSTANCE;
}
private static String capitalize(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
|
Inline private method
|
subprojects/docs/src/docsTest/java/org/gradle/docs/samples/IntegrationTestSamplesExecutor.java
|
Inline private method
|
|
Java
|
apache-2.0
|
77f997b1d6c4ef3fe8fbf608e5916b219103808b
| 0
|
adufilie/flex-falcon,greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon
|
/*
*
* 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.flex.compiler.internal.tree.mxml;
import static org.junit.Assert.*;
import static org.hamcrest.core.Is.is;
import org.apache.flex.compiler.definitions.IClassDefinition;
import org.apache.flex.compiler.tree.ASTNodeID;
import org.apache.flex.compiler.tree.mxml.IMXMLClassDefinitionNode;
import org.apache.flex.compiler.tree.mxml.IMXMLClassNode;
import org.apache.flex.compiler.tree.mxml.IMXMLComponentNode;
import org.apache.flex.compiler.tree.mxml.IMXMLFileNode;
import org.junit.Test;
/**
* JUnit tests for {@link MXMLComponentNode}.
*
* @author Gordon Smith
*/
public class MXMLComponentNodeTests extends MXMLInstanceNodeTests
{
private IMXMLComponentNode getMXMLComponentNode(String[] code)
{
IMXMLFileNode fileNode = getMXMLFileNodeWithFlex(code);
IMXMLComponentNode node = (IMXMLComponentNode)findFirstDescendantOfType(fileNode, IMXMLComponentNode.class);
assertThat("getNodeID", node.getNodeID(), is(ASTNodeID.MXMLComponentID));
//assertThat("getName", node.getName(), is("Component"));
return node;
}
// Note: getClassName() always returns null for an IMXMLComponentNode.
// It is non-null in the case of an IFactoryNode that gets created
// for the value of a property of type IFactory.
@Test
public void MXMLComponentNode_empty1()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component/></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(0));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is((IMXMLClassDefinitionNode)null));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition(), is((IClassDefinition)null));
}
@Test
public void MXMLComponentNode_empty2()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component>",
"</fx:Component></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(0));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is((IMXMLClassDefinitionNode)null));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition(), is((IClassDefinition)null));
}
@Test
public void MXMLComponentNode_Sprite()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component>",
" <d:Sprite/>",
"</fx:Component></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_className_Sprite()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component className='MySprite'>",
" <d:Sprite/>",
"</fx:Component></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is("MySprite"));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_id_Sprite()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component id='c1'>",
" <d:Sprite/>",
"</fx:Component></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is("c1"));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_className_id_Sprite_width_height()
{
String[] code = new String[]
{
"<fx:Declarations><fx:Component id='c1' className='MySprite'>",
" <d:Sprite width='100'>",
" <d:height>100</d:height>",
" </d:Sprite>",
"</fx:Component></fx:Declarations>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is("c1"));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is("MySprite"));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
assertThat("getContainedClassDefinitionNode.getChildCount", node.getContainedClassDefinitionNode().getChildCount(), is(2));
}
}
|
compiler.tests/unit-tests/org/apache/flex/compiler/internal/tree/mxml/MXMLComponentNodeTests.java
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.internal.tree.mxml;
import static org.junit.Assert.*;
import static org.hamcrest.core.Is.is;
import org.apache.flex.compiler.definitions.IClassDefinition;
import org.apache.flex.compiler.tree.ASTNodeID;
import org.apache.flex.compiler.tree.mxml.IMXMLClassDefinitionNode;
import org.apache.flex.compiler.tree.mxml.IMXMLClassNode;
import org.apache.flex.compiler.tree.mxml.IMXMLComponentNode;
import org.apache.flex.compiler.tree.mxml.IMXMLFileNode;
import org.junit.Test;
/**
* JUnit tests for {@link MXMLComponentNode}.
*
* @author Gordon Smith
*/
public class MXMLComponentNodeTests extends MXMLInstanceNodeTests
{
private IMXMLComponentNode getMXMLComponentNode(String[] code)
{
IMXMLFileNode fileNode = getMXMLFileNode(code);
IMXMLComponentNode node = (IMXMLComponentNode)findFirstDescendantOfType(fileNode, IMXMLComponentNode.class);
assertThat("getNodeID", node.getNodeID(), is(ASTNodeID.MXMLComponentID));
//assertThat("getName", node.getName(), is("Component"));
return node;
}
// Note: getClassName() always returns null for an IMXMLComponentNode.
// It is non-null in the case of an IFactoryNode that gets created
// for the value of a property of type IFactory.
@Test
public void MXMLComponentNode_empty1()
{
String[] code = new String[]
{
"<fx:Component/>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(0));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is((IMXMLClassDefinitionNode)null));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition(), is((IClassDefinition)null));
}
@Test
public void MXMLComponentNode_empty2()
{
String[] code = new String[]
{
"<fx:Component>",
"</fx:Component>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(0));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is((IMXMLClassDefinitionNode)null));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition(), is((IClassDefinition)null));
}
@Test
public void MXMLComponentNode_Sprite()
{
String[] code = new String[]
{
"<fx:Component>",
" <d:Sprite/>",
"</fx:Component>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_className_Sprite()
{
String[] code = new String[]
{
"<fx:Component className='MySprite'>",
" <d:Sprite/>",
"</fx:Component>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is((String)null));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is("MySprite"));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_id_Sprite()
{
String[] code = new String[]
{
"<fx:Component id='c1'>",
" <d:Sprite/>",
"</fx:Component>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is("c1"));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is((String)null));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
}
@Test
public void MXMLComponentNode_className_id_Sprite_width_height()
{
String[] code = new String[]
{
"<fx:Component id='c1' className='MySprite'>",
" <d:Sprite width='100'>",
" <d:height>100</d:height>",
" </d:Sprite>",
"</fx:Component>"
};
IMXMLComponentNode node = getMXMLComponentNode(code);
assertThat("getChildCount", node.getChildCount(), is(1));
assertThat("getID", node.getID(), is("c1"));
assertThat("getClassNode", node.getClassNode(), is((IMXMLClassNode)null));
assertThat("getClassName", node.getClassName(), is("MySprite"));
assertThat("getContainedClassDefinitionNode", node.getContainedClassDefinitionNode(), is(node.getChild(0)));
assertThat("getContainedClassDefinition", node.getContainedClassDefinition().isInstanceOf("flash.display.Sprite", project), is(true));
assertThat("getContainedClassDefinitionNode.getChildCount", node.getContainedClassDefinitionNode().getChildCount(), is(2));
}
}
|
all of a sudden this test wants to be wrapped in fx:Declaration which I think it should always have been. Not sure how it passed before
|
compiler.tests/unit-tests/org/apache/flex/compiler/internal/tree/mxml/MXMLComponentNodeTests.java
|
all of a sudden this test wants to be wrapped in fx:Declaration which I think it should always have been. Not sure how it passed before
|
|
Java
|
apache-2.0
|
837d4cd9e981604529d796d23e6833edfa87dbea
| 0
|
hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak
|
package com.sequenceiq.cloudbreak.cloud.aws;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.amazonaws.services.ec2.model.DescribeRouteTablesResult;
import com.amazonaws.services.ec2.model.Route;
import com.amazonaws.services.ec2.model.RouteTable;
import com.amazonaws.services.ec2.model.RouteTableAssociation;
@Component
public class AwsSubnetIgwExplorer {
private static final Logger LOGGER = LoggerFactory.getLogger(AwsSubnetIgwExplorer.class);
private static final String OPEN_CIDR_BLOCK = "0.0.0.0/0";
private static final String IGW_PREFIX = "igw-";
public boolean hasInternetGatewayOfSubnet(DescribeRouteTablesResult describeRouteTablesResult, String subnetId, String vpcId) {
Set<RouteTable> routeTables = getRouteTableForSubnet(describeRouteTablesResult, subnetId, vpcId);
return hasInternetGateway(routeTables, subnetId, vpcId);
}
private Set<RouteTable> getRouteTableForSubnet(DescribeRouteTablesResult describeRouteTablesResult, String subnetId, String vpcId) {
List<RouteTable> routeTables = describeRouteTablesResult.getRouteTables();
Set<RouteTable> connectedRouteTables = new HashSet<>();
for (RouteTable rt : routeTables) {
if (rt.getVpcId().equalsIgnoreCase(vpcId)) {
LOGGER.debug("Analyzing the route table('{}') for the VPC id is:'{}' and the subnet is :'{}'", rt, vpcId, subnetId);
for (RouteTableAssociation association : rt.getAssociations()) {
LOGGER.debug("Analyzing the association('{}') for the VCP id is:'{}' and the subnet is :'{}'", association, vpcId, subnetId);
if (StringUtils.isEmpty(association.getSubnetId()) && association.isMain()) {
LOGGER.debug("Found a route table('{}') which is 'Main'/default for the VPC('{}'), "
+ "doesn't need to check the subnet id as it is not returned in this case", rt, vpcId);
connectedRouteTables.add(rt);
} else if (subnetId.equalsIgnoreCase(association.getSubnetId())) {
LOGGER.info("Found the route table('{}') which is explicitly connected to the subnet('{}')", rt, subnetId);
connectedRouteTables.add(rt);
break;
}
}
}
}
return connectedRouteTables;
}
private boolean hasInternetGateway(Set<RouteTable> routeTables, String subnetId, String vpcId) {
if (!routeTables.isEmpty()) {
for (RouteTable routeTable : routeTables) {
for (Route route : routeTable.getRoutes()) {
LOGGER.debug("Searching the route which is open. the route is {} and the subnet is :{}", route, subnetId);
if (StringUtils.isNotEmpty(route.getGatewayId()) && route.getGatewayId().startsWith(IGW_PREFIX)
&& OPEN_CIDR_BLOCK.equals(route.getDestinationCidrBlock())) {
LOGGER.info("Found the route('{}') with internet gateway for the subnet ('{}') within VPC('{}')", route, subnetId, vpcId);
return true;
}
}
}
}
LOGGER.info("Internet gateway with route that has '{}' as destination CIDR block could not be found for subnet('{}') within VPC('{}')",
OPEN_CIDR_BLOCK, subnetId, vpcId);
return false;
}
}
|
cloud-aws/src/main/java/com/sequenceiq/cloudbreak/cloud/aws/AwsSubnetIgwExplorer.java
|
package com.sequenceiq.cloudbreak.cloud.aws;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.amazonaws.services.ec2.model.DescribeRouteTablesResult;
import com.amazonaws.services.ec2.model.Route;
import com.amazonaws.services.ec2.model.RouteTable;
import com.amazonaws.services.ec2.model.RouteTableAssociation;
@Component
public class AwsSubnetIgwExplorer {
private static final Logger LOGGER = LoggerFactory.getLogger(AwsSubnetIgwExplorer.class);
private static final String OPEN_CIDR_BLOCK = "0.0.0.0/0";
private static final String IGW_PREFIX = "igw-";
public boolean hasInternetGatewayOfSubnet(DescribeRouteTablesResult describeRouteTablesResult, String subnetId, String vpcId) {
Set<RouteTable> routeTables = getRouteTableForSubnet(describeRouteTablesResult, subnetId, vpcId);
return hasInternetGateway(routeTables, subnetId, vpcId);
}
private Set<RouteTable> getRouteTableForSubnet(DescribeRouteTablesResult describeRouteTablesResult, String subnetId, String vpcId) {
List<RouteTable> routeTables = describeRouteTablesResult.getRouteTables();
Set<RouteTable> connectedRouteTables = new HashSet<>();
for (RouteTable rt : routeTables) {
if (rt.getVpcId().equalsIgnoreCase(vpcId) || rt.getVpcId().startsWith(vpcId)) {
LOGGER.debug("Analyzing the route table('{}') for the VPC id is:'{}' and the subnet is :'{}'", rt, vpcId, subnetId);
for (RouteTableAssociation association : rt.getAssociations()) {
LOGGER.debug("Analyzing the association('{}') for the VCP id is:'{}' and the subnet is :'{}'", association, vpcId, subnetId);
if (StringUtils.isEmpty(association.getSubnetId()) && association.isMain()) {
LOGGER.debug("Found a route table('{}') which is 'Main'/default for the VPC('{}'), "
+ "doesn't need to check the subnet id as it is not returned in this case", rt, vpcId);
connectedRouteTables.add(rt);
} else if (subnetId.equalsIgnoreCase(association.getSubnetId())
|| (StringUtils.isNotEmpty(association.getSubnetId()) && association.getSubnetId().startsWith(subnetId))) {
LOGGER.info("Found the route table('{}') which is explicitly connected to the subnet('{}')", rt, subnetId);
connectedRouteTables.add(rt);
break;
}
}
}
}
return connectedRouteTables;
}
private boolean hasInternetGateway(Set<RouteTable> routeTables, String subnetId, String vpcId) {
if (!routeTables.isEmpty()) {
for (RouteTable routeTable : routeTables) {
for (Route route : routeTable.getRoutes()) {
LOGGER.debug("Searching the route which is open. the route is {} and the subnet is :{}", route, subnetId);
if (StringUtils.isNotEmpty(route.getGatewayId()) && route.getGatewayId().startsWith(IGW_PREFIX)
&& OPEN_CIDR_BLOCK.equals(route.getDestinationCidrBlock())) {
LOGGER.info("Found the route('{}') with internet gateway for the subnet ('{}') within VPC('{}')", route, subnetId, vpcId);
return true;
}
}
}
}
LOGGER.info("Internet gateway with route that has '{}' as destination CIDR block could not be found for subnet('{}') within VPC('{}')",
OPEN_CIDR_BLOCK, subnetId, vpcId);
return false;
}
}
|
Revert "CB-10638 Aws IGW check should support long and short aws names"
This reverts commit 35b92accb051e237d8110c95fcbdab8437bea0c4.
|
cloud-aws/src/main/java/com/sequenceiq/cloudbreak/cloud/aws/AwsSubnetIgwExplorer.java
|
Revert "CB-10638 Aws IGW check should support long and short aws names"
|
|
Java
|
apache-2.0
|
a74876616859d2b13b61761e24ad2de71e6b0d86
| 0
|
chibenwa/james,rouazana/james,rouazana/james,aduprat/james,chibenwa/james,aduprat/james,aduprat/james,rouazana/james,aduprat/james,rouazana/james,chibenwa/james,chibenwa/james
|
/****************************************************************
* 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.james.transport.mailets;
import org.apache.avalon.cornerstone.services.store.Store;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.james.Constants;
import org.apache.james.api.dnsservice.DNSService;
import org.apache.james.api.dnsservice.TemporaryResolutionException;
import org.apache.james.services.SpoolRepository;
import org.apache.james.util.TimeConverter;
import org.apache.mailet.base.GenericMailet;
import org.apache.mailet.HostAddress;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.MailetContext;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimePart;
import javax.mail.internet.ParseException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* <p>Receives a MessageContainer from JamesSpoolManager and takes care of delivery
* the message to remote hosts. If for some reason mail can't be delivered
* store it in the "outgoing" Repository and set an Alarm. After the next "delayTime" the
* Alarm will wake the servlet that will try to send it again. After "maxRetries"
* the mail will be considered undeliverable and will be returned to sender.
* </p><p>
* TO DO (in priority):
* </p>
* <ol>
* <li>Support a gateway (a single server where all mail will be delivered) (DONE)</li>
* <li>Provide better failure messages (DONE)</li>
* <li>More efficiently handle numerous recipients</li>
* <li>Migrate to use Phoenix for the delivery threads</li>
* </ol>
* <p>
* You really want to read the JavaMail documentation if you are
* working in here, and you will want to view the list of JavaMail
* attributes, which are documented
* <a href='http://java.sun.com/products/javamail/1.3/docs/javadocs/com/sun/mail/smtp/package-summary.html'>here</a>
* as well as other places.</p>
*
* @version CVS $Revision$ $Date$
*/
public class RemoteDelivery extends GenericMailet implements Runnable {
/** Default Delay Time (Default is 6*60*60*1000 Milliseconds (6 hours)). */
private static final long DEFAULT_DELAY_TIME = 21600000;
/** Pattern to match [attempts*]delay[units]. */
private static final String PATTERN_STRING = "\\s*([0-9]*\\s*[\\*])?\\s*([0-9]+)\\s*([a-z,A-Z]*)\\s*";
/** Compiled pattern of the above String. */
private static Pattern PATTERN = null;
/** The DNSService */
private DNSService dnsServer;
/**
* Static initializer.<p>
* Compiles pattern for processing delaytime entries.<p>
* Initializes MULTIPLIERS with the supported unit quantifiers
*/
static {
try {
Perl5Compiler compiler = new Perl5Compiler();
PATTERN = compiler.compile(PATTERN_STRING, Perl5Compiler.READ_ONLY_MASK);
} catch(MalformedPatternException mpe) {
//this should not happen as the pattern string is hardcoded.
mpe.printStackTrace (System.err);
}
}
/**
* This filter is used in the accept call to the spool.
* It will select the next mail ready for processing according to the mails
* retrycount and lastUpdated time
**/
private class MultipleDelayFilter implements SpoolRepository.AcceptFilter {
/**
* holds the time to wait for the youngest mail to get ready for processing
**/
long youngest = 0;
/**
* Uses the getNextDelay to determine if a mail is ready for processing based on the delivered parameters
* errorMessage (which holds the retrycount), lastUpdated and state
* @param key the name/key of the message
* @param state the mails state
* @param lastUpdated the mail was last written to the spool at this time.
* @param errorMessage actually holds the retrycount as a string (see failMessage below)
**/
public boolean accept (String key, String state, long lastUpdated, String errorMessage) {
if (state.equals(Mail.ERROR)) {
//Test the time...
int retries = 0;
try {
retries = Integer.parseInt(errorMessage);
} catch (NumberFormatException e) {
// Something strange was happen with the errorMessage.. Ignore the Exception and try
// to deliver it now!
}
// If the retries count is 0 we should try to send the mail now!
if (retries == 0) return true;
long delay = getNextDelay (retries);
long timeToProcess = delay + lastUpdated;
if (System.currentTimeMillis() > timeToProcess) {
//We're ready to process this again
return true;
} else {
//We're not ready to process this.
if (youngest == 0 || youngest > timeToProcess) {
//Mark this as the next most likely possible mail to process
youngest = timeToProcess;
}
return false;
}
} else {
//This mail is good to go... return the key
return true;
}
}
/**
* @return the optimal time the SpoolRepository.accept(AcceptFilter) method should wait before
* trying to find a mail ready for processing again.
**/
public long getWaitTime () {
if (youngest == 0) {
return 0;
} else {
long duration = youngest - System.currentTimeMillis();
youngest = 0; //get ready for next run
return duration <= 0 ? 1 : duration;
}
}
}
/** Flag to define verbose logging messages. */
private boolean isDebug = false;
/** Repository used to store messages that will be delivered. */
private SpoolRepository workRepository;
/** List of Delay Times. Controls frequency of retry attempts. */
private long[] delayTimes;
/** Maximum no. of retries (Defaults to 5). */
private int maxRetries = 5;
/** Default number of ms to timeout on smtp delivery */
private long smtpTimeout = 180000;
/** If false then ANY address errors will cause the transmission to fail */
private boolean sendPartial = false;
/** The amount of time JavaMail will wait before giving up on a socket connect() */
private int connectionTimeout = 60000;
/** No. of threads used to process messages that should be retried. */
private int workersThreadCount = 1;
/** The server(s) to send all email to */
private Collection gatewayServer = null;
/** Auth for gateway server */
private String authUser = null;
/** Password for gateway server */
private String authPass = null;
/**
* JavaMail delivery socket binds to this local address.
* If null the JavaMail default will be used.
*/
private String bindAddress = null;
/**
* True, if the bind configuration parameter is supplied, RemoteDeliverySocketFactory
* will be used in this case.
*/
private boolean isBindUsed = false;
/** Collection that stores all worker threads.*/
private Collection workersThreads = new Vector();
/** Flag used by 'run' method to end itself. */
private volatile boolean destroyed = false;
/** the processor for creating Bounces */
private String bounceProcessor = null;
/**
* Matcher used in 'init' method to parse delayTimes specified in config
* file.
*/
private Perl5Matcher delayTimeMatcher;
/**
* Filter used by 'accept' to check if message is ready for retrying.
*/
private MultipleDelayFilter delayFilter = new MultipleDelayFilter();
/** Default properties for the JavaMail Session */
private Properties defprops = new Properties();
/** The retry count dnsProblemErrors */
private int dnsProblemRetry = 0;
/**
* Initializes all arguments based on configuration values specified in the
* James configuration file.
*
* @throws MessagingException
* on failure to initialize attributes.
*/
public void init() throws MessagingException {
// Set isDebug flag.
isDebug = (getInitParameter("debug") == null) ? false : new Boolean(getInitParameter("debug")).booleanValue();
// Create list of Delay Times.
ArrayList delayTimesList = new ArrayList();
try {
if (getInitParameter("delayTime") != null) {
delayTimeMatcher = new Perl5Matcher();
String delayTimesParm = getInitParameter("delayTime");
// Split on commas
StringTokenizer st = new StringTokenizer (delayTimesParm,",");
while (st.hasMoreTokens()) {
String delayTime = st.nextToken();
delayTimesList.add (new Delay(delayTime));
}
} else {
// Use default delayTime.
delayTimesList.add (new Delay());
}
} catch (Exception e) {
log("Invalid delayTime setting: " + getInitParameter("delayTime"));
}
try {
// Get No. of Max Retries.
if (getInitParameter("maxRetries") != null) {
maxRetries = Integer.parseInt(getInitParameter("maxRetries"));
}
// Check consistency of 'maxRetries' with delayTimesList attempts.
int totalAttempts = calcTotalAttempts(delayTimesList);
// If inconsistency found, fix it.
if (totalAttempts > maxRetries) {
log("Total number of delayTime attempts exceeds maxRetries specified. "
+ " Increasing maxRetries from "
+ maxRetries
+ " to "
+ totalAttempts);
maxRetries = totalAttempts;
} else {
int extra = maxRetries - totalAttempts;
if (extra != 0) {
log("maxRetries is larger than total number of attempts specified. "
+ "Increasing last delayTime with "
+ extra
+ " attempts ");
// Add extra attempts to the last delayTime.
if (delayTimesList.size() != 0) {
// Get the last delayTime.
Delay delay = (Delay) delayTimesList.get(delayTimesList
.size() - 1);
// Increase no. of attempts.
delay.setAttempts(delay.getAttempts() + extra);
log("Delay of " + delay.getDelayTime()
+ " msecs is now attempted: " + delay.getAttempts()
+ " times");
} else {
throw new MessagingException(
"No delaytimes, cannot continue");
}
}
}
delayTimes = expandDelays(delayTimesList);
} catch (Exception e) {
log("Invalid maxRetries setting: " + getInitParameter("maxRetries"));
}
ServiceManager compMgr = (ServiceManager) getMailetContext()
.getAttribute(Constants.AVALON_COMPONENT_MANAGER);
// Get the path for the 'Outgoing' repository. This is the place on the
// file system where Mail objects will be saved during the 'delivery'
// processing. This can be changed to a repository on a database (e.g.
// db://maildb/spool/retry).
String workRepositoryPath = getInitParameter("outgoing");
if (workRepositoryPath == null) {
workRepositoryPath = "file:///../var/mail/outgoing";
}
try {
// Instantiate a MailRepository for mails to be processed.
Store mailstore = (Store) compMgr.lookup(Store.ROLE);
DefaultConfiguration spoolConf = new DefaultConfiguration(
"repository", "generated:RemoteDelivery");
spoolConf.setAttribute("destinationURL", workRepositoryPath);
spoolConf.setAttribute("type", "SPOOL");
workRepository = (SpoolRepository) mailstore.select(spoolConf);
} catch (ServiceException cnfe) {
log("Failed to retrieve Store component:" + cnfe.getMessage());
throw new MessagingException("Failed to retrieve Store component",
cnfe);
}
// Start Workers Threads.
workersThreadCount = Integer.parseInt(getInitParameter("deliveryThreads"));
for (int i = 0; i < workersThreadCount; i++) {
String threadName = "Remote delivery thread (" + i + ")";
Thread t = new Thread(this, threadName);
t.start();
workersThreads.add(t);
}
try {
if (getInitParameter("timeout") != null) {
smtpTimeout = Integer.parseInt(getInitParameter("timeout"));
}
} catch (Exception e) {
log("Invalid timeout setting: " + getInitParameter("timeout"));
}
try {
if (getInitParameter("connectiontimeout") != null) {
connectionTimeout = Integer.parseInt(getInitParameter("connectiontimeout"));
}
} catch (Exception e) {
log("Invalid timeout setting: " + getInitParameter("timeout"));
}
sendPartial = (getInitParameter("sendpartial") == null) ? false : new Boolean(getInitParameter("sendpartial")).booleanValue();
bounceProcessor = getInitParameter("bounceProcessor");
String gateway = getInitParameter("gateway");
String gatewayPort = getInitParameter("gatewayPort");
if (gateway != null) {
gatewayServer = new ArrayList();
StringTokenizer st = new StringTokenizer(gateway, ",") ;
while (st.hasMoreTokens()) {
String server = st.nextToken().trim() ;
if (server.indexOf(':') < 0 && gatewayPort != null) {
server += ":";
server += gatewayPort;
}
if (isDebug) log("Adding SMTP gateway: " + server) ;
gatewayServer.add(server);
}
authUser = getInitParameter("gatewayUsername");
// backward compatibility with 2.3.x
if (authUser == null) {
authUser = getInitParameter("gatewayusername");
}
authPass = getInitParameter("gatewayPassword");
}
// Instantiate the DNSService for DNS queries lookup
try {
dnsServer = (DNSService) compMgr.lookup(DNSService.ROLE);
} catch (ServiceException e1) {
log("Failed to retrieve DNSService" + e1.getMessage());
}
bindAddress = getInitParameter("bind");
isBindUsed = bindAddress != null;
try {
if (isBindUsed) RemoteDeliverySocketFactory.setBindAdress(bindAddress);
} catch (UnknownHostException e) {
log("Invalid bind setting (" + bindAddress + "): " + e.toString());
}
// deal with <mail.*> attributes, passing them to javamail
Iterator i = getInitParameterNames();
while (i.hasNext()) {
String name = (String) i.next();
if (name.startsWith("mail.")) {
defprops.put(name,getInitParameter(name));
}
}
String dnsRetry = getInitParameter("maxDnsProblemRetries");
if (dnsRetry != null && !dnsRetry.equals("")) {
dnsProblemRetry = Integer.parseInt(dnsRetry);
}
}
/**
* Calculates Total no. of attempts for the specified delayList.
*
* @param delayList
* list of 'Delay' objects
* @return total no. of retry attempts
*/
private int calcTotalAttempts (ArrayList delayList) {
int sum = 0;
Iterator i = delayList.iterator();
while (i.hasNext()) {
Delay delay = (Delay)i.next();
sum += delay.getAttempts();
}
return sum;
}
/**
* This method expands an ArrayList containing Delay objects into an array holding the
* only delaytime in the order.<p>
* So if the list has 2 Delay objects the first having attempts=2 and delaytime 4000
* the second having attempts=1 and delaytime=300000 will be expanded into this array:<p>
* long[0] = 4000<p>
* long[1] = 4000<p>
* long[2] = 300000<p>
* @param list the list to expand
* @return the expanded list
**/
private long[] expandDelays (ArrayList list) {
long[] delays = new long [calcTotalAttempts(list)];
Iterator i = list.iterator();
int idx = 0;
while (i.hasNext()) {
Delay delay = (Delay)i.next();
for (int j=0; j<delay.getAttempts(); j++) {
delays[idx++]= delay.getDelayTime();
}
}
return delays;
}
/**
* This method returns, given a retry-count, the next delay time to use.
* @param retry_count the current retry_count.
* @return the next delay time to use, given the retry count
**/
private long getNextDelay (int retry_count) {
if (retry_count > delayTimes.length) {
return DEFAULT_DELAY_TIME;
}
return delayTimes[retry_count-1];
}
/**
* This class is used to hold a delay time and its corresponding number of
* retries.
**/
private class Delay {
private int attempts = 1;
private long delayTime = DEFAULT_DELAY_TIME;
/**
* This constructor expects Strings of the form
* "[attempt\*]delaytime[unit]".
* <p>
* The optional attempt is the number of tries this delay should be used
* (default = 1). The unit, if present, must be one of
* (msec,sec,minute,hour,day). The default value of unit is 'msec'.
* <p>
* The constructor multiplies the delaytime by the relevant multiplier
* for the unit, so the delayTime instance variable is always in msec.
*
* @param initString
* the string to initialize this Delay object from
**/
public Delay(String initString) throws MessagingException {
// Default unit value to 'msec'.
String unit = "msec";
if (delayTimeMatcher.matches(initString, PATTERN)) {
MatchResult res = delayTimeMatcher.getMatch();
// The capturing groups will now hold:
// at 1: attempts * (if present)
// at 2: delaytime
// at 3: unit (if present)
if (res.group(1) != null && !res.group(1).equals("")) {
// We have an attempt *
String attemptMatch = res.group(1);
// Strip the * and whitespace.
attemptMatch = attemptMatch.substring(0,
attemptMatch.length() - 1).trim();
attempts = Integer.parseInt(attemptMatch);
}
delayTime = Long.parseLong(res.group(2));
if (!res.group(3).equals("")) {
// We have a value for 'unit'.
unit = res.group(3).toLowerCase(Locale.US);
}
} else {
throw new MessagingException(initString + " does not match "
+ PATTERN_STRING);
}
// calculate delayTime.
try {
delayTime = TimeConverter.getMilliSeconds(delayTime, unit);
} catch (NumberFormatException e) {
throw new MessagingException(e.getMessage());
}
}
/**
* This constructor makes a default Delay object with attempts = 1 and
* delayTime = DEFAULT_DELAY_TIME.
**/
public Delay() {
}
/**
* @return the delayTime for this Delay
**/
public long getDelayTime() {
return delayTime;
}
/**
* @return the number attempts this Delay should be used.
**/
public int getAttempts() {
return attempts;
}
/**
* Set the number attempts this Delay should be used.
**/
public void setAttempts(int value) {
attempts = value;
}
/**
* Pretty prints this Delay
**/
public String toString() {
String message = getAttempts() + "*" + getDelayTime() + "msecs";
return message;
}
}
public String getMailetInfo() {
return "RemoteDelivery Mailet";
}
/**
* For this message, we take the list of recipients, organize these into distinct
* servers, and duplicate the message for each of these servers, and then call
* the deliver (messagecontainer) method for each server-specific
* messagecontainer ... that will handle storing it in the outgoing queue if needed.
*
* @param mail org.apache.mailet.Mail
*/
public void service(Mail mail) throws MessagingException{
// Do I want to give the internal key, or the message's Message ID
if (isDebug) {
log("Remotely delivering mail " + mail.getName());
}
Collection recipients = mail.getRecipients();
if (gatewayServer == null) {
// Must first organize the recipients into distinct servers (name made case insensitive)
Hashtable targets = new Hashtable();
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress target = (MailAddress)i.next();
String targetServer = target.getHost().toLowerCase(Locale.US);
Collection temp = (Collection)targets.get(targetServer);
if (temp == null) {
temp = new ArrayList();
targets.put(targetServer, temp);
}
temp.add(target);
}
//We have the recipients organized into distinct servers... put them into the
//delivery store organized like this... this is ultra inefficient I think...
// Store the new message containers, organized by server, in the outgoing mail repository
String name = mail.getName();
for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) {
String host = (String) i.next();
Collection rec = (Collection) targets.get(host);
if (isDebug) {
StringBuffer logMessageBuffer =
new StringBuffer(128)
.append("Sending mail to ")
.append(rec)
.append(" on host ")
.append(host);
log(logMessageBuffer.toString());
}
mail.setRecipients(rec);
StringBuffer nameBuffer =
new StringBuffer(128)
.append(name)
.append("-to-")
.append(host);
mail.setName(nameBuffer.toString());
workRepository.store(mail);
//Set it to try to deliver (in a separate thread) immediately (triggered by storage)
}
} else {
// Store the mail unaltered for processing by the gateway server(s)
if (isDebug) {
StringBuffer logMessageBuffer =
new StringBuffer(128)
.append("Sending mail to ")
.append(mail.getRecipients())
.append(" via ")
.append(gatewayServer);
log(logMessageBuffer.toString());
}
//Set it to try to deliver (in a separate thread) immediately (triggered by storage)
workRepository.store(mail);
}
mail.setState(Mail.GHOST);
}
/**
* Stops all the worker threads that are waiting for messages. This method is
* called by the Mailet container before taking this Mailet out of service.
*/
public synchronized void destroy() {
// Mark flag so threads from this Mailet stop themselves
destroyed = true;
// Wake up all threads from waiting for an accept
for (Iterator i = workersThreads.iterator(); i.hasNext(); ) {
Thread t = (Thread)i.next();
t.interrupt();
}
notifyAll();
}
/**
* Handles checking the outgoing spool for new mail and delivering them if
* there are any
*/
public void run() {
/* TODO: CHANGE ME!!! The problem is that we need to wait for James to
* finish initializing. We expect the HELLO_NAME to be put into
* the MailetContext, but in the current configuration we get
* started before the SMTP Server, which establishes the value.
* Since there is no contractual guarantee that there will be a
* HELLO_NAME value, we can't just wait for it. As a temporary
* measure, I'm inserting this philosophically unsatisfactory
* fix.
*/
long stop = System.currentTimeMillis() + 60000;
while ((getMailetContext().getAttribute(Constants.HELLO_NAME) == null)
&& stop > System.currentTimeMillis()) {
try {
Thread.sleep(1000);
} catch (Exception ignored) {} // wait for James to finish initializing
}
//Checks the pool and delivers a mail message
Properties props = new Properties();
//Not needed for production environment
props.put("mail.debug", "false");
// Reactivated: javamail 1.3.2 should no more have problems with "250 OK"
// messages (WAS "false": Prevents problems encountered with 250 OK Messages)
props.put("mail.smtp.ehlo", "true");
// By setting this property to true the transport is allowed to
// send 8 bit data to the server (if it supports the 8bitmime extension).
// 2006/03/01 reverted to false because of a javamail bug converting to 8bit
// messages created by an inputstream.
props.setProperty("mail.smtp.allow8bitmime", "true");
//Sets timeout on going connections
props.put("mail.smtp.timeout", smtpTimeout + "");
props.put("mail.smtp.connectiontimeout", connectionTimeout + "");
props.put("mail.smtp.sendpartial",String.valueOf(sendPartial));
//Set the hostname we'll use as this server
if (getMailetContext().getAttribute(Constants.HELLO_NAME) != null) {
props.put("mail.smtp.localhost", getMailetContext().getAttribute(Constants.HELLO_NAME));
}
else {
String defaultDomain = (String) getMailetContext().getAttribute(Constants.DEFAULT_DOMAIN);
if (defaultDomain != null) {
props.put("mail.smtp.localhost", defaultDomain);
}
}
if (isBindUsed) {
// undocumented JavaMail 1.2 feature, smtp transport will use
// our socket factory, which will also set the local address
props.put("mail.smtp.socketFactory.class", RemoteDeliverySocketFactory.class.getClass());
// Don't fallback to the standard socket factory on error, do throw an exception
props.put("mail.smtp.socketFactory.fallback", "false");
}
if (authUser != null) {
props.put("mail.smtp.auth","true");
}
props.putAll(defprops);
Session session = obtainSession(props);
try {
while (!Thread.interrupted() && !destroyed) {
try {
// Get the 'mail' object that is ready for deliverying. If no
// message is
// ready, the 'accept' will block until message is ready.
// The amount
// of time to block is determined by the 'getWaitTime'
// method of the
// MultipleDelayFilter.
Mail mail = workRepository.accept(delayFilter);
String key = mail.getName();
try {
if (isDebug) {
String message = Thread.currentThread().getName()
+ " will process mail " + key;
log(message);
}
// Deliver message
if (deliver(mail, session)) {
// Message was successfully delivered/fully failed...
// delete it
ContainerUtil.dispose(mail);
workRepository.remove(key);
} else {
// Something happened that will delay delivery.
// Store it back in the retry repository.
workRepository.store(mail);
ContainerUtil.dispose(mail);
// This is an update, so we have to unlock and
// notify or this mail is kept locked by this thread.
workRepository.unlock(key);
// Note: We do not notify because we updated an
// already existing mail and we are now free to handle
// more mails.
// Furthermore this mail should not be processed now
// because we have a retry time scheduling.
}
// Clear the object handle to make sure it recycles
// this object.
mail = null;
} catch (Exception e) {
// Prevent unexpected exceptions from causing looping by
// removing message from outgoing.
// DO NOT CHANGE THIS to catch Error! For example, if
// there were an OutOfMemory condition caused because
// something else in the server was abusing memory, we would
// not want to start purging the retrying spool!
ContainerUtil.dispose(mail);
workRepository.remove(key);
throw e;
}
} catch (Throwable e) {
if (!destroyed) {
log("Exception caught in RemoteDelivery.run()", e);
}
}
}
} finally {
// Restore the thread state to non-interrupted.
Thread.interrupted();
}
}
/**
* We can assume that the recipients of this message are all going to the same
* mail server. We will now rely on the DNS server to do DNS MX record lookup
* and try to deliver to the multiple mail servers. If it fails, it should
* throw an exception.
*
* Creation date: (2/24/00 11:25:00 PM)
* @param mail org.apache.james.core.MailImpl
* @param session javax.mail.Session
* @return boolean Whether the delivery was successful and the message can be deleted
*/
private boolean deliver(Mail mail, Session session) {
try {
if (isDebug) {
log("Attempting to deliver " + mail.getName());
}
MimeMessage message = mail.getMessage();
//Create an array of the recipients as InternetAddress objects
Collection recipients = mail.getRecipients();
InternetAddress addr[] = new InternetAddress[recipients.size()];
int j = 0;
for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
MailAddress rcpt = (MailAddress)i.next();
addr[j] = rcpt.toInternetAddress();
}
if (addr.length <= 0) {
log("No recipients specified... not sure how this could have happened.");
return true;
}
//Figure out which servers to try to send to. This collection
// will hold all the possible target servers
Iterator targetServers = null;
if (gatewayServer == null) {
MailAddress rcpt = (MailAddress) recipients.iterator().next();
String host = rcpt.getHost();
//Lookup the possible targets
try {
targetServers = dnsServer.getSMTPHostAddresses(host);
} catch (TemporaryResolutionException e) {
log("Temporary problem looking up mail server for host: " + host);
StringBuffer exceptionBuffer =
new StringBuffer(128)
.append("Temporary problem looking up mail server for host: ")
.append(host)
.append(". I cannot determine where to send this message.");
// temporary problems
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), false);
}
if (!targetServers.hasNext()) {
log("No mail server found for: " + host);
StringBuffer exceptionBuffer =
new StringBuffer(128)
.append("There are no DNS entries for the hostname ")
.append(host)
.append(". I cannot determine where to send this message.");
int retry = 0;
try {
retry = Integer.parseInt(mail.getErrorMessage());
} catch (NumberFormatException e) {
// Unable to parse retryCount
}
if (retry == 0 || retry > dnsProblemRetry) {
// The domain has no dns entry.. Return a permanent error
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), true);
} else {
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), false);
}
}
} else {
targetServers = getGatewaySMTPHostAddresses(gatewayServer);
}
MessagingException lastError = null;
while ( targetServers.hasNext()) {
try {
HostAddress outgoingMailServer = (HostAddress) targetServers.next();
StringBuffer logMessageBuffer =
new StringBuffer(256)
.append("Attempting delivery of ")
.append(mail.getName())
.append(" to host ")
.append(outgoingMailServer.getHostName())
.append(" at ")
.append(outgoingMailServer.getHost())
.append(" for addresses ")
.append(Arrays.asList(addr));
log(logMessageBuffer.toString());
Properties props = session.getProperties();
if (mail.getSender() == null) {
props.put("mail.smtp.from", "<>");
} else {
String sender = mail.getSender().toString();
props.put("mail.smtp.from", sender);
}
//Many of these properties are only in later JavaMail versions
//"mail.smtp.ehlo" //default true
//"mail.smtp.auth" //default false
//"mail.smtp.dsn.ret" //default to nothing... appended as RET= after MAIL FROM line.
//"mail.smtp.dsn.notify" //default to nothing...appended as NOTIFY= after RCPT TO line.
Transport transport = null;
try {
transport = session.getTransport(outgoingMailServer);
try {
if (authUser != null) {
transport.connect(outgoingMailServer.getHostName(), authUser, authPass);
} else {
transport.connect();
}
} catch (MessagingException me) {
// Any error on connect should cause the mailet to attempt
// to connect to the next SMTP server associated with this
// MX record. Just log the exception. We'll worry about
// failing the message at the end of the loop.
log(me.getMessage());
continue;
}
// if the transport is a SMTPTransport (from sun) some
// performance enhancement can be done.
if (transport.getClass().getName().endsWith(".SMTPTransport")) {
boolean supports8bitmime = false;
try {
Method supportsExtension = transport.getClass().getMethod("supportsExtension", new Class[] {String.class});
supports8bitmime = ((Boolean) supportsExtension.invoke(transport, new Object[] {"8BITMIME"})).booleanValue();
} catch (NoSuchMethodException nsme) {
// An SMTPAddressFailedException with no getAddress method.
} catch (IllegalAccessException iae) {
} catch (IllegalArgumentException iae) {
} catch (InvocationTargetException ite) {
// Other issues with getAddress invokation.
}
// if the message is alredy 8bit or binary and the
// server doesn't support the 8bit extension it has
// to be converted to 7bit. Javamail api doesn't perform
// that conversion, but it is required to be a
// rfc-compliant smtp server.
// Temporarily disabled. See JAMES-638
if (!supports8bitmime) {
try {
convertTo7Bit(message);
} catch (IOException e) {
// An error has occured during the 7bit conversion.
// The error is logged and the message is sent anyway.
log("Error during the conversion to 7 bit.", e);
}
}
} else {
// If the transport is not the one
// developed by Sun we are not sure of how it
// handles the 8 bit mime stuff,
// so I convert the message to 7bit.
try {
convertTo7Bit(message);
} catch (IOException e) {
log("Error during the conversion to 7 bit.", e);
}
}
transport.sendMessage(message, addr);
} finally {
if (transport != null) {
transport.close();
transport = null;
}
}
logMessageBuffer =
new StringBuffer(256)
.append("Mail (")
.append(mail.getName())
.append(") sent successfully to ")
.append(outgoingMailServer.getHostName())
.append(" at ")
.append(outgoingMailServer.getHost())
.append(" for ")
.append(mail.getRecipients());
log(logMessageBuffer.toString());
return true;
} catch (SendFailedException sfe) {
logSendFailedException(sfe);
if (sfe.getValidSentAddresses() != null) {
Address[] validSent = sfe.getValidSentAddresses();
if (validSent.length > 0) {
StringBuffer logMessageBuffer =
new StringBuffer(256)
.append("Mail (")
.append(mail.getName())
.append(") sent successfully for ")
.append(Arrays.asList(validSent));
log(logMessageBuffer.toString());
}
}
/* SMTPSendFailedException introduced in JavaMail 1.3.2, and provides detailed protocol reply code for the operation */
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
try {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
// if 5xx, terminate this delivery attempt by re-throwing the exception.
if (returnCode >= 500 && returnCode <= 599) throw sfe;
} catch (ClassCastException cce) {
} catch (IllegalArgumentException iae) {
}
}
if (sfe.getValidUnsentAddresses() != null
&& sfe.getValidUnsentAddresses().length > 0) {
if (isDebug) log("Send failed, " + sfe.getValidUnsentAddresses().length + " valid addresses remain, continuing with any other servers");
lastError = sfe;
continue;
} else {
// There are no valid addresses left to send, so rethrow
throw sfe;
}
} catch (MessagingException me) {
//MessagingException are horribly difficult to figure out what actually happened.
StringBuffer exceptionBuffer =
new StringBuffer(256)
.append("Exception delivering message (")
.append(mail.getName())
.append(") - ")
.append(me.getMessage());
log(exceptionBuffer.toString());
if ((me.getNextException() != null) &&
(me.getNextException() instanceof java.io.IOException)) {
//This is more than likely a temporary failure
// If it's an IO exception with no nested exception, it's probably
// some socket or weird I/O related problem.
lastError = me;
continue;
}
// This was not a connection or I/O error particular to one
// SMTP server of an MX set. Instead, it is almost certainly
// a protocol level error. In this case we assume that this
// is an error we'd encounter with any of the SMTP servers
// associated with this MX record, and we pass the exception
// to the code in the outer block that determines its severity.
throw me;
}
} // end while
//If we encountered an exception while looping through,
//throw the last MessagingException we caught. We only
//do this if we were unable to send the message to any
//server. If sending eventually succeeded, we exit
//deliver() though the return at the end of the try
//block.
if (lastError != null) {
throw lastError;
}
} catch (SendFailedException sfe) {
logSendFailedException(sfe);
Collection recipients = mail.getRecipients();
boolean deleteMessage = false;
/*
* If you send a message that has multiple invalid
* addresses, you'll get a top-level SendFailedException
* that that has the valid, valid-unsent, and invalid
* address lists, with all of the server response messages
* will be contained within the nested exceptions. [Note:
* the content of the nested exceptions is implementation
* dependent.]
*
* sfe.getInvalidAddresses() should be considered permanent.
* sfe.getValidUnsentAddresses() should be considered temporary.
*
* JavaMail v1.3 properly populates those collections based
* upon the 4xx and 5xx response codes to RCPT TO. Some
* servers, such as Yahoo! don't respond to the RCPT TO,
* and provide a 5xx reply after DATA. In that case, we
* will pick up the failure from SMTPSendFailedException.
*
*/
/* SMTPSendFailedException introduced in JavaMail 1.3.2, and provides detailed protocol reply code for the operation */
try {
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
// If we got an SMTPSendFailedException, use its RetCode to determine default permanent/temporary failure
deleteMessage = (returnCode >= 500 && returnCode <= 599);
} else {
// Sometimes we'll get a normal SendFailedException with nested SMTPAddressFailedException, so use the latter RetCode
MessagingException me = sfe;
Exception ne;
while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
me = (MessagingException)ne;
if (me.getClass().getName().endsWith(".SMTPAddressFailedException")) {
int returnCode = ((Integer) invokeGetter(me, "getReturnCode")).intValue();
deleteMessage = (returnCode >= 500 && returnCode <= 599);
}
}
}
} catch (IllegalStateException ise) {
// unexpected exception (not a compatible javamail implementation)
} catch (ClassCastException cce) {
// unexpected exception (not a compatible javamail implementation)
}
// log the original set of intended recipients
if (isDebug) log("Recipients: " + recipients);
if (sfe.getInvalidAddresses() != null) {
Address[] address = sfe.getInvalidAddresses();
if (address.length > 0) {
recipients.clear();
for (int i = 0; i < address.length; i++) {
try {
recipients.add(new MailAddress(address[i].toString()));
} catch (ParseException pe) {
// this should never happen ... we should have
// caught malformed addresses long before we
// got to this code.
log("Can't parse invalid address: " + pe.getMessage());
}
}
if (isDebug) log("Invalid recipients: " + recipients);
deleteMessage = failMessage(mail, sfe, true);
}
}
if (sfe.getValidUnsentAddresses() != null) {
Address[] address = sfe.getValidUnsentAddresses();
if (address.length > 0) {
recipients.clear();
for (int i = 0; i < address.length; i++) {
try {
recipients.add(new MailAddress(address[i].toString()));
} catch (ParseException pe) {
// this should never happen ... we should have
// caught malformed addresses long before we
// got to this code.
log("Can't parse unsent address: " + pe.getMessage());
}
}
if (isDebug) log("Unsent recipients: " + recipients);
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
deleteMessage = failMessage(mail, sfe, returnCode >= 500 && returnCode <= 599);
} else {
deleteMessage = failMessage(mail, sfe, false);
}
}
}
return deleteMessage;
} catch (MessagingException ex) {
// We should do a better job checking this... if the failure is a general
// connect exception, this is less descriptive than more specific SMTP command
// failure... have to lookup and see what are the various Exception
// possibilities
// Unable to deliver message after numerous tries... fail accordingly
// We check whether this is a 5xx error message, which
// indicates a permanent failure (like account doesn't exist
// or mailbox is full or domain is setup wrong).
// We fail permanently if this was a 5xx error
return failMessage(mail, ex, ('5' == ex.getMessage().charAt(0)));
} catch (Exception ex) {
// Generic exception = permanent failure
return failMessage(mail, ex, true);
}
/* If we get here, we've exhausted the loop of servers without
* sending the message or throwing an exception. One case
* where this might happen is if we get a MessagingException on
* each transport.connect(), e.g., if there is only one server
* and we get a connect exception.
*/
return failMessage(mail, new MessagingException("No mail server(s) available at this time."), false);
}
/**
* Try to return a usefull logString created of the Exception which was given.
* Return null if nothing usefull could be done
*
* @param e The MessagingException to use
* @return logString
*/
private String exceptionToLogString(Exception e) {
if (e.getClass().getName().endsWith(".SMTPSendFailedException")) {
return "RemoteHost said: " + e.getMessage();
} else if (e instanceof SendFailedException) {
SendFailedException exception = (SendFailedException) e;
// No error
if ( exception.getInvalidAddresses().length == 0 &&
exception.getValidUnsentAddresses().length == 0) return null;
Exception ex;
StringBuffer sb = new StringBuffer();
boolean smtpExFound = false;
sb.append("RemoteHost said:");
if (e instanceof MessagingException) while((ex = ((MessagingException) e).getNextException()) != null && ex instanceof MessagingException) {
e = ex;
if (ex.getClass().getName().endsWith(".SMTPAddressFailedException")) {
try {
InternetAddress ia = (InternetAddress) invokeGetter(ex, "getAddress");
sb.append(" ( " + ia + " - [" + ex.getMessage().replaceAll("\\n", "") + "] )");
smtpExFound = true;
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
} catch (ClassCastException cce) {
// The getAddress method returned something different than InternetAddress
}
}
}
if (!smtpExFound) {
boolean invalidAddr = false;
sb.append(" ( ");
if (exception.getInvalidAddresses().length > 0) {
sb.append(exception.getInvalidAddresses());
invalidAddr = true;
}
if (exception.getValidUnsentAddresses().length > 0) {
if (invalidAddr == true) sb.append(" " );
sb.append(exception.getValidUnsentAddresses());
}
sb.append(" - [");
sb.append(exception.getMessage().replaceAll("\\n", ""));
sb.append("] )");
}
return sb.toString();
}
return null;
}
/**
* Utility method used to invoke getters for javamail implementation specific classes.
*
* @param target the object whom method will be invoked
* @param getter the no argument method name
* @return the result object
* @throws IllegalStateException on invocation error
*/
private Object invokeGetter(Object target, String getter) {
try {
Method getAddress = target.getClass().getMethod(getter, null);
return getAddress.invoke(target, null);
} catch (NoSuchMethodException nsme) {
// An SMTPAddressFailedException with no getAddress method.
} catch (IllegalAccessException iae) {
} catch (IllegalArgumentException iae) {
} catch (InvocationTargetException ite) {
// Other issues with getAddress invokation.
}
return new IllegalStateException("Exception invoking "+getter+" on a "+target.getClass()+" object");
}
/*
* private method to log the extended SendFailedException introduced in JavaMail 1.3.2.
*/
private void logSendFailedException(SendFailedException sfe) {
if (isDebug) {
MessagingException me = sfe;
if (me.getClass().getName().endsWith(".SMTPSendFailedException")) {
try {
String command = (String) invokeGetter(sfe, "getCommand");
Integer returnCode = (Integer) invokeGetter(sfe, "getReturnCode");
log("SMTP SEND FAILED:");
log(sfe.toString());
log(" Command: " + command);
log(" RetCode: " + returnCode);
log(" Response: " + sfe.getMessage());
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
log("Send failed: " + me.toString());
} catch (ClassCastException cce) {
// The getAddress method returned something different than InternetAddress
log("Send failed: " + me.toString());
}
} else {
log("Send failed: " + me.toString());
}
Exception ne;
while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
me = (MessagingException)ne;
if (me.getClass().getName().endsWith(".SMTPAddressFailedException") || me.getClass().getName().endsWith(".SMTPAddressSucceededException")) {
try {
String action = me.getClass().getName().endsWith(".SMTPAddressFailedException") ? "FAILED" : "SUCCEEDED";
InternetAddress address = (InternetAddress) invokeGetter(me, "getAddress");
String command = (String) invokeGetter(me, "getCommand");
Integer returnCode = (Integer) invokeGetter(me, "getReturnCode");
log("ADDRESS "+action+":");
log(me.toString());
log(" Address: " + address);
log(" Command: " + command);
log(" RetCode: " + returnCode);
log(" Response: " + me.getMessage());
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
} catch (ClassCastException cce) {
// A method returned something different than expected
}
}
}
}
}
/**
* Converts a message to 7 bit.
*
* @param part
*/
private void convertTo7Bit(MimePart part) throws MessagingException, IOException {
if (part.isMimeType("multipart/*")) {
MimeMultipart parts = (MimeMultipart) part.getContent();
int count = parts.getCount();
for (int i = 0; i < count; i++) {
convertTo7Bit((MimePart)parts.getBodyPart(i));
}
} else if ("8bit".equals(part.getEncoding())) {
// The content may already be in encoded the form (likely with mail created from a
// stream). In that case, just changing the encoding to quoted-printable will mangle
// the result when this is transmitted. We must first convert the content into its
// native format, set it back, and only THEN set the transfer encoding to force the
// content to be encoded appropriately.
// if the part doesn't contain text it will be base64 encoded.
String contentTransferEncoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";
part.setContent(part.getContent(), part.getContentType());
part.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
part.addHeader("X-MIME-Autoconverted", "from 8bit to "+contentTransferEncoding+" by "+getMailetContext().getServerInfo());
}
}
/**
* Insert the method's description here.
* Creation date: (2/25/00 1:14:18 AM)
* @param mail org.apache.james.core.MailImpl
* @param ex javax.mail.MessagingException
* @param permanent
* @return boolean Whether the message failed fully and can be deleted
*/
private boolean failMessage(Mail mail, Exception ex, boolean permanent) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
if (permanent) {
out.print("Permanent");
} else {
out.print("Temporary");
}
String exceptionLog = exceptionToLogString(ex);
StringBuffer logBuffer =
new StringBuffer(64)
.append(" exception delivering mail (")
.append(mail.getName());
if (exceptionLog != null) {
logBuffer.append(". ");
logBuffer.append(exceptionLog);
}
logBuffer.append(": ");
out.print(logBuffer.toString());
if (isDebug) ex.printStackTrace(out);
log(sout.toString());
if (!permanent) {
if (!mail.getState().equals(Mail.ERROR)) {
mail.setState(Mail.ERROR);
mail.setErrorMessage("0");
mail.setLastUpdated(new Date());
}
int retries = 0;
try {
retries = Integer.parseInt(mail.getErrorMessage());
} catch (NumberFormatException e) {
// Something strange was happen with the errorMessage..
}
if (retries < maxRetries) {
logBuffer =
new StringBuffer(128)
.append("Storing message ")
.append(mail.getName())
.append(" into outgoing after ")
.append(retries)
.append(" retries");
log(logBuffer.toString());
++retries;
mail.setErrorMessage(retries + "");
mail.setLastUpdated(new Date());
return false;
} else {
logBuffer =
new StringBuffer(128)
.append("Bouncing message ")
.append(mail.getName())
.append(" after ")
.append(retries)
.append(" retries");
log(logBuffer.toString());
}
}
if (mail.getSender() == null) {
log("Null Sender: no bounce will be generated for " + mail.getName());
return true;
}
if (bounceProcessor != null) {
// do the new DSN bounce
// setting attributes for DSN mailet
mail.setAttribute("delivery-error", ex);
mail.setState(bounceProcessor);
// re-insert the mail into the spool for getting it passed to the dsn-processor
MailetContext mc = getMailetContext();
try {
mc.sendMail(mail);
} catch (MessagingException e) {
// we shouldn't get an exception, because the mail was already processed
log("Exception re-inserting failed mail: ", e);
}
} else {
// do an old style bounce
bounce(mail, ex);
}
return true;
}
private void bounce(Mail mail, Exception ex) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
String machine = "[unknown]";
try {
machine = getMailetContext().getAttribute(Constants.HOSTNAME).toString();
} catch(Exception e){
machine = "[address unknown]";
}
StringBuffer bounceBuffer =
new StringBuffer(128)
.append("Hi. This is the James mail server at ")
.append(machine)
.append(".");
out.println(bounceBuffer.toString());
out.println("I'm afraid I wasn't able to deliver your message to the following addresses.");
out.println("This is a permanent error; I've given up. Sorry it didn't work out. Below");
out.println("I include the list of recipients and the reason why I was unable to deliver");
out.println("your message.");
out.println();
for (Iterator i = mail.getRecipients().iterator(); i.hasNext(); ) {
out.println(i.next());
}
if (ex instanceof MessagingException) {
if (((MessagingException) ex).getNextException() == null) {
out.println(ex.getMessage().trim());
} else {
Exception ex1 = ((MessagingException) ex).getNextException();
if (ex1 instanceof SendFailedException) {
out.println("Remote mail server told me: " + ex1.getMessage().trim());
} else if (ex1 instanceof UnknownHostException) {
out.println("Unknown host: " + ex1.getMessage().trim());
out.println("This could be a DNS server error, a typo, or a problem with the recipient's mail server.");
} else if (ex1 instanceof ConnectException) {
//Already formatted as "Connection timed out: connect"
out.println(ex1.getMessage().trim());
} else if (ex1 instanceof SocketException) {
out.println("Socket exception: " + ex1.getMessage().trim());
} else {
out.println(ex1.getMessage().trim());
}
}
}
out.println();
log("Sending failure message " + mail.getName());
try {
getMailetContext().bounce(mail, sout.toString());
} catch (MessagingException me) {
log("Encountered unexpected messaging exception while bouncing message: " + me.getMessage());
} catch (Exception e) {
log("Encountered unexpected exception while bouncing message: " + e.getMessage());
}
}
/**
* Returns the javamail Session object.
* @param props
* @param authenticator
* @return
*/
protected Session obtainSession(Properties props) {
return Session.getInstance(props);
}
/**
* Returns an Iterator over org.apache.mailet.HostAddress, a
* specialized subclass of javax.mail.URLName, which provides
* location information for servers that are specified as mail
* handlers for the given hostname. If no host is found, the
* Iterator returned will be empty and the first call to hasNext()
* will return false. The Iterator is a nested iterator: the outer
* iteration is over each gateway, and the inner iteration is over
* potentially multiple A records for each gateway.
*
* @see org.apache.james.DNSServer#getSMTPHostAddresses(String)
* @since v2.2.0a16-unstable
* @param gatewayServers - Collection of host[:port] Strings
* @return an Iterator over HostAddress instances, sorted by priority
*/
private Iterator getGatewaySMTPHostAddresses(final Collection gatewayServers) {
return new Iterator() {
private Iterator gateways = gatewayServers.iterator();
private Iterator addresses = null;
public boolean hasNext() {
/* Make sure that when next() is called, that we can
* provide a HostAddress. This means that we need to
* have an inner iterator, and verify that it has
* addresses. We could, for example, run into a
* situation where the next gateway didn't have any
* valid addresses.
*/
if (!hasNextAddress() && gateways.hasNext()) {
do {
String server = (String) gateways.next();
String port = "25";
int idx = server.indexOf(':');
if ( idx > 0) {
port = server.substring(idx+1);
server = server.substring(0,idx);
}
final String nextGateway = server;
final String nextGatewayPort = port;
try {
final InetAddress[] ips = dnsServer.getAllByName(nextGateway);
addresses = new Iterator() {
private InetAddress[] ipAddresses = ips;
int i = 0;
public boolean hasNext() {
return i < ipAddresses.length;
}
public Object next() {
return new org.apache.mailet.HostAddress(nextGateway, "smtp://" + (ipAddresses[i++]).getHostAddress() + ":" + nextGatewayPort);
}
public void remove() {
throw new UnsupportedOperationException ("remove not supported by this iterator");
}
};
}
catch (java.net.UnknownHostException uhe) {
log("Unknown gateway host: " + uhe.getMessage().trim());
log("This could be a DNS server error or configuration error.");
}
} while (!hasNextAddress() && gateways.hasNext());
}
return hasNextAddress();
}
private boolean hasNextAddress() {
return addresses != null && addresses.hasNext();
}
public Object next() {
return (addresses != null) ? addresses.next() : null;
}
public void remove() {
throw new UnsupportedOperationException ("remove not supported by this iterator");
}
};
}
/**
* Setter for the dnsserver service
* @param dnsServer dns service
*/
protected synchronized void setDNSServer(DNSService dnsServer) {
this.dnsServer = dnsServer;
}
}
|
mailets-function/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
|
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.transport.mailets;
import org.apache.avalon.cornerstone.services.store.Store;
import org.apache.avalon.framework.configuration.DefaultConfiguration;
import org.apache.avalon.framework.container.ContainerUtil;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.james.Constants;
import org.apache.james.api.dnsservice.DNSService;
import org.apache.james.api.dnsservice.TemporaryResolutionException;
import org.apache.james.services.SpoolRepository;
import org.apache.james.util.TimeConverter;
import org.apache.mailet.base.GenericMailet;
import org.apache.mailet.HostAddress;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.MailetContext;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimePart;
import javax.mail.internet.ParseException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Receives a MessageContainer from JamesSpoolManager and takes care of delivery
* the message to remote hosts. If for some reason mail can't be delivered
* store it in the "outgoing" Repository and set an Alarm. After the next "delayTime" the
* Alarm will wake the servlet that will try to send it again. After "maxRetries"
* the mail will be considered undeliverable and will be returned to sender.
*
* TO DO (in priority):
* 1. Support a gateway (a single server where all mail will be delivered) (DONE)
* 2. Provide better failure messages (DONE)
* 3. More efficiently handle numerous recipients
* 4. Migrate to use Phoenix for the delivery threads
*
* You really want to read the JavaMail documentation if you are
* working in here, and you will want to view the list of JavaMail
* attributes, which are documented here:
*
* http://java.sun.com/products/javamail/1.3/docs/javadocs/com/sun/mail/smtp/package-summary.html
*
* as well as other places.
*
* @version CVS $Revision$ $Date$
*/
public class RemoteDelivery extends GenericMailet implements Runnable {
// Default Delay Time (Default is 6*60*60*1000 Milliseconds (6 hours)).
private static final long DEFAULT_DELAY_TIME = 21600000;
// Pattern to match [attempts*]delay[units].
private static final String PATTERN_STRING = "\\s*([0-9]*\\s*[\\*])?\\s*([0-9]+)\\s*([a-z,A-Z]*)\\s*";
// Compiled pattern of the above String.
private static Pattern PATTERN = null;
// The DNSService
private DNSService dnsServer;
/*
* Static initializer.<p>
* Compiles pattern for processing delaytime entries.<p>
* Initializes MULTIPLIERS with the supported unit quantifiers
*/
static {
try {
Perl5Compiler compiler = new Perl5Compiler();
PATTERN = compiler.compile(PATTERN_STRING, Perl5Compiler.READ_ONLY_MASK);
} catch(MalformedPatternException mpe) {
//this should not happen as the pattern string is hardcoded.
mpe.printStackTrace (System.err);
}
}
/**
* This filter is used in the accept call to the spool.
* It will select the next mail ready for processing according to the mails
* retrycount and lastUpdated time
**/
private class MultipleDelayFilter implements SpoolRepository.AcceptFilter {
/**
* holds the time to wait for the youngest mail to get ready for processing
**/
long youngest = 0;
/**
* Uses the getNextDelay to determine if a mail is ready for processing based on the delivered parameters
* errorMessage (which holds the retrycount), lastUpdated and state
* @param key the name/key of the message
* @param state the mails state
* @param lastUpdated the mail was last written to the spool at this time.
* @param errorMessage actually holds the retrycount as a string (see failMessage below)
**/
public boolean accept (String key, String state, long lastUpdated, String errorMessage) {
if (state.equals(Mail.ERROR)) {
//Test the time...
int retries = 0;
try {
retries = Integer.parseInt(errorMessage);
} catch (NumberFormatException e) {
// Something strange was happen with the errorMessage.. Ignore the Exception and try
// to deliver it now!
}
// If the retries count is 0 we should try to send the mail now!
if (retries == 0) return true;
long delay = getNextDelay (retries);
long timeToProcess = delay + lastUpdated;
if (System.currentTimeMillis() > timeToProcess) {
//We're ready to process this again
return true;
} else {
//We're not ready to process this.
if (youngest == 0 || youngest > timeToProcess) {
//Mark this as the next most likely possible mail to process
youngest = timeToProcess;
}
return false;
}
} else {
//This mail is good to go... return the key
return true;
}
}
/**
* @return the optimal time the SpoolRepository.accept(AcceptFilter) method should wait before
* trying to find a mail ready for processing again.
**/
public long getWaitTime () {
if (youngest == 0) {
return 0;
} else {
long duration = youngest - System.currentTimeMillis();
youngest = 0; //get ready for next run
return duration <= 0 ? 1 : duration;
}
}
}
// Flag to define verbose logging messages.
private boolean isDebug = false;
// Repository used to store messages that will be delivered.
private SpoolRepository workRepository;
// List of Delay Times. Controls frequency of retry attempts.
private long[] delayTimes;
// Maximum no. of retries (Defaults to 5).
private int maxRetries = 5;
//default number of ms to timeout on smtp delivery
private long smtpTimeout = 180000;
// If false then ANY address errors will cause the transmission to fail
private boolean sendPartial = false;
// The amount of time JavaMail will wait before giving up on a socket connect()
private int connectionTimeout = 60000;
// No. of threads used to process messages that should be retried.
private int workersThreadCount = 1;
// the server(s) to send all email to
private Collection gatewayServer = null;
// auth for gateway server
private String authUser = null;
// password for gateway server
private String authPass = null;
// JavaMail delivery socket binds to this local address. If null the JavaMail default will be used.
private String bindAddress = null;
// true, if the bind configuration parameter is supplied, RemoteDeliverySocketFactory
// will be used in this case
private boolean isBindUsed = false;
// Collection that stores all worker threads.
private Collection workersThreads = new Vector();
// Flag used by 'run' method to end itself.
private volatile boolean destroyed = false;
// the processor for creating Bounces
private String bounceProcessor = null;
// Matcher used in 'init' method to parse delayTimes specified in config
// file.
private Perl5Matcher delayTimeMatcher;
// Filter used by 'accept' to check if message is ready for retrying.
private MultipleDelayFilter delayFilter = new MultipleDelayFilter();
// default properties for the javamail Session
private Properties defprops = new Properties();
// The retry count dnsProblemErrors
private int dnsProblemRetry = 0;
/**
* Initializes all arguments based on configuration values specified in the
* James configuration file.
*
* @throws MessagingException
* on failure to initialize attributes.
*/
public void init() throws MessagingException {
// Set isDebug flag.
isDebug = (getInitParameter("debug") == null) ? false : new Boolean(getInitParameter("debug")).booleanValue();
// Create list of Delay Times.
ArrayList delayTimesList = new ArrayList();
try {
if (getInitParameter("delayTime") != null) {
delayTimeMatcher = new Perl5Matcher();
String delayTimesParm = getInitParameter("delayTime");
// Split on commas
StringTokenizer st = new StringTokenizer (delayTimesParm,",");
while (st.hasMoreTokens()) {
String delayTime = st.nextToken();
delayTimesList.add (new Delay(delayTime));
}
} else {
// Use default delayTime.
delayTimesList.add (new Delay());
}
} catch (Exception e) {
log("Invalid delayTime setting: " + getInitParameter("delayTime"));
}
try {
// Get No. of Max Retries.
if (getInitParameter("maxRetries") != null) {
maxRetries = Integer.parseInt(getInitParameter("maxRetries"));
}
// Check consistency of 'maxRetries' with delayTimesList attempts.
int totalAttempts = calcTotalAttempts(delayTimesList);
// If inconsistency found, fix it.
if (totalAttempts > maxRetries) {
log("Total number of delayTime attempts exceeds maxRetries specified. "
+ " Increasing maxRetries from "
+ maxRetries
+ " to "
+ totalAttempts);
maxRetries = totalAttempts;
} else {
int extra = maxRetries - totalAttempts;
if (extra != 0) {
log("maxRetries is larger than total number of attempts specified. "
+ "Increasing last delayTime with "
+ extra
+ " attempts ");
// Add extra attempts to the last delayTime.
if (delayTimesList.size() != 0) {
// Get the last delayTime.
Delay delay = (Delay) delayTimesList.get(delayTimesList
.size() - 1);
// Increase no. of attempts.
delay.setAttempts(delay.getAttempts() + extra);
log("Delay of " + delay.getDelayTime()
+ " msecs is now attempted: " + delay.getAttempts()
+ " times");
} else {
throw new MessagingException(
"No delaytimes, cannot continue");
}
}
}
delayTimes = expandDelays(delayTimesList);
} catch (Exception e) {
log("Invalid maxRetries setting: " + getInitParameter("maxRetries"));
}
ServiceManager compMgr = (ServiceManager) getMailetContext()
.getAttribute(Constants.AVALON_COMPONENT_MANAGER);
// Get the path for the 'Outgoing' repository. This is the place on the
// file system where Mail objects will be saved during the 'delivery'
// processing. This can be changed to a repository on a database (e.g.
// db://maildb/spool/retry).
String workRepositoryPath = getInitParameter("outgoing");
if (workRepositoryPath == null) {
workRepositoryPath = "file:///../var/mail/outgoing";
}
try {
// Instantiate a MailRepository for mails to be processed.
Store mailstore = (Store) compMgr.lookup(Store.ROLE);
DefaultConfiguration spoolConf = new DefaultConfiguration(
"repository", "generated:RemoteDelivery");
spoolConf.setAttribute("destinationURL", workRepositoryPath);
spoolConf.setAttribute("type", "SPOOL");
workRepository = (SpoolRepository) mailstore.select(spoolConf);
} catch (ServiceException cnfe) {
log("Failed to retrieve Store component:" + cnfe.getMessage());
throw new MessagingException("Failed to retrieve Store component",
cnfe);
}
// Start Workers Threads.
workersThreadCount = Integer.parseInt(getInitParameter("deliveryThreads"));
for (int i = 0; i < workersThreadCount; i++) {
String threadName = "Remote delivery thread (" + i + ")";
Thread t = new Thread(this, threadName);
t.start();
workersThreads.add(t);
}
try {
if (getInitParameter("timeout") != null) {
smtpTimeout = Integer.parseInt(getInitParameter("timeout"));
}
} catch (Exception e) {
log("Invalid timeout setting: " + getInitParameter("timeout"));
}
try {
if (getInitParameter("connectiontimeout") != null) {
connectionTimeout = Integer.parseInt(getInitParameter("connectiontimeout"));
}
} catch (Exception e) {
log("Invalid timeout setting: " + getInitParameter("timeout"));
}
sendPartial = (getInitParameter("sendpartial") == null) ? false : new Boolean(getInitParameter("sendpartial")).booleanValue();
bounceProcessor = getInitParameter("bounceProcessor");
String gateway = getInitParameter("gateway");
String gatewayPort = getInitParameter("gatewayPort");
if (gateway != null) {
gatewayServer = new ArrayList();
StringTokenizer st = new StringTokenizer(gateway, ",") ;
while (st.hasMoreTokens()) {
String server = st.nextToken().trim() ;
if (server.indexOf(':') < 0 && gatewayPort != null) {
server += ":";
server += gatewayPort;
}
if (isDebug) log("Adding SMTP gateway: " + server) ;
gatewayServer.add(server);
}
authUser = getInitParameter("gatewayUsername");
// backward compatibility with 2.3.x
if (authUser == null) {
authUser = getInitParameter("gatewayusername");
}
authPass = getInitParameter("gatewayPassword");
}
// Instantiate the DNSService for DNS queries lookup
try {
dnsServer = (DNSService) compMgr.lookup(DNSService.ROLE);
} catch (ServiceException e1) {
log("Failed to retrieve DNSService" + e1.getMessage());
}
bindAddress = getInitParameter("bind");
isBindUsed = bindAddress != null;
try {
if (isBindUsed) RemoteDeliverySocketFactory.setBindAdress(bindAddress);
} catch (UnknownHostException e) {
log("Invalid bind setting (" + bindAddress + "): " + e.toString());
}
// deal with <mail.*> attributes, passing them to javamail
Iterator i = getInitParameterNames();
while (i.hasNext()) {
String name = (String) i.next();
if (name.startsWith("mail.")) {
defprops.put(name,getInitParameter(name));
}
}
String dnsRetry = getInitParameter("maxDnsProblemRetries");
if (dnsRetry != null && !dnsRetry.equals("")) {
dnsProblemRetry = Integer.parseInt(dnsRetry);
}
}
/**
* Calculates Total no. of attempts for the specified delayList.
*
* @param delayList
* list of 'Delay' objects
* @return total no. of retry attempts
*/
private int calcTotalAttempts (ArrayList delayList) {
int sum = 0;
Iterator i = delayList.iterator();
while (i.hasNext()) {
Delay delay = (Delay)i.next();
sum += delay.getAttempts();
}
return sum;
}
/**
* This method expands an ArrayList containing Delay objects into an array holding the
* only delaytime in the order.<p>
* So if the list has 2 Delay objects the first having attempts=2 and delaytime 4000
* the second having attempts=1 and delaytime=300000 will be expanded into this array:<p>
* long[0] = 4000<p>
* long[1] = 4000<p>
* long[2] = 300000<p>
* @param list the list to expand
* @return the expanded list
**/
private long[] expandDelays (ArrayList list) {
long[] delays = new long [calcTotalAttempts(list)];
Iterator i = list.iterator();
int idx = 0;
while (i.hasNext()) {
Delay delay = (Delay)i.next();
for (int j=0; j<delay.getAttempts(); j++) {
delays[idx++]= delay.getDelayTime();
}
}
return delays;
}
/**
* This method returns, given a retry-count, the next delay time to use.
* @param retry_count the current retry_count.
* @return the next delay time to use, given the retry count
**/
private long getNextDelay (int retry_count) {
if (retry_count > delayTimes.length) {
return DEFAULT_DELAY_TIME;
}
return delayTimes[retry_count-1];
}
/**
* This class is used to hold a delay time and its corresponding number of
* retries.
**/
private class Delay {
private int attempts = 1;
private long delayTime = DEFAULT_DELAY_TIME;
/**
* This constructor expects Strings of the form
* "[attempt\*]delaytime[unit]".
* <p>
* The optional attempt is the number of tries this delay should be used
* (default = 1). The unit, if present, must be one of
* (msec,sec,minute,hour,day). The default value of unit is 'msec'.
* <p>
* The constructor multiplies the delaytime by the relevant multiplier
* for the unit, so the delayTime instance variable is always in msec.
*
* @param initString
* the string to initialize this Delay object from
**/
public Delay(String initString) throws MessagingException {
// Default unit value to 'msec'.
String unit = "msec";
if (delayTimeMatcher.matches(initString, PATTERN)) {
MatchResult res = delayTimeMatcher.getMatch();
// The capturing groups will now hold:
// at 1: attempts * (if present)
// at 2: delaytime
// at 3: unit (if present)
if (res.group(1) != null && !res.group(1).equals("")) {
// We have an attempt *
String attemptMatch = res.group(1);
// Strip the * and whitespace.
attemptMatch = attemptMatch.substring(0,
attemptMatch.length() - 1).trim();
attempts = Integer.parseInt(attemptMatch);
}
delayTime = Long.parseLong(res.group(2));
if (!res.group(3).equals("")) {
// We have a value for 'unit'.
unit = res.group(3).toLowerCase(Locale.US);
}
} else {
throw new MessagingException(initString + " does not match "
+ PATTERN_STRING);
}
// calculate delayTime.
try {
delayTime = TimeConverter.getMilliSeconds(delayTime, unit);
} catch (NumberFormatException e) {
throw new MessagingException(e.getMessage());
}
}
/**
* This constructor makes a default Delay object with attempts = 1 and
* delayTime = DEFAULT_DELAY_TIME.
**/
public Delay() {
}
/**
* @return the delayTime for this Delay
**/
public long getDelayTime() {
return delayTime;
}
/**
* @return the number attempts this Delay should be used.
**/
public int getAttempts() {
return attempts;
}
/**
* Set the number attempts this Delay should be used.
**/
public void setAttempts(int value) {
attempts = value;
}
/**
* Pretty prints this Delay
**/
public String toString() {
String message = getAttempts() + "*" + getDelayTime() + "msecs";
return message;
}
}
public String getMailetInfo() {
return "RemoteDelivery Mailet";
}
/**
* For this message, we take the list of recipients, organize these into distinct
* servers, and duplicate the message for each of these servers, and then call
* the deliver (messagecontainer) method for each server-specific
* messagecontainer ... that will handle storing it in the outgoing queue if needed.
*
* @param mail org.apache.mailet.Mail
*/
public void service(Mail mail) throws MessagingException{
// Do I want to give the internal key, or the message's Message ID
if (isDebug) {
log("Remotely delivering mail " + mail.getName());
}
Collection recipients = mail.getRecipients();
if (gatewayServer == null) {
// Must first organize the recipients into distinct servers (name made case insensitive)
Hashtable targets = new Hashtable();
for (Iterator i = recipients.iterator(); i.hasNext();) {
MailAddress target = (MailAddress)i.next();
String targetServer = target.getHost().toLowerCase(Locale.US);
Collection temp = (Collection)targets.get(targetServer);
if (temp == null) {
temp = new ArrayList();
targets.put(targetServer, temp);
}
temp.add(target);
}
//We have the recipients organized into distinct servers... put them into the
//delivery store organized like this... this is ultra inefficient I think...
// Store the new message containers, organized by server, in the outgoing mail repository
String name = mail.getName();
for (Iterator i = targets.keySet().iterator(); i.hasNext(); ) {
String host = (String) i.next();
Collection rec = (Collection) targets.get(host);
if (isDebug) {
StringBuffer logMessageBuffer =
new StringBuffer(128)
.append("Sending mail to ")
.append(rec)
.append(" on host ")
.append(host);
log(logMessageBuffer.toString());
}
mail.setRecipients(rec);
StringBuffer nameBuffer =
new StringBuffer(128)
.append(name)
.append("-to-")
.append(host);
mail.setName(nameBuffer.toString());
workRepository.store(mail);
//Set it to try to deliver (in a separate thread) immediately (triggered by storage)
}
} else {
// Store the mail unaltered for processing by the gateway server(s)
if (isDebug) {
StringBuffer logMessageBuffer =
new StringBuffer(128)
.append("Sending mail to ")
.append(mail.getRecipients())
.append(" via ")
.append(gatewayServer);
log(logMessageBuffer.toString());
}
//Set it to try to deliver (in a separate thread) immediately (triggered by storage)
workRepository.store(mail);
}
mail.setState(Mail.GHOST);
}
/**
* Stops all the worker threads that are waiting for messages. This method is
* called by the Mailet container before taking this Mailet out of service.
*/
public synchronized void destroy() {
// Mark flag so threads from this Mailet stop themselves
destroyed = true;
// Wake up all threads from waiting for an accept
for (Iterator i = workersThreads.iterator(); i.hasNext(); ) {
Thread t = (Thread)i.next();
t.interrupt();
}
notifyAll();
}
/**
* Handles checking the outgoing spool for new mail and delivering them if
* there are any
*/
public void run() {
/* TODO: CHANGE ME!!! The problem is that we need to wait for James to
* finish initializing. We expect the HELLO_NAME to be put into
* the MailetContext, but in the current configuration we get
* started before the SMTP Server, which establishes the value.
* Since there is no contractual guarantee that there will be a
* HELLO_NAME value, we can't just wait for it. As a temporary
* measure, I'm inserting this philosophically unsatisfactory
* fix.
*/
long stop = System.currentTimeMillis() + 60000;
while ((getMailetContext().getAttribute(Constants.HELLO_NAME) == null)
&& stop > System.currentTimeMillis()) {
try {
Thread.sleep(1000);
} catch (Exception ignored) {} // wait for James to finish initializing
}
//Checks the pool and delivers a mail message
Properties props = new Properties();
//Not needed for production environment
props.put("mail.debug", "false");
// Reactivated: javamail 1.3.2 should no more have problems with "250 OK"
// messages (WAS "false": Prevents problems encountered with 250 OK Messages)
props.put("mail.smtp.ehlo", "true");
// By setting this property to true the transport is allowed to
// send 8 bit data to the server (if it supports the 8bitmime extension).
// 2006/03/01 reverted to false because of a javamail bug converting to 8bit
// messages created by an inputstream.
props.setProperty("mail.smtp.allow8bitmime", "true");
//Sets timeout on going connections
props.put("mail.smtp.timeout", smtpTimeout + "");
props.put("mail.smtp.connectiontimeout", connectionTimeout + "");
props.put("mail.smtp.sendpartial",String.valueOf(sendPartial));
//Set the hostname we'll use as this server
if (getMailetContext().getAttribute(Constants.HELLO_NAME) != null) {
props.put("mail.smtp.localhost", getMailetContext().getAttribute(Constants.HELLO_NAME));
}
else {
String defaultDomain = (String) getMailetContext().getAttribute(Constants.DEFAULT_DOMAIN);
if (defaultDomain != null) {
props.put("mail.smtp.localhost", defaultDomain);
}
}
if (isBindUsed) {
// undocumented JavaMail 1.2 feature, smtp transport will use
// our socket factory, which will also set the local address
props.put("mail.smtp.socketFactory.class", RemoteDeliverySocketFactory.class.getClass());
// Don't fallback to the standard socket factory on error, do throw an exception
props.put("mail.smtp.socketFactory.fallback", "false");
}
if (authUser != null) {
props.put("mail.smtp.auth","true");
}
props.putAll(defprops);
Session session = obtainSession(props);
try {
while (!Thread.interrupted() && !destroyed) {
try {
// Get the 'mail' object that is ready for deliverying. If no
// message is
// ready, the 'accept' will block until message is ready.
// The amount
// of time to block is determined by the 'getWaitTime'
// method of the
// MultipleDelayFilter.
Mail mail = workRepository.accept(delayFilter);
String key = mail.getName();
try {
if (isDebug) {
String message = Thread.currentThread().getName()
+ " will process mail " + key;
log(message);
}
// Deliver message
if (deliver(mail, session)) {
// Message was successfully delivered/fully failed...
// delete it
ContainerUtil.dispose(mail);
workRepository.remove(key);
} else {
// Something happened that will delay delivery.
// Store it back in the retry repository.
workRepository.store(mail);
ContainerUtil.dispose(mail);
// This is an update, so we have to unlock and
// notify or this mail is kept locked by this thread.
workRepository.unlock(key);
// Note: We do not notify because we updated an
// already existing mail and we are now free to handle
// more mails.
// Furthermore this mail should not be processed now
// because we have a retry time scheduling.
}
// Clear the object handle to make sure it recycles
// this object.
mail = null;
} catch (Exception e) {
// Prevent unexpected exceptions from causing looping by
// removing message from outgoing.
// DO NOT CHANGE THIS to catch Error! For example, if
// there were an OutOfMemory condition caused because
// something else in the server was abusing memory, we would
// not want to start purging the retrying spool!
ContainerUtil.dispose(mail);
workRepository.remove(key);
throw e;
}
} catch (Throwable e) {
if (!destroyed) {
log("Exception caught in RemoteDelivery.run()", e);
}
}
}
} finally {
// Restore the thread state to non-interrupted.
Thread.interrupted();
}
}
/**
* We can assume that the recipients of this message are all going to the same
* mail server. We will now rely on the DNS server to do DNS MX record lookup
* and try to deliver to the multiple mail servers. If it fails, it should
* throw an exception.
*
* Creation date: (2/24/00 11:25:00 PM)
* @param mail org.apache.james.core.MailImpl
* @param session javax.mail.Session
* @return boolean Whether the delivery was successful and the message can be deleted
*/
private boolean deliver(Mail mail, Session session) {
try {
if (isDebug) {
log("Attempting to deliver " + mail.getName());
}
MimeMessage message = mail.getMessage();
//Create an array of the recipients as InternetAddress objects
Collection recipients = mail.getRecipients();
InternetAddress addr[] = new InternetAddress[recipients.size()];
int j = 0;
for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
MailAddress rcpt = (MailAddress)i.next();
addr[j] = rcpt.toInternetAddress();
}
if (addr.length <= 0) {
log("No recipients specified... not sure how this could have happened.");
return true;
}
//Figure out which servers to try to send to. This collection
// will hold all the possible target servers
Iterator targetServers = null;
if (gatewayServer == null) {
MailAddress rcpt = (MailAddress) recipients.iterator().next();
String host = rcpt.getHost();
//Lookup the possible targets
try {
targetServers = dnsServer.getSMTPHostAddresses(host);
} catch (TemporaryResolutionException e) {
log("Temporary problem looking up mail server for host: " + host);
StringBuffer exceptionBuffer =
new StringBuffer(128)
.append("Temporary problem looking up mail server for host: ")
.append(host)
.append(". I cannot determine where to send this message.");
// temporary problems
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), false);
}
if (!targetServers.hasNext()) {
log("No mail server found for: " + host);
StringBuffer exceptionBuffer =
new StringBuffer(128)
.append("There are no DNS entries for the hostname ")
.append(host)
.append(". I cannot determine where to send this message.");
int retry = 0;
try {
retry = Integer.parseInt(mail.getErrorMessage());
} catch (NumberFormatException e) {
// Unable to parse retryCount
}
if (retry == 0 || retry > dnsProblemRetry) {
// The domain has no dns entry.. Return a permanent error
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), true);
} else {
return failMessage(mail, new MessagingException(exceptionBuffer.toString()), false);
}
}
} else {
targetServers = getGatewaySMTPHostAddresses(gatewayServer);
}
MessagingException lastError = null;
while ( targetServers.hasNext()) {
try {
HostAddress outgoingMailServer = (HostAddress) targetServers.next();
StringBuffer logMessageBuffer =
new StringBuffer(256)
.append("Attempting delivery of ")
.append(mail.getName())
.append(" to host ")
.append(outgoingMailServer.getHostName())
.append(" at ")
.append(outgoingMailServer.getHost())
.append(" for addresses ")
.append(Arrays.asList(addr));
log(logMessageBuffer.toString());
Properties props = session.getProperties();
if (mail.getSender() == null) {
props.put("mail.smtp.from", "<>");
} else {
String sender = mail.getSender().toString();
props.put("mail.smtp.from", sender);
}
//Many of these properties are only in later JavaMail versions
//"mail.smtp.ehlo" //default true
//"mail.smtp.auth" //default false
//"mail.smtp.dsn.ret" //default to nothing... appended as RET= after MAIL FROM line.
//"mail.smtp.dsn.notify" //default to nothing...appended as NOTIFY= after RCPT TO line.
Transport transport = null;
try {
transport = session.getTransport(outgoingMailServer);
try {
if (authUser != null) {
transport.connect(outgoingMailServer.getHostName(), authUser, authPass);
} else {
transport.connect();
}
} catch (MessagingException me) {
// Any error on connect should cause the mailet to attempt
// to connect to the next SMTP server associated with this
// MX record. Just log the exception. We'll worry about
// failing the message at the end of the loop.
log(me.getMessage());
continue;
}
// if the transport is a SMTPTransport (from sun) some
// performance enhancement can be done.
if (transport.getClass().getName().endsWith(".SMTPTransport")) {
boolean supports8bitmime = false;
try {
Method supportsExtension = transport.getClass().getMethod("supportsExtension", new Class[] {String.class});
supports8bitmime = ((Boolean) supportsExtension.invoke(transport, new Object[] {"8BITMIME"})).booleanValue();
} catch (NoSuchMethodException nsme) {
// An SMTPAddressFailedException with no getAddress method.
} catch (IllegalAccessException iae) {
} catch (IllegalArgumentException iae) {
} catch (InvocationTargetException ite) {
// Other issues with getAddress invokation.
}
// if the message is alredy 8bit or binary and the
// server doesn't support the 8bit extension it has
// to be converted to 7bit. Javamail api doesn't perform
// that conversion, but it is required to be a
// rfc-compliant smtp server.
// Temporarily disabled. See JAMES-638
if (!supports8bitmime) {
try {
convertTo7Bit(message);
} catch (IOException e) {
// An error has occured during the 7bit conversion.
// The error is logged and the message is sent anyway.
log("Error during the conversion to 7 bit.", e);
}
}
} else {
// If the transport is not the one
// developed by Sun we are not sure of how it
// handles the 8 bit mime stuff,
// so I convert the message to 7bit.
try {
convertTo7Bit(message);
} catch (IOException e) {
log("Error during the conversion to 7 bit.", e);
}
}
transport.sendMessage(message, addr);
} finally {
if (transport != null) {
transport.close();
transport = null;
}
}
logMessageBuffer =
new StringBuffer(256)
.append("Mail (")
.append(mail.getName())
.append(") sent successfully to ")
.append(outgoingMailServer.getHostName())
.append(" at ")
.append(outgoingMailServer.getHost())
.append(" for ")
.append(mail.getRecipients());
log(logMessageBuffer.toString());
return true;
} catch (SendFailedException sfe) {
logSendFailedException(sfe);
if (sfe.getValidSentAddresses() != null) {
Address[] validSent = sfe.getValidSentAddresses();
if (validSent.length > 0) {
StringBuffer logMessageBuffer =
new StringBuffer(256)
.append("Mail (")
.append(mail.getName())
.append(") sent successfully for ")
.append(Arrays.asList(validSent));
log(logMessageBuffer.toString());
}
}
/* SMTPSendFailedException introduced in JavaMail 1.3.2, and provides detailed protocol reply code for the operation */
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
try {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
// if 5xx, terminate this delivery attempt by re-throwing the exception.
if (returnCode >= 500 && returnCode <= 599) throw sfe;
} catch (ClassCastException cce) {
} catch (IllegalArgumentException iae) {
}
}
if (sfe.getValidUnsentAddresses() != null
&& sfe.getValidUnsentAddresses().length > 0) {
if (isDebug) log("Send failed, " + sfe.getValidUnsentAddresses().length + " valid addresses remain, continuing with any other servers");
lastError = sfe;
continue;
} else {
// There are no valid addresses left to send, so rethrow
throw sfe;
}
} catch (MessagingException me) {
//MessagingException are horribly difficult to figure out what actually happened.
StringBuffer exceptionBuffer =
new StringBuffer(256)
.append("Exception delivering message (")
.append(mail.getName())
.append(") - ")
.append(me.getMessage());
log(exceptionBuffer.toString());
if ((me.getNextException() != null) &&
(me.getNextException() instanceof java.io.IOException)) {
//This is more than likely a temporary failure
// If it's an IO exception with no nested exception, it's probably
// some socket or weird I/O related problem.
lastError = me;
continue;
}
// This was not a connection or I/O error particular to one
// SMTP server of an MX set. Instead, it is almost certainly
// a protocol level error. In this case we assume that this
// is an error we'd encounter with any of the SMTP servers
// associated with this MX record, and we pass the exception
// to the code in the outer block that determines its severity.
throw me;
}
} // end while
//If we encountered an exception while looping through,
//throw the last MessagingException we caught. We only
//do this if we were unable to send the message to any
//server. If sending eventually succeeded, we exit
//deliver() though the return at the end of the try
//block.
if (lastError != null) {
throw lastError;
}
} catch (SendFailedException sfe) {
logSendFailedException(sfe);
Collection recipients = mail.getRecipients();
boolean deleteMessage = false;
/*
* If you send a message that has multiple invalid
* addresses, you'll get a top-level SendFailedException
* that that has the valid, valid-unsent, and invalid
* address lists, with all of the server response messages
* will be contained within the nested exceptions. [Note:
* the content of the nested exceptions is implementation
* dependent.]
*
* sfe.getInvalidAddresses() should be considered permanent.
* sfe.getValidUnsentAddresses() should be considered temporary.
*
* JavaMail v1.3 properly populates those collections based
* upon the 4xx and 5xx response codes to RCPT TO. Some
* servers, such as Yahoo! don't respond to the RCPT TO,
* and provide a 5xx reply after DATA. In that case, we
* will pick up the failure from SMTPSendFailedException.
*
*/
/* SMTPSendFailedException introduced in JavaMail 1.3.2, and provides detailed protocol reply code for the operation */
try {
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
// If we got an SMTPSendFailedException, use its RetCode to determine default permanent/temporary failure
deleteMessage = (returnCode >= 500 && returnCode <= 599);
} else {
// Sometimes we'll get a normal SendFailedException with nested SMTPAddressFailedException, so use the latter RetCode
MessagingException me = sfe;
Exception ne;
while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
me = (MessagingException)ne;
if (me.getClass().getName().endsWith(".SMTPAddressFailedException")) {
int returnCode = ((Integer) invokeGetter(me, "getReturnCode")).intValue();
deleteMessage = (returnCode >= 500 && returnCode <= 599);
}
}
}
} catch (IllegalStateException ise) {
// unexpected exception (not a compatible javamail implementation)
} catch (ClassCastException cce) {
// unexpected exception (not a compatible javamail implementation)
}
// log the original set of intended recipients
if (isDebug) log("Recipients: " + recipients);
if (sfe.getInvalidAddresses() != null) {
Address[] address = sfe.getInvalidAddresses();
if (address.length > 0) {
recipients.clear();
for (int i = 0; i < address.length; i++) {
try {
recipients.add(new MailAddress(address[i].toString()));
} catch (ParseException pe) {
// this should never happen ... we should have
// caught malformed addresses long before we
// got to this code.
log("Can't parse invalid address: " + pe.getMessage());
}
}
if (isDebug) log("Invalid recipients: " + recipients);
deleteMessage = failMessage(mail, sfe, true);
}
}
if (sfe.getValidUnsentAddresses() != null) {
Address[] address = sfe.getValidUnsentAddresses();
if (address.length > 0) {
recipients.clear();
for (int i = 0; i < address.length; i++) {
try {
recipients.add(new MailAddress(address[i].toString()));
} catch (ParseException pe) {
// this should never happen ... we should have
// caught malformed addresses long before we
// got to this code.
log("Can't parse unsent address: " + pe.getMessage());
}
}
if (isDebug) log("Unsent recipients: " + recipients);
if (sfe.getClass().getName().endsWith(".SMTPSendFailedException")) {
int returnCode = ((Integer) invokeGetter(sfe, "getReturnCode")).intValue();
deleteMessage = failMessage(mail, sfe, returnCode >= 500 && returnCode <= 599);
} else {
deleteMessage = failMessage(mail, sfe, false);
}
}
}
return deleteMessage;
} catch (MessagingException ex) {
// We should do a better job checking this... if the failure is a general
// connect exception, this is less descriptive than more specific SMTP command
// failure... have to lookup and see what are the various Exception
// possibilities
// Unable to deliver message after numerous tries... fail accordingly
// We check whether this is a 5xx error message, which
// indicates a permanent failure (like account doesn't exist
// or mailbox is full or domain is setup wrong).
// We fail permanently if this was a 5xx error
return failMessage(mail, ex, ('5' == ex.getMessage().charAt(0)));
} catch (Exception ex) {
// Generic exception = permanent failure
return failMessage(mail, ex, true);
}
/* If we get here, we've exhausted the loop of servers without
* sending the message or throwing an exception. One case
* where this might happen is if we get a MessagingException on
* each transport.connect(), e.g., if there is only one server
* and we get a connect exception.
*/
return failMessage(mail, new MessagingException("No mail server(s) available at this time."), false);
}
/**
* Try to return a usefull logString created of the Exception which was given.
* Return null if nothing usefull could be done
*
* @param e The MessagingException to use
* @return logString
*/
private String exceptionToLogString(Exception e) {
if (e.getClass().getName().endsWith(".SMTPSendFailedException")) {
return "RemoteHost said: " + e.getMessage();
} else if (e instanceof SendFailedException) {
SendFailedException exception = (SendFailedException) e;
// No error
if ( exception.getInvalidAddresses().length == 0 &&
exception.getValidUnsentAddresses().length == 0) return null;
Exception ex;
StringBuffer sb = new StringBuffer();
boolean smtpExFound = false;
sb.append("RemoteHost said:");
if (e instanceof MessagingException) while((ex = ((MessagingException) e).getNextException()) != null && ex instanceof MessagingException) {
e = ex;
if (ex.getClass().getName().endsWith(".SMTPAddressFailedException")) {
try {
InternetAddress ia = (InternetAddress) invokeGetter(ex, "getAddress");
sb.append(" ( " + ia + " - [" + ex.getMessage().replaceAll("\\n", "") + "] )");
smtpExFound = true;
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
} catch (ClassCastException cce) {
// The getAddress method returned something different than InternetAddress
}
}
}
if (!smtpExFound) {
boolean invalidAddr = false;
sb.append(" ( ");
if (exception.getInvalidAddresses().length > 0) {
sb.append(exception.getInvalidAddresses());
invalidAddr = true;
}
if (exception.getValidUnsentAddresses().length > 0) {
if (invalidAddr == true) sb.append(" " );
sb.append(exception.getValidUnsentAddresses());
}
sb.append(" - [");
sb.append(exception.getMessage().replaceAll("\\n", ""));
sb.append("] )");
}
return sb.toString();
}
return null;
}
/**
* Utility method used to invoke getters for javamail implementation specific classes.
*
* @param target the object whom method will be invoked
* @param getter the no argument method name
* @return the result object
* @throws IllegalStateException on invocation error
*/
private Object invokeGetter(Object target, String getter) {
try {
Method getAddress = target.getClass().getMethod(getter, null);
return getAddress.invoke(target, null);
} catch (NoSuchMethodException nsme) {
// An SMTPAddressFailedException with no getAddress method.
} catch (IllegalAccessException iae) {
} catch (IllegalArgumentException iae) {
} catch (InvocationTargetException ite) {
// Other issues with getAddress invokation.
}
return new IllegalStateException("Exception invoking "+getter+" on a "+target.getClass()+" object");
}
/*
* private method to log the extended SendFailedException introduced in JavaMail 1.3.2.
*/
private void logSendFailedException(SendFailedException sfe) {
if (isDebug) {
MessagingException me = sfe;
if (me.getClass().getName().endsWith(".SMTPSendFailedException")) {
try {
String command = (String) invokeGetter(sfe, "getCommand");
Integer returnCode = (Integer) invokeGetter(sfe, "getReturnCode");
log("SMTP SEND FAILED:");
log(sfe.toString());
log(" Command: " + command);
log(" RetCode: " + returnCode);
log(" Response: " + sfe.getMessage());
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
log("Send failed: " + me.toString());
} catch (ClassCastException cce) {
// The getAddress method returned something different than InternetAddress
log("Send failed: " + me.toString());
}
} else {
log("Send failed: " + me.toString());
}
Exception ne;
while ((ne = me.getNextException()) != null && ne instanceof MessagingException) {
me = (MessagingException)ne;
if (me.getClass().getName().endsWith(".SMTPAddressFailedException") || me.getClass().getName().endsWith(".SMTPAddressSucceededException")) {
try {
String action = me.getClass().getName().endsWith(".SMTPAddressFailedException") ? "FAILED" : "SUCCEEDED";
InternetAddress address = (InternetAddress) invokeGetter(me, "getAddress");
String command = (String) invokeGetter(me, "getCommand");
Integer returnCode = (Integer) invokeGetter(me, "getReturnCode");
log("ADDRESS "+action+":");
log(me.toString());
log(" Address: " + address);
log(" Command: " + command);
log(" RetCode: " + returnCode);
log(" Response: " + me.getMessage());
} catch (IllegalStateException ise) {
// Error invoking the getAddress method
} catch (ClassCastException cce) {
// A method returned something different than expected
}
}
}
}
}
/**
* Converts a message to 7 bit.
*
* @param part
*/
private void convertTo7Bit(MimePart part) throws MessagingException, IOException {
if (part.isMimeType("multipart/*")) {
MimeMultipart parts = (MimeMultipart) part.getContent();
int count = parts.getCount();
for (int i = 0; i < count; i++) {
convertTo7Bit((MimePart)parts.getBodyPart(i));
}
} else if ("8bit".equals(part.getEncoding())) {
// The content may already be in encoded the form (likely with mail created from a
// stream). In that case, just changing the encoding to quoted-printable will mangle
// the result when this is transmitted. We must first convert the content into its
// native format, set it back, and only THEN set the transfer encoding to force the
// content to be encoded appropriately.
// if the part doesn't contain text it will be base64 encoded.
String contentTransferEncoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";
part.setContent(part.getContent(), part.getContentType());
part.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
part.addHeader("X-MIME-Autoconverted", "from 8bit to "+contentTransferEncoding+" by "+getMailetContext().getServerInfo());
}
}
/**
* Insert the method's description here.
* Creation date: (2/25/00 1:14:18 AM)
* @param mail org.apache.james.core.MailImpl
* @param ex javax.mail.MessagingException
* @param permanent
* @return boolean Whether the message failed fully and can be deleted
*/
private boolean failMessage(Mail mail, Exception ex, boolean permanent) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
if (permanent) {
out.print("Permanent");
} else {
out.print("Temporary");
}
String exceptionLog = exceptionToLogString(ex);
StringBuffer logBuffer =
new StringBuffer(64)
.append(" exception delivering mail (")
.append(mail.getName());
if (exceptionLog != null) {
logBuffer.append(". ");
logBuffer.append(exceptionLog);
}
logBuffer.append(": ");
out.print(logBuffer.toString());
if (isDebug) ex.printStackTrace(out);
log(sout.toString());
if (!permanent) {
if (!mail.getState().equals(Mail.ERROR)) {
mail.setState(Mail.ERROR);
mail.setErrorMessage("0");
mail.setLastUpdated(new Date());
}
int retries = 0;
try {
retries = Integer.parseInt(mail.getErrorMessage());
} catch (NumberFormatException e) {
// Something strange was happen with the errorMessage..
}
if (retries < maxRetries) {
logBuffer =
new StringBuffer(128)
.append("Storing message ")
.append(mail.getName())
.append(" into outgoing after ")
.append(retries)
.append(" retries");
log(logBuffer.toString());
++retries;
mail.setErrorMessage(retries + "");
mail.setLastUpdated(new Date());
return false;
} else {
logBuffer =
new StringBuffer(128)
.append("Bouncing message ")
.append(mail.getName())
.append(" after ")
.append(retries)
.append(" retries");
log(logBuffer.toString());
}
}
if (mail.getSender() == null) {
log("Null Sender: no bounce will be generated for " + mail.getName());
return true;
}
if (bounceProcessor != null) {
// do the new DSN bounce
// setting attributes for DSN mailet
mail.setAttribute("delivery-error", ex);
mail.setState(bounceProcessor);
// re-insert the mail into the spool for getting it passed to the dsn-processor
MailetContext mc = getMailetContext();
try {
mc.sendMail(mail);
} catch (MessagingException e) {
// we shouldn't get an exception, because the mail was already processed
log("Exception re-inserting failed mail: ", e);
}
} else {
// do an old style bounce
bounce(mail, ex);
}
return true;
}
private void bounce(Mail mail, Exception ex) {
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
String machine = "[unknown]";
try {
machine = getMailetContext().getAttribute(Constants.HOSTNAME).toString();
} catch(Exception e){
machine = "[address unknown]";
}
StringBuffer bounceBuffer =
new StringBuffer(128)
.append("Hi. This is the James mail server at ")
.append(machine)
.append(".");
out.println(bounceBuffer.toString());
out.println("I'm afraid I wasn't able to deliver your message to the following addresses.");
out.println("This is a permanent error; I've given up. Sorry it didn't work out. Below");
out.println("I include the list of recipients and the reason why I was unable to deliver");
out.println("your message.");
out.println();
for (Iterator i = mail.getRecipients().iterator(); i.hasNext(); ) {
out.println(i.next());
}
if (ex instanceof MessagingException) {
if (((MessagingException) ex).getNextException() == null) {
out.println(ex.getMessage().trim());
} else {
Exception ex1 = ((MessagingException) ex).getNextException();
if (ex1 instanceof SendFailedException) {
out.println("Remote mail server told me: " + ex1.getMessage().trim());
} else if (ex1 instanceof UnknownHostException) {
out.println("Unknown host: " + ex1.getMessage().trim());
out.println("This could be a DNS server error, a typo, or a problem with the recipient's mail server.");
} else if (ex1 instanceof ConnectException) {
//Already formatted as "Connection timed out: connect"
out.println(ex1.getMessage().trim());
} else if (ex1 instanceof SocketException) {
out.println("Socket exception: " + ex1.getMessage().trim());
} else {
out.println(ex1.getMessage().trim());
}
}
}
out.println();
log("Sending failure message " + mail.getName());
try {
getMailetContext().bounce(mail, sout.toString());
} catch (MessagingException me) {
log("Encountered unexpected messaging exception while bouncing message: " + me.getMessage());
} catch (Exception e) {
log("Encountered unexpected exception while bouncing message: " + e.getMessage());
}
}
/**
* Returns the javamail Session object.
* @param props
* @param authenticator
* @return
*/
protected Session obtainSession(Properties props) {
return Session.getInstance(props);
}
/*
* Returns an Iterator over org.apache.mailet.HostAddress, a
* specialized subclass of javax.mail.URLName, which provides
* location information for servers that are specified as mail
* handlers for the given hostname. If no host is found, the
* Iterator returned will be empty and the first call to hasNext()
* will return false. The Iterator is a nested iterator: the outer
* iteration is over each gateway, and the inner iteration is over
* potentially multiple A records for each gateway.
*
* @see org.apache.james.DNSServer#getSMTPHostAddresses(String)
* @since v2.2.0a16-unstable
* @param gatewayServers - Collection of host[:port] Strings
* @return an Iterator over HostAddress instances, sorted by priority
*/
private Iterator getGatewaySMTPHostAddresses(final Collection gatewayServers) {
return new Iterator() {
private Iterator gateways = gatewayServers.iterator();
private Iterator addresses = null;
public boolean hasNext() {
/* Make sure that when next() is called, that we can
* provide a HostAddress. This means that we need to
* have an inner iterator, and verify that it has
* addresses. We could, for example, run into a
* situation where the next gateway didn't have any
* valid addresses.
*/
if (!hasNextAddress() && gateways.hasNext()) {
do {
String server = (String) gateways.next();
String port = "25";
int idx = server.indexOf(':');
if ( idx > 0) {
port = server.substring(idx+1);
server = server.substring(0,idx);
}
final String nextGateway = server;
final String nextGatewayPort = port;
try {
final InetAddress[] ips = dnsServer.getAllByName(nextGateway);
addresses = new Iterator() {
private InetAddress[] ipAddresses = ips;
int i = 0;
public boolean hasNext() {
return i < ipAddresses.length;
}
public Object next() {
return new org.apache.mailet.HostAddress(nextGateway, "smtp://" + (ipAddresses[i++]).getHostAddress() + ":" + nextGatewayPort);
}
public void remove() {
throw new UnsupportedOperationException ("remove not supported by this iterator");
}
};
}
catch (java.net.UnknownHostException uhe) {
log("Unknown gateway host: " + uhe.getMessage().trim());
log("This could be a DNS server error or configuration error.");
}
} while (!hasNextAddress() && gateways.hasNext());
}
return hasNextAddress();
}
private boolean hasNextAddress() {
return addresses != null && addresses.hasNext();
}
public Object next() {
return (addresses != null) ? addresses.next() : null;
}
public void remove() {
throw new UnsupportedOperationException ("remove not supported by this iterator");
}
};
}
/**
* Setter for the dnsserver service
* @param dnsServer dns service
*/
protected synchronized void setDNSServer(DNSService dnsServer) {
this.dnsServer = dnsServer;
}
}
|
Improved javadocs JAMES-892 https://issues.apache.org/jira/browse/JAMES-892
git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@748865 13f79535-47bb-0310-9956-ffa450edef68
|
mailets-function/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
|
Improved javadocs JAMES-892 https://issues.apache.org/jira/browse/JAMES-892
|
|
Java
|
apache-2.0
|
60be421469dd85893978bfc645b41e94c63ba1b1
| 0
|
JodaOrg/joda-time,mosoft521/joda-time,Shais14/joda-time,Alexey-N-Chernyshov/IU_AST_Mutation_Score,tingting703/mp3_maven,Alexey-N-Chernyshov/IU_AST_Mutation_Score,Shais14/joda-time,flightstats/joda-time,flightstats/joda-time,tingting703/mp3_maven,JodaOrg/joda-time,mosoft521/joda-time
|
/*
* Copyright 2001-2013 Stephen Colebourne
*
* 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.joda.time.tz;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.chrono.ISOChronology;
/**
* DateTimeZoneBuilder allows complex DateTimeZones to be constructed. Since
* creating a new DateTimeZone this way is a relatively expensive operation,
* built zones can be written to a file. Reading back the encoded data is a
* quick operation.
* <p>
* DateTimeZoneBuilder itself is mutable and not thread-safe, but the
* DateTimeZone objects that it builds are thread-safe and immutable.
* <p>
* It is intended that {@link ZoneInfoCompiler} be used to read time zone data
* files, indirectly calling DateTimeZoneBuilder. The following complex
* example defines the America/Los_Angeles time zone, with all historical
* transitions:
*
* <pre>
* DateTimeZone America_Los_Angeles = new DateTimeZoneBuilder()
* .addCutover(-2147483648, 'w', 1, 1, 0, false, 0)
* .setStandardOffset(-28378000)
* .setFixedSavings("LMT", 0)
* .addCutover(1883, 'w', 11, 18, 0, false, 43200000)
* .setStandardOffset(-28800000)
* .addRecurringSavings("PDT", 3600000, 1918, 1919, 'w', 3, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1918, 1919, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PWT", 3600000, 1942, 1942, 'w', 2, 9, 0, false, 7200000)
* .addRecurringSavings("PPT", 3600000, 1945, 1945, 'u', 8, 14, 0, false, 82800000)
* .addRecurringSavings("PST", 0, 1945, 1945, 'w', 9, 30, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1948, 1948, 'w', 3, 14, 0, false, 7200000)
* .addRecurringSavings("PST", 0, 1949, 1949, 'w', 1, 1, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1950, 1966, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1950, 1961, 'w', 9, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1962, 1966, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1967, 2147483647, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1967, 1973, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1974, 1974, 'w', 1, 6, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1975, 1975, 'w', 2, 23, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1976, 1986, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1987, 2147483647, 'w', 4, 1, 7, true, 7200000)
* .toDateTimeZone("America/Los_Angeles", true);
* </pre>
*
* @author Brian S O'Neill
* @see ZoneInfoCompiler
* @see ZoneInfoProvider
* @since 1.0
*/
public class DateTimeZoneBuilder {
/**
* Decodes a built DateTimeZone from the given stream, as encoded by
* writeTo.
*
* @param in input stream to read encoded DateTimeZone from.
* @param id time zone id to assign
*/
public static DateTimeZone readFrom(InputStream in, String id) throws IOException {
if (in instanceof DataInput) {
return readFrom((DataInput)in, id);
} else {
return readFrom((DataInput)new DataInputStream(in), id);
}
}
/**
* Decodes a built DateTimeZone from the given stream, as encoded by
* writeTo.
*
* @param in input stream to read encoded DateTimeZone from.
* @param id time zone id to assign
*/
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
switch (in.readUnsignedByte()) {
case 'F':
DateTimeZone fixed = new FixedDateTimeZone
(id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
if (fixed.equals(DateTimeZone.UTC)) {
fixed = DateTimeZone.UTC;
}
return fixed;
case 'C':
return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
case 'P':
return PrecalculatedZone.readFrom(in, id);
default:
throw new IOException("Invalid encoding");
}
}
/**
* Millisecond encoding formats:
*
* upper two bits units field length approximate range
* ---------------------------------------------------------------
* 00 30 minutes 1 byte +/- 16 hours
* 01 minutes 4 bytes +/- 1020 years
* 10 seconds 5 bytes +/- 4355 years
* 11 millis 9 bytes +/- 292,000,000 years
*
* Remaining bits in field form signed offset from 1970-01-01T00:00:00Z.
*/
static void writeMillis(DataOutput out, long millis) throws IOException {
if (millis % (30 * 60000L) == 0) {
// Try to write in 30 minute units.
long units = millis / (30 * 60000L);
if (((units << (64 - 6)) >> (64 - 6)) == units) {
// Form 00 (6 bits effective precision)
out.writeByte((int)(units & 0x3f));
return;
}
}
if (millis % 60000L == 0) {
// Try to write minutes.
long minutes = millis / 60000L;
if (((minutes << (64 - 30)) >> (64 - 30)) == minutes) {
// Form 01 (30 bits effective precision)
out.writeInt(0x40000000 | (int)(minutes & 0x3fffffff));
return;
}
}
if (millis % 1000L == 0) {
// Try to write seconds.
long seconds = millis / 1000L;
if (((seconds << (64 - 38)) >> (64 - 38)) == seconds) {
// Form 10 (38 bits effective precision)
out.writeByte(0x80 | (int)((seconds >> 32) & 0x3f));
out.writeInt((int)(seconds & 0xffffffff));
return;
}
}
// Write milliseconds either because the additional precision is
// required or the minutes didn't fit in the field.
// Form 11 (64-bits effective precision, but write as if 70 bits)
out.writeByte(millis < 0 ? 0xff : 0xc0);
out.writeLong(millis);
}
/**
* Reads encoding generated by writeMillis.
*/
static long readMillis(DataInput in) throws IOException {
int v = in.readUnsignedByte();
switch (v >> 6) {
case 0: default:
// Form 00 (6 bits effective precision)
v = (v << (32 - 6)) >> (32 - 6);
return v * (30 * 60000L);
case 1:
// Form 01 (30 bits effective precision)
v = (v << (32 - 6)) >> (32 - 30);
v |= (in.readUnsignedByte()) << 16;
v |= (in.readUnsignedByte()) << 8;
v |= (in.readUnsignedByte());
return v * 60000L;
case 2:
// Form 10 (38 bits effective precision)
long w = (((long)v) << (64 - 6)) >> (64 - 38);
w |= (in.readUnsignedByte()) << 24;
w |= (in.readUnsignedByte()) << 16;
w |= (in.readUnsignedByte()) << 8;
w |= (in.readUnsignedByte());
return w * 1000L;
case 3:
// Form 11 (64-bits effective precision)
return in.readLong();
}
}
private static DateTimeZone buildFixedZone(String id, String nameKey,
int wallOffset, int standardOffset) {
if ("UTC".equals(id) && id.equals(nameKey) &&
wallOffset == 0 && standardOffset == 0) {
return DateTimeZone.UTC;
}
return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset);
}
// List of RuleSets.
private final ArrayList<RuleSet> iRuleSets;
public DateTimeZoneBuilder() {
iRuleSets = new ArrayList<RuleSet>(10);
}
/**
* Adds a cutover for added rules. The standard offset at the cutover
* defaults to 0. Call setStandardOffset afterwards to change it.
*
* @param year the year of cutover
* @param mode 'u' - cutover is measured against UTC, 'w' - against wall
* offset, 's' - against standard offset
* @param monthOfYear the month from 1 (January) to 12 (December)
* @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth).
* For example, if -1, set to last day of month
* @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore
* @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to
* dayOfWeek when true, retreat when false.
* @param millisOfDay additional precision for specifying time of day of cutover
*/
public DateTimeZoneBuilder addCutover(int year,
char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek,
boolean advanceDayOfWeek,
int millisOfDay)
{
if (iRuleSets.size() > 0) {
OfYear ofYear = new OfYear
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1);
lastRuleSet.setUpperLimit(year, ofYear);
}
iRuleSets.add(new RuleSet());
return this;
}
/**
* Sets the standard offset to use for newly added rules until the next
* cutover is added.
* @param standardOffset the standard offset in millis
*/
public DateTimeZoneBuilder setStandardOffset(int standardOffset) {
getLastRuleSet().setStandardOffset(standardOffset);
return this;
}
/**
* Set a fixed savings rule at the cutover.
*/
public DateTimeZoneBuilder setFixedSavings(String nameKey, int saveMillis) {
getLastRuleSet().setFixedSavings(nameKey, saveMillis);
return this;
}
/**
* Add a recurring daylight saving time rule.
*
* @param nameKey the name key of new rule
* @param saveMillis the milliseconds to add to standard offset
* @param fromYear the first year that rule is in effect, MIN_VALUE indicates
* beginning of time
* @param toYear the last year (inclusive) that rule is in effect, MAX_VALUE
* indicates end of time
* @param mode 'u' - transitions are calculated against UTC, 'w' -
* transitions are calculated against wall offset, 's' - transitions are
* calculated against standard offset
* @param monthOfYear the month from 1 (January) to 12 (December)
* @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth).
* For example, if -1, set to last day of month
* @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore
* @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to
* dayOfWeek when true, retreat when false.
* @param millisOfDay additional precision for specifying time of day of transitions
*/
public DateTimeZoneBuilder addRecurringSavings(String nameKey, int saveMillis,
int fromYear, int toYear,
char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek,
boolean advanceDayOfWeek,
int millisOfDay)
{
if (fromYear <= toYear) {
OfYear ofYear = new OfYear
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
Recurrence recurrence = new Recurrence(ofYear, nameKey, saveMillis);
Rule rule = new Rule(recurrence, fromYear, toYear);
getLastRuleSet().addRule(rule);
}
return this;
}
private RuleSet getLastRuleSet() {
if (iRuleSets.size() == 0) {
addCutover(Integer.MIN_VALUE, 'w', 1, 1, 0, false, 0);
}
return iRuleSets.get(iRuleSets.size() - 1);
}
/**
* Processes all the rules and builds a DateTimeZone.
*
* @param id time zone id to assign
* @param outputID true if the zone id should be output
*/
public DateTimeZone toDateTimeZone(String id, boolean outputID) {
if (id == null) {
throw new IllegalArgumentException();
}
// Discover where all the transitions occur and store the results in
// these lists.
ArrayList<Transition> transitions = new ArrayList<Transition>();
// Tail zone picks up remaining transitions in the form of an endless
// DST cycle.
DSTZone tailZone = null;
long millis = Long.MIN_VALUE;
int saveMillis = 0;
int ruleSetCount = iRuleSets.size();
for (int i=0; i<ruleSetCount; i++) {
RuleSet rs = iRuleSets.get(i);
Transition next = rs.firstTransition(millis);
if (next == null) {
continue;
}
addTransition(transitions, next);
millis = next.getMillis();
saveMillis = next.getSaveMillis();
// Copy it since we're going to destroy it.
rs = new RuleSet(rs);
while ((next = rs.nextTransition(millis, saveMillis)) != null) {
if (addTransition(transitions, next) && tailZone != null) {
// Got the extra transition before DSTZone.
break;
}
millis = next.getMillis();
saveMillis = next.getSaveMillis();
if (tailZone == null && i == ruleSetCount - 1) {
tailZone = rs.buildTailZone(id);
// If tailZone is not null, don't break out of main loop until
// at least one more transition is calculated. This ensures a
// correct 'seam' to the DSTZone.
}
}
millis = rs.getUpperLimit(saveMillis);
}
// Check if a simpler zone implementation can be returned.
if (transitions.size() == 0) {
if (tailZone != null) {
// This shouldn't happen, but handle just in case.
return tailZone;
}
return buildFixedZone(id, "UTC", 0, 0);
}
if (transitions.size() == 1 && tailZone == null) {
Transition tr = transitions.get(0);
return buildFixedZone(id, tr.getNameKey(),
tr.getWallOffset(), tr.getStandardOffset());
}
PrecalculatedZone zone = PrecalculatedZone.create(id, outputID, transitions, tailZone);
if (zone.isCachable()) {
return CachedDateTimeZone.forZone(zone);
}
return zone;
}
private boolean addTransition(ArrayList<Transition> transitions, Transition tr) {
int size = transitions.size();
if (size == 0) {
transitions.add(tr);
return true;
}
Transition last = transitions.get(size - 1);
if (!tr.isTransitionFrom(last)) {
return false;
}
// If local time of new transition is same as last local time, just
// replace last transition with new one.
int offsetForLast = 0;
if (size >= 2) {
offsetForLast = transitions.get(size - 2).getWallOffset();
}
int offsetForNew = last.getWallOffset();
long lastLocal = last.getMillis() + offsetForLast;
long newLocal = tr.getMillis() + offsetForNew;
if (newLocal != lastLocal) {
transitions.add(tr);
return true;
}
transitions.remove(size - 1);
return addTransition(transitions, tr);
}
/**
* Encodes a built DateTimeZone to the given stream. Call readFrom to
* decode the data into a DateTimeZone object.
*
* @param out the output stream to receive the encoded DateTimeZone
* @since 1.5 (parameter added)
*/
public void writeTo(String zoneID, OutputStream out) throws IOException {
if (out instanceof DataOutput) {
writeTo(zoneID, (DataOutput)out);
} else {
DataOutputStream dout = new DataOutputStream(out);
writeTo(zoneID, (DataOutput)dout);
dout.flush();
}
}
/**
* Encodes a built DateTimeZone to the given stream. Call readFrom to
* decode the data into a DateTimeZone object.
*
* @param out the output stream to receive the encoded DateTimeZone
* @since 1.5 (parameter added)
*/
public void writeTo(String zoneID, DataOutput out) throws IOException {
// pass false so zone id is not written out
DateTimeZone zone = toDateTimeZone(zoneID, false);
if (zone instanceof FixedDateTimeZone) {
out.writeByte('F'); // 'F' for fixed
out.writeUTF(zone.getNameKey(0));
writeMillis(out, zone.getOffset(0));
writeMillis(out, zone.getStandardOffset(0));
} else {
if (zone instanceof CachedDateTimeZone) {
out.writeByte('C'); // 'C' for cached, precalculated
zone = ((CachedDateTimeZone)zone).getUncachedZone();
} else {
out.writeByte('P'); // 'P' for precalculated, uncached
}
((PrecalculatedZone)zone).writeTo(out);
}
}
/**
* Supports setting fields of year and moving between transitions.
*/
private static final class OfYear {
static OfYear readFrom(DataInput in) throws IOException {
return new OfYear((char)in.readUnsignedByte(),
(int)in.readUnsignedByte(),
(int)in.readByte(),
(int)in.readUnsignedByte(),
in.readBoolean(),
(int)readMillis(in));
}
// Is 'u', 'w', or 's'.
final char iMode;
final int iMonthOfYear;
final int iDayOfMonth;
final int iDayOfWeek;
final boolean iAdvance;
final int iMillisOfDay;
OfYear(char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek, boolean advanceDayOfWeek,
int millisOfDay)
{
if (mode != 'u' && mode != 'w' && mode != 's') {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
iMode = mode;
iMonthOfYear = monthOfYear;
iDayOfMonth = dayOfMonth;
iDayOfWeek = dayOfWeek;
iAdvance = advanceDayOfWeek;
iMillisOfDay = millisOfDay;
}
/**
* @param standardOffset standard offset just before instant
*/
public long setInstant(int year, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
Chronology chrono = ISOChronology.getInstanceUTC();
long millis = chrono.year().set(0, year);
millis = chrono.monthOfYear().set(millis, iMonthOfYear);
millis = chrono.millisOfDay().set(millis, iMillisOfDay);
millis = setDayOfMonth(chrono, millis);
if (iDayOfWeek != 0) {
millis = setDayOfWeek(chrono, millis);
}
// Convert from local time to UTC.
return millis - offset;
}
/**
* @param standardOffset standard offset just before next recurrence
*/
public long next(long instant, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
// Convert from UTC to local time.
instant += offset;
Chronology chrono = ISOChronology.getInstanceUTC();
long next = chrono.monthOfYear().set(instant, iMonthOfYear);
// Be lenient with millisOfDay.
next = chrono.millisOfDay().set(next, 0);
next = chrono.millisOfDay().add(next, iMillisOfDay);
next = setDayOfMonthNext(chrono, next);
if (iDayOfWeek == 0) {
if (next <= instant) {
next = chrono.year().add(next, 1);
next = setDayOfMonthNext(chrono, next);
}
} else {
next = setDayOfWeek(chrono, next);
if (next <= instant) {
next = chrono.year().add(next, 1);
next = chrono.monthOfYear().set(next, iMonthOfYear);
next = setDayOfMonthNext(chrono, next);
next = setDayOfWeek(chrono, next);
}
}
// Convert from local time to UTC.
return next - offset;
}
/**
* @param standardOffset standard offset just before previous recurrence
*/
public long previous(long instant, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
// Convert from UTC to local time.
instant += offset;
Chronology chrono = ISOChronology.getInstanceUTC();
long prev = chrono.monthOfYear().set(instant, iMonthOfYear);
// Be lenient with millisOfDay.
prev = chrono.millisOfDay().set(prev, 0);
prev = chrono.millisOfDay().add(prev, iMillisOfDay);
prev = setDayOfMonthPrevious(chrono, prev);
if (iDayOfWeek == 0) {
if (prev >= instant) {
prev = chrono.year().add(prev, -1);
prev = setDayOfMonthPrevious(chrono, prev);
}
} else {
prev = setDayOfWeek(chrono, prev);
if (prev >= instant) {
prev = chrono.year().add(prev, -1);
prev = chrono.monthOfYear().set(prev, iMonthOfYear);
prev = setDayOfMonthPrevious(chrono, prev);
prev = setDayOfWeek(chrono, prev);
}
}
// Convert from local time to UTC.
return prev - offset;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof OfYear) {
OfYear other = (OfYear)obj;
return
iMode == other.iMode &&
iMonthOfYear == other.iMonthOfYear &&
iDayOfMonth == other.iDayOfMonth &&
iDayOfWeek == other.iDayOfWeek &&
iAdvance == other.iAdvance &&
iMillisOfDay == other.iMillisOfDay;
}
return false;
}
/*
public String toString() {
return
"[OfYear]\n" +
"Mode: " + iMode + '\n' +
"MonthOfYear: " + iMonthOfYear + '\n' +
"DayOfMonth: " + iDayOfMonth + '\n' +
"DayOfWeek: " + iDayOfWeek + '\n' +
"AdvanceDayOfWeek: " + iAdvance + '\n' +
"MillisOfDay: " + iMillisOfDay + '\n';
}
*/
public void writeTo(DataOutput out) throws IOException {
out.writeByte(iMode);
out.writeByte(iMonthOfYear);
out.writeByte(iDayOfMonth);
out.writeByte(iDayOfWeek);
out.writeBoolean(iAdvance);
writeMillis(out, iMillisOfDay);
}
/**
* If month-day is 02-29 and year isn't leap, advances to next leap year.
*/
private long setDayOfMonthNext(Chronology chrono, long next) {
try {
next = setDayOfMonth(chrono, next);
} catch (IllegalArgumentException e) {
if (iMonthOfYear == 2 && iDayOfMonth == 29) {
while (chrono.year().isLeap(next) == false) {
next = chrono.year().add(next, 1);
}
next = setDayOfMonth(chrono, next);
} else {
throw e;
}
}
return next;
}
/**
* If month-day is 02-29 and year isn't leap, retreats to previous leap year.
*/
private long setDayOfMonthPrevious(Chronology chrono, long prev) {
try {
prev = setDayOfMonth(chrono, prev);
} catch (IllegalArgumentException e) {
if (iMonthOfYear == 2 && iDayOfMonth == 29) {
while (chrono.year().isLeap(prev) == false) {
prev = chrono.year().add(prev, -1);
}
prev = setDayOfMonth(chrono, prev);
} else {
throw e;
}
}
return prev;
}
private long setDayOfMonth(Chronology chrono, long instant) {
if (iDayOfMonth >= 0) {
instant = chrono.dayOfMonth().set(instant, iDayOfMonth);
} else {
instant = chrono.dayOfMonth().set(instant, 1);
instant = chrono.monthOfYear().add(instant, 1);
instant = chrono.dayOfMonth().add(instant, iDayOfMonth);
}
return instant;
}
private long setDayOfWeek(Chronology chrono, long instant) {
int dayOfWeek = chrono.dayOfWeek().get(instant);
int daysToAdd = iDayOfWeek - dayOfWeek;
if (daysToAdd != 0) {
if (iAdvance) {
if (daysToAdd < 0) {
daysToAdd += 7;
}
} else {
if (daysToAdd > 0) {
daysToAdd -= 7;
}
}
instant = chrono.dayOfWeek().add(instant, daysToAdd);
}
return instant;
}
}
/**
* Extends OfYear with a nameKey and savings.
*/
private static final class Recurrence {
static Recurrence readFrom(DataInput in) throws IOException {
return new Recurrence(OfYear.readFrom(in), in.readUTF(), (int)readMillis(in));
}
final OfYear iOfYear;
final String iNameKey;
final int iSaveMillis;
Recurrence(OfYear ofYear, String nameKey, int saveMillis) {
iOfYear = ofYear;
iNameKey = nameKey;
iSaveMillis = saveMillis;
}
public OfYear getOfYear() {
return iOfYear;
}
/**
* @param standardOffset standard offset just before next recurrence
*/
public long next(long instant, int standardOffset, int saveMillis) {
return iOfYear.next(instant, standardOffset, saveMillis);
}
/**
* @param standardOffset standard offset just before previous recurrence
*/
public long previous(long instant, int standardOffset, int saveMillis) {
return iOfYear.previous(instant, standardOffset, saveMillis);
}
public String getNameKey() {
return iNameKey;
}
public int getSaveMillis() {
return iSaveMillis;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Recurrence) {
Recurrence other = (Recurrence)obj;
return
iSaveMillis == other.iSaveMillis &&
iNameKey.equals(other.iNameKey) &&
iOfYear.equals(other.iOfYear);
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
iOfYear.writeTo(out);
out.writeUTF(iNameKey);
writeMillis(out, iSaveMillis);
}
Recurrence rename(String nameKey) {
return new Recurrence(iOfYear, nameKey, iSaveMillis);
}
Recurrence renameAppend(String appendNameKey) {
return rename((iNameKey + appendNameKey).intern());
}
}
/**
* Extends Recurrence with inclusive year limits.
*/
private static final class Rule {
final Recurrence iRecurrence;
final int iFromYear; // inclusive
final int iToYear; // inclusive
Rule(Recurrence recurrence, int fromYear, int toYear) {
iRecurrence = recurrence;
iFromYear = fromYear;
iToYear = toYear;
}
@SuppressWarnings("unused")
public int getFromYear() {
return iFromYear;
}
public int getToYear() {
return iToYear;
}
@SuppressWarnings("unused")
public OfYear getOfYear() {
return iRecurrence.getOfYear();
}
public String getNameKey() {
return iRecurrence.getNameKey();
}
public int getSaveMillis() {
return iRecurrence.getSaveMillis();
}
public long next(final long instant, int standardOffset, int saveMillis) {
Chronology chrono = ISOChronology.getInstanceUTC();
final int wallOffset = standardOffset + saveMillis;
long testInstant = instant;
int year;
if (instant == Long.MIN_VALUE) {
year = Integer.MIN_VALUE;
} else {
year = chrono.year().get(instant + wallOffset);
}
if (year < iFromYear) {
// First advance instant to start of from year.
testInstant = chrono.year().set(0, iFromYear) - wallOffset;
// Back off one millisecond to account for next recurrence
// being exactly at the beginning of the year.
testInstant -= 1;
}
long next = iRecurrence.next(testInstant, standardOffset, saveMillis);
if (next > instant) {
year = chrono.year().get(next + wallOffset);
if (year > iToYear) {
// Out of range, return original value.
next = instant;
}
}
return next;
}
}
private static final class Transition {
private final long iMillis;
private final String iNameKey;
private final int iWallOffset;
private final int iStandardOffset;
Transition(long millis, Transition tr) {
iMillis = millis;
iNameKey = tr.iNameKey;
iWallOffset = tr.iWallOffset;
iStandardOffset = tr.iStandardOffset;
}
Transition(long millis, Rule rule, int standardOffset) {
iMillis = millis;
iNameKey = rule.getNameKey();
iWallOffset = standardOffset + rule.getSaveMillis();
iStandardOffset = standardOffset;
}
Transition(long millis, String nameKey,
int wallOffset, int standardOffset) {
iMillis = millis;
iNameKey = nameKey;
iWallOffset = wallOffset;
iStandardOffset = standardOffset;
}
public long getMillis() {
return iMillis;
}
public String getNameKey() {
return iNameKey;
}
public int getWallOffset() {
return iWallOffset;
}
public int getStandardOffset() {
return iStandardOffset;
}
public int getSaveMillis() {
return iWallOffset - iStandardOffset;
}
/**
* There must be a change in the millis, wall offsets or name keys.
*/
public boolean isTransitionFrom(Transition other) {
if (other == null) {
return true;
}
return iMillis > other.iMillis &&
(iWallOffset != other.iWallOffset ||
//iStandardOffset != other.iStandardOffset ||
!(iNameKey.equals(other.iNameKey)));
}
}
private static final class RuleSet {
private static final int YEAR_LIMIT;
static {
// Don't pre-calculate more than 100 years into the future. Almost
// all zones will stop pre-calculating far sooner anyhow. Either a
// simple DST cycle is detected or the last rule is a fixed
// offset. If a zone has a fixed offset set more than 100 years
// into the future, then it won't be observed.
long now = DateTimeUtils.currentTimeMillis();
YEAR_LIMIT = ISOChronology.getInstanceUTC().year().get(now) + 100;
}
private int iStandardOffset;
private ArrayList<Rule> iRules;
// Optional.
private String iInitialNameKey;
private int iInitialSaveMillis;
// Upper limit is exclusive.
private int iUpperYear;
private OfYear iUpperOfYear;
RuleSet() {
iRules = new ArrayList<Rule>(10);
iUpperYear = Integer.MAX_VALUE;
}
/**
* Copy constructor.
*/
RuleSet(RuleSet rs) {
iStandardOffset = rs.iStandardOffset;
iRules = new ArrayList<Rule>(rs.iRules);
iInitialNameKey = rs.iInitialNameKey;
iInitialSaveMillis = rs.iInitialSaveMillis;
iUpperYear = rs.iUpperYear;
iUpperOfYear = rs.iUpperOfYear;
}
@SuppressWarnings("unused")
public int getStandardOffset() {
return iStandardOffset;
}
public void setStandardOffset(int standardOffset) {
iStandardOffset = standardOffset;
}
public void setFixedSavings(String nameKey, int saveMillis) {
iInitialNameKey = nameKey;
iInitialSaveMillis = saveMillis;
}
public void addRule(Rule rule) {
if (!iRules.contains(rule)) {
iRules.add(rule);
}
}
public void setUpperLimit(int year, OfYear ofYear) {
iUpperYear = year;
iUpperOfYear = ofYear;
}
/**
* Returns a transition at firstMillis with the first name key and
* offsets for this rule set. This method may return null.
*
* @param firstMillis millis of first transition
*/
public Transition firstTransition(final long firstMillis) {
if (iInitialNameKey != null) {
// Initial zone info explicitly set, so don't search the rules.
return new Transition(firstMillis, iInitialNameKey,
iStandardOffset + iInitialSaveMillis, iStandardOffset);
}
// Make a copy before we destroy the rules.
ArrayList<Rule> copy = new ArrayList<Rule>(iRules);
// Iterate through all the transitions until firstMillis is
// reached. Use the name key and savings for whatever rule reaches
// the limit.
long millis = Long.MIN_VALUE;
int saveMillis = 0;
Transition first = null;
Transition next;
while ((next = nextTransition(millis, saveMillis)) != null) {
millis = next.getMillis();
if (millis == firstMillis) {
first = new Transition(firstMillis, next);
break;
}
if (millis > firstMillis) {
if (first == null) {
// Find first rule without savings. This way a more
// accurate nameKey is found even though no rule
// extends to the RuleSet's lower limit.
for (Rule rule : copy) {
if (rule.getSaveMillis() == 0) {
first = new Transition(firstMillis, rule, iStandardOffset);
break;
}
}
}
if (first == null) {
// Found no rule without savings. Create a transition
// with no savings anyhow, and use the best available
// name key.
first = new Transition(firstMillis, next.getNameKey(),
iStandardOffset, iStandardOffset);
}
break;
}
// Set first to the best transition found so far, but next
// iteration may find something closer to lower limit.
first = new Transition(firstMillis, next);
saveMillis = next.getSaveMillis();
}
iRules = copy;
return first;
}
/**
* Returns null if RuleSet is exhausted or upper limit reached. Calling
* this method will throw away rules as they each become
* exhausted. Copy the RuleSet before using it to compute transitions.
*
* Returned transition may be a duplicate from previous
* transition. Caller must call isTransitionFrom to filter out
* duplicates.
*
* @param saveMillis savings before next transition
*/
public Transition nextTransition(final long instant, final int saveMillis) {
Chronology chrono = ISOChronology.getInstanceUTC();
// Find next matching rule.
Rule nextRule = null;
long nextMillis = Long.MAX_VALUE;
Iterator<Rule> it = iRules.iterator();
while (it.hasNext()) {
Rule rule = it.next();
long next = rule.next(instant, iStandardOffset, saveMillis);
if (next <= instant) {
it.remove();
continue;
}
// Even if next is same as previous next, choose the rule
// in order for more recently added rules to override.
if (next <= nextMillis) {
// Found a better match.
nextRule = rule;
nextMillis = next;
}
}
if (nextRule == null) {
return null;
}
// Stop precalculating if year reaches some arbitrary limit.
if (chrono.year().get(nextMillis) >= YEAR_LIMIT) {
return null;
}
// Check if upper limit reached or passed.
if (iUpperYear < Integer.MAX_VALUE) {
long upperMillis =
iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis);
if (nextMillis >= upperMillis) {
// At or after upper limit.
return null;
}
}
return new Transition(nextMillis, nextRule, iStandardOffset);
}
/**
* @param saveMillis savings before upper limit
*/
public long getUpperLimit(int saveMillis) {
if (iUpperYear == Integer.MAX_VALUE) {
return Long.MAX_VALUE;
}
return iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis);
}
/**
* Returns null if none can be built.
*/
public DSTZone buildTailZone(String id) {
if (iRules.size() == 2) {
Rule startRule = iRules.get(0);
Rule endRule = iRules.get(1);
if (startRule.getToYear() == Integer.MAX_VALUE &&
endRule.getToYear() == Integer.MAX_VALUE) {
// With exactly two infinitely recurring rules left, a
// simple DSTZone can be formed.
// The order of rules can come in any order, and it doesn't
// really matter which rule was chosen the 'start' and
// which is chosen the 'end'. DSTZone works properly either
// way.
return new DSTZone(id, iStandardOffset,
startRule.iRecurrence, endRule.iRecurrence);
}
}
return null;
}
}
private static final class DSTZone extends DateTimeZone {
private static final long serialVersionUID = 6941492635554961361L;
static DSTZone readFrom(DataInput in, String id) throws IOException {
return new DSTZone(id, (int)readMillis(in),
Recurrence.readFrom(in), Recurrence.readFrom(in));
}
final int iStandardOffset;
final Recurrence iStartRecurrence;
final Recurrence iEndRecurrence;
DSTZone(String id, int standardOffset,
Recurrence startRecurrence, Recurrence endRecurrence) {
super(id);
iStandardOffset = standardOffset;
iStartRecurrence = startRecurrence;
iEndRecurrence = endRecurrence;
}
public String getNameKey(long instant) {
return findMatchingRecurrence(instant).getNameKey();
}
public int getOffset(long instant) {
return iStandardOffset + findMatchingRecurrence(instant).getSaveMillis();
}
public int getStandardOffset(long instant) {
return iStandardOffset;
}
public boolean isFixed() {
return false;
}
public long nextTransition(long instant) {
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.next
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant > 0 && start < 0) {
// Overflowed.
start = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.next
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant > 0 && end < 0) {
// Overflowed.
end = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return (start > end) ? end : start;
}
public long previousTransition(long instant) {
// Increment in order to handle the case where instant is exactly at
// a transition.
instant++;
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.previous
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant < 0 && start > 0) {
// Overflowed.
start = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.previous
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant < 0 && end > 0) {
// Overflowed.
end = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return ((start > end) ? start : end) - 1;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DSTZone) {
DSTZone other = (DSTZone)obj;
return
getID().equals(other.getID()) &&
iStandardOffset == other.iStandardOffset &&
iStartRecurrence.equals(other.iStartRecurrence) &&
iEndRecurrence.equals(other.iEndRecurrence);
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
writeMillis(out, iStandardOffset);
iStartRecurrence.writeTo(out);
iEndRecurrence.writeTo(out);
}
private Recurrence findMatchingRecurrence(long instant) {
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.next
(instant, standardOffset, endRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.next
(instant, standardOffset, startRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return (start > end) ? startRecurrence : endRecurrence;
}
}
private static final class PrecalculatedZone extends DateTimeZone {
private static final long serialVersionUID = 7811976468055766265L;
static PrecalculatedZone readFrom(DataInput in, String id) throws IOException {
// Read string pool.
int poolSize = in.readUnsignedShort();
String[] pool = new String[poolSize];
for (int i=0; i<poolSize; i++) {
pool[i] = in.readUTF();
}
int size = in.readInt();
long[] transitions = new long[size];
int[] wallOffsets = new int[size];
int[] standardOffsets = new int[size];
String[] nameKeys = new String[size];
for (int i=0; i<size; i++) {
transitions[i] = readMillis(in);
wallOffsets[i] = (int)readMillis(in);
standardOffsets[i] = (int)readMillis(in);
try {
int index;
if (poolSize < 256) {
index = in.readUnsignedByte();
} else {
index = in.readUnsignedShort();
}
nameKeys[i] = pool[index];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Invalid encoding");
}
}
DSTZone tailZone = null;
if (in.readBoolean()) {
tailZone = DSTZone.readFrom(in, id);
}
return new PrecalculatedZone
(id, transitions, wallOffsets, standardOffsets, nameKeys, tailZone);
}
/**
* Factory to create instance from builder.
*
* @param id the zone id
* @param outputID true if the zone id should be output
* @param transitions the list of Transition objects
* @param tailZone optional zone for getting info beyond precalculated tables
*/
static PrecalculatedZone create(String id, boolean outputID, ArrayList<Transition> transitions,
DSTZone tailZone) {
int size = transitions.size();
if (size == 0) {
throw new IllegalArgumentException();
}
long[] trans = new long[size];
int[] wallOffsets = new int[size];
int[] standardOffsets = new int[size];
String[] nameKeys = new String[size];
Transition last = null;
for (int i=0; i<size; i++) {
Transition tr = transitions.get(i);
if (!tr.isTransitionFrom(last)) {
throw new IllegalArgumentException(id);
}
trans[i] = tr.getMillis();
wallOffsets[i] = tr.getWallOffset();
standardOffsets[i] = tr.getStandardOffset();
nameKeys[i] = tr.getNameKey();
last = tr;
}
// Some timezones (Australia) have the same name key for
// summer and winter which messes everything up. Fix it here.
String[] zoneNameData = new String[5];
String[][] zoneStrings = new DateFormatSymbols(Locale.ENGLISH).getZoneStrings();
for (int j = 0; j < zoneStrings.length; j++) {
String[] set = zoneStrings[j];
if (set != null && set.length == 5 && id.equals(set[0])) {
zoneNameData = set;
}
}
Chronology chrono = ISOChronology.getInstanceUTC();
for (int i = 0; i < nameKeys.length - 1; i++) {
String curNameKey = nameKeys[i];
String nextNameKey = nameKeys[i + 1];
long curOffset = wallOffsets[i];
long nextOffset = wallOffsets[i + 1];
long curStdOffset = standardOffsets[i];
long nextStdOffset = standardOffsets[i + 1];
Period p = new Period(trans[i], trans[i + 1], PeriodType.yearMonthDay(), chrono);
if (curOffset != nextOffset &&
curStdOffset == nextStdOffset &&
curNameKey.equals(nextNameKey) &&
p.getYears() == 0 && p.getMonths() > 4 && p.getMonths() < 8 &&
curNameKey.equals(zoneNameData[2]) &&
curNameKey.equals(zoneNameData[4])) {
if (ZoneInfoLogger.verbose()) {
System.out.println("Fixing duplicate name key - " + nextNameKey);
System.out.println(" - " + new DateTime(trans[i], chrono) +
" - " + new DateTime(trans[i + 1], chrono));
}
if (curOffset > nextOffset) {
nameKeys[i] = (curNameKey + "-Summer").intern();
} else if (curOffset < nextOffset) {
nameKeys[i + 1] = (nextNameKey + "-Summer").intern();
i++;
}
}
}
if (tailZone != null) {
if (tailZone.iStartRecurrence.getNameKey()
.equals(tailZone.iEndRecurrence.getNameKey())) {
if (ZoneInfoLogger.verbose()) {
System.out.println("Fixing duplicate recurrent name key - " +
tailZone.iStartRecurrence.getNameKey());
}
if (tailZone.iStartRecurrence.getSaveMillis() > 0) {
tailZone = new DSTZone(
tailZone.getID(),
tailZone.iStandardOffset,
tailZone.iStartRecurrence.renameAppend("-Summer"),
tailZone.iEndRecurrence);
} else {
tailZone = new DSTZone(
tailZone.getID(),
tailZone.iStandardOffset,
tailZone.iStartRecurrence,
tailZone.iEndRecurrence.renameAppend("-Summer"));
}
}
}
return new PrecalculatedZone
((outputID ? id : ""), trans, wallOffsets, standardOffsets, nameKeys, tailZone);
}
// All array fields have the same length.
private final long[] iTransitions;
private final int[] iWallOffsets;
private final int[] iStandardOffsets;
private final String[] iNameKeys;
private final DSTZone iTailZone;
/**
* Constructor used ONLY for valid input, loaded via static methods.
*/
private PrecalculatedZone(String id, long[] transitions, int[] wallOffsets,
int[] standardOffsets, String[] nameKeys, DSTZone tailZone)
{
super(id);
iTransitions = transitions;
iWallOffsets = wallOffsets;
iStandardOffsets = standardOffsets;
iNameKeys = nameKeys;
iTailZone = tailZone;
}
public String getNameKey(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iNameKeys[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iNameKeys[i - 1];
}
return "UTC";
}
if (iTailZone == null) {
return iNameKeys[i - 1];
}
return iTailZone.getNameKey(instant);
}
public int getOffset(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iWallOffsets[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iWallOffsets[i - 1];
}
return 0;
}
if (iTailZone == null) {
return iWallOffsets[i - 1];
}
return iTailZone.getOffset(instant);
}
public int getStandardOffset(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iStandardOffsets[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iStandardOffsets[i - 1];
}
return 0;
}
if (iTailZone == null) {
return iStandardOffsets[i - 1];
}
return iTailZone.getStandardOffset(instant);
}
public boolean isFixed() {
return false;
}
public long nextTransition(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
i = (i >= 0) ? (i + 1) : ~i;
if (i < transitions.length) {
return transitions[i];
}
if (iTailZone == null) {
return instant;
}
long end = transitions[transitions.length - 1];
if (instant < end) {
instant = end;
}
return iTailZone.nextTransition(instant);
}
public long previousTransition(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
if (instant > Long.MIN_VALUE) {
return instant - 1;
}
return instant;
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
long prev = transitions[i - 1];
if (prev > Long.MIN_VALUE) {
return prev - 1;
}
}
return instant;
}
if (iTailZone != null) {
long prev = iTailZone.previousTransition(instant);
if (prev < instant) {
return prev;
}
}
long prev = transitions[i - 1];
if (prev > Long.MIN_VALUE) {
return prev - 1;
}
return instant;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof PrecalculatedZone) {
PrecalculatedZone other = (PrecalculatedZone)obj;
return
getID().equals(other.getID()) &&
Arrays.equals(iTransitions, other.iTransitions) &&
Arrays.equals(iNameKeys, other.iNameKeys) &&
Arrays.equals(iWallOffsets, other.iWallOffsets) &&
Arrays.equals(iStandardOffsets, other.iStandardOffsets) &&
((iTailZone == null)
? (null == other.iTailZone)
: (iTailZone.equals(other.iTailZone)));
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
int size = iTransitions.length;
// Create unique string pool.
Set<String> poolSet = new HashSet<String>();
for (int i=0; i<size; i++) {
poolSet.add(iNameKeys[i]);
}
int poolSize = poolSet.size();
if (poolSize > 65535) {
throw new UnsupportedOperationException("String pool is too large");
}
String[] pool = new String[poolSize];
Iterator<String> it = poolSet.iterator();
for (int i=0; it.hasNext(); i++) {
pool[i] = it.next();
}
// Write out the pool.
out.writeShort(poolSize);
for (int i=0; i<poolSize; i++) {
out.writeUTF(pool[i]);
}
out.writeInt(size);
for (int i=0; i<size; i++) {
writeMillis(out, iTransitions[i]);
writeMillis(out, iWallOffsets[i]);
writeMillis(out, iStandardOffsets[i]);
// Find pool index and write it out.
String nameKey = iNameKeys[i];
for (int j=0; j<poolSize; j++) {
if (pool[j].equals(nameKey)) {
if (poolSize < 256) {
out.writeByte(j);
} else {
out.writeShort(j);
}
break;
}
}
}
out.writeBoolean(iTailZone != null);
if (iTailZone != null) {
iTailZone.writeTo(out);
}
}
public boolean isCachable() {
if (iTailZone != null) {
return true;
}
long[] transitions = iTransitions;
if (transitions.length <= 1) {
return false;
}
// Add up all the distances between transitions that are less than
// about two years.
double distances = 0;
int count = 0;
for (int i=1; i<transitions.length; i++) {
long diff = transitions[i] - transitions[i - 1];
if (diff < ((366L + 365) * 24 * 60 * 60 * 1000)) {
distances += (double)diff;
count++;
}
}
if (count > 0) {
double avg = distances / count;
avg /= 24 * 60 * 60 * 1000;
if (avg >= 25) {
// Only bother caching if average distance between
// transitions is at least 25 days. Why 25?
// CachedDateTimeZone is more efficient if the distance
// between transitions is large. With an average of 25, it
// will on average perform about 2 tests per cache
// hit. (49.7 / 25) is approximately 2.
return true;
}
}
return false;
}
}
}
|
src/main/java/org/joda/time/tz/DateTimeZoneBuilder.java
|
/*
* Copyright 2001-2013 Stephen Colebourne
*
* 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.joda.time.tz;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.chrono.ISOChronology;
/**
* DateTimeZoneBuilder allows complex DateTimeZones to be constructed. Since
* creating a new DateTimeZone this way is a relatively expensive operation,
* built zones can be written to a file. Reading back the encoded data is a
* quick operation.
* <p>
* DateTimeZoneBuilder itself is mutable and not thread-safe, but the
* DateTimeZone objects that it builds are thread-safe and immutable.
* <p>
* It is intended that {@link ZoneInfoCompiler} be used to read time zone data
* files, indirectly calling DateTimeZoneBuilder. The following complex
* example defines the America/Los_Angeles time zone, with all historical
* transitions:
*
* <pre>
* DateTimeZone America_Los_Angeles = new DateTimeZoneBuilder()
* .addCutover(-2147483648, 'w', 1, 1, 0, false, 0)
* .setStandardOffset(-28378000)
* .setFixedSavings("LMT", 0)
* .addCutover(1883, 'w', 11, 18, 0, false, 43200000)
* .setStandardOffset(-28800000)
* .addRecurringSavings("PDT", 3600000, 1918, 1919, 'w', 3, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1918, 1919, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PWT", 3600000, 1942, 1942, 'w', 2, 9, 0, false, 7200000)
* .addRecurringSavings("PPT", 3600000, 1945, 1945, 'u', 8, 14, 0, false, 82800000)
* .addRecurringSavings("PST", 0, 1945, 1945, 'w', 9, 30, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1948, 1948, 'w', 3, 14, 0, false, 7200000)
* .addRecurringSavings("PST", 0, 1949, 1949, 'w', 1, 1, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1950, 1966, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1950, 1961, 'w', 9, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1962, 1966, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PST", 0, 1967, 2147483647, 'w', 10, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1967, 1973, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1974, 1974, 'w', 1, 6, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1975, 1975, 'w', 2, 23, 0, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1976, 1986, 'w', 4, -1, 7, false, 7200000)
* .addRecurringSavings("PDT", 3600000, 1987, 2147483647, 'w', 4, 1, 7, true, 7200000)
* .toDateTimeZone("America/Los_Angeles", true);
* </pre>
*
* @author Brian S O'Neill
* @see ZoneInfoCompiler
* @see ZoneInfoProvider
* @since 1.0
*/
public class DateTimeZoneBuilder {
/**
* Decodes a built DateTimeZone from the given stream, as encoded by
* writeTo.
*
* @param in input stream to read encoded DateTimeZone from.
* @param id time zone id to assign
*/
public static DateTimeZone readFrom(InputStream in, String id) throws IOException {
if (in instanceof DataInput) {
return readFrom((DataInput)in, id);
} else {
return readFrom((DataInput)new DataInputStream(in), id);
}
}
/**
* Decodes a built DateTimeZone from the given stream, as encoded by
* writeTo.
*
* @param in input stream to read encoded DateTimeZone from.
* @param id time zone id to assign
*/
public static DateTimeZone readFrom(DataInput in, String id) throws IOException {
switch (in.readUnsignedByte()) {
case 'F':
DateTimeZone fixed = new FixedDateTimeZone
(id, in.readUTF(), (int)readMillis(in), (int)readMillis(in));
if (fixed.equals(DateTimeZone.UTC)) {
fixed = DateTimeZone.UTC;
}
return fixed;
case 'C':
return CachedDateTimeZone.forZone(PrecalculatedZone.readFrom(in, id));
case 'P':
return PrecalculatedZone.readFrom(in, id);
default:
throw new IOException("Invalid encoding");
}
}
/**
* Millisecond encoding formats:
*
* upper two bits units field length approximate range
* ---------------------------------------------------------------
* 00 30 minutes 1 byte +/- 16 hours
* 01 minutes 4 bytes +/- 1020 years
* 10 seconds 5 bytes +/- 4355 years
* 11 millis 9 bytes +/- 292,000,000 years
*
* Remaining bits in field form signed offset from 1970-01-01T00:00:00Z.
*/
static void writeMillis(DataOutput out, long millis) throws IOException {
if (millis % (30 * 60000L) == 0) {
// Try to write in 30 minute units.
long units = millis / (30 * 60000L);
if (((units << (64 - 6)) >> (64 - 6)) == units) {
// Form 00 (6 bits effective precision)
out.writeByte((int)(units & 0x3f));
return;
}
}
if (millis % 60000L == 0) {
// Try to write minutes.
long minutes = millis / 60000L;
if (((minutes << (64 - 30)) >> (64 - 30)) == minutes) {
// Form 01 (30 bits effective precision)
out.writeInt(0x40000000 | (int)(minutes & 0x3fffffff));
return;
}
}
if (millis % 1000L == 0) {
// Try to write seconds.
long seconds = millis / 1000L;
if (((seconds << (64 - 38)) >> (64 - 38)) == seconds) {
// Form 10 (38 bits effective precision)
out.writeByte(0x80 | (int)((seconds >> 32) & 0x3f));
out.writeInt((int)(seconds & 0xffffffff));
return;
}
}
// Write milliseconds either because the additional precision is
// required or the minutes didn't fit in the field.
// Form 11 (64-bits effective precision, but write as if 70 bits)
out.writeByte(millis < 0 ? 0xff : 0xc0);
out.writeLong(millis);
}
/**
* Reads encoding generated by writeMillis.
*/
static long readMillis(DataInput in) throws IOException {
int v = in.readUnsignedByte();
switch (v >> 6) {
case 0: default:
// Form 00 (6 bits effective precision)
v = (v << (32 - 6)) >> (32 - 6);
return v * (30 * 60000L);
case 1:
// Form 01 (30 bits effective precision)
v = (v << (32 - 6)) >> (32 - 30);
v |= (in.readUnsignedByte()) << 16;
v |= (in.readUnsignedByte()) << 8;
v |= (in.readUnsignedByte());
return v * 60000L;
case 2:
// Form 10 (38 bits effective precision)
long w = (((long)v) << (64 - 6)) >> (64 - 38);
w |= (in.readUnsignedByte()) << 24;
w |= (in.readUnsignedByte()) << 16;
w |= (in.readUnsignedByte()) << 8;
w |= (in.readUnsignedByte());
return w * 1000L;
case 3:
// Form 11 (64-bits effective precision)
return in.readLong();
}
}
private static DateTimeZone buildFixedZone(String id, String nameKey,
int wallOffset, int standardOffset) {
if ("UTC".equals(id) && id.equals(nameKey) &&
wallOffset == 0 && standardOffset == 0) {
return DateTimeZone.UTC;
}
return new FixedDateTimeZone(id, nameKey, wallOffset, standardOffset);
}
// List of RuleSets.
private final ArrayList<RuleSet> iRuleSets;
public DateTimeZoneBuilder() {
iRuleSets = new ArrayList<RuleSet>(10);
}
/**
* Adds a cutover for added rules. The standard offset at the cutover
* defaults to 0. Call setStandardOffset afterwards to change it.
*
* @param year the year of cutover
* @param mode 'u' - cutover is measured against UTC, 'w' - against wall
* offset, 's' - against standard offset
* @param monthOfYear the month from 1 (January) to 12 (December)
* @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth).
* For example, if -1, set to last day of month
* @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore
* @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to
* dayOfWeek when true, retreat when false.
* @param millisOfDay additional precision for specifying time of day of cutover
*/
public DateTimeZoneBuilder addCutover(int year,
char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek,
boolean advanceDayOfWeek,
int millisOfDay)
{
if (iRuleSets.size() > 0) {
OfYear ofYear = new OfYear
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
RuleSet lastRuleSet = iRuleSets.get(iRuleSets.size() - 1);
lastRuleSet.setUpperLimit(year, ofYear);
}
iRuleSets.add(new RuleSet());
return this;
}
/**
* Sets the standard offset to use for newly added rules until the next
* cutover is added.
* @param standardOffset the standard offset in millis
*/
public DateTimeZoneBuilder setStandardOffset(int standardOffset) {
getLastRuleSet().setStandardOffset(standardOffset);
return this;
}
/**
* Set a fixed savings rule at the cutover.
*/
public DateTimeZoneBuilder setFixedSavings(String nameKey, int saveMillis) {
getLastRuleSet().setFixedSavings(nameKey, saveMillis);
return this;
}
/**
* Add a recurring daylight saving time rule.
*
* @param nameKey the name key of new rule
* @param saveMillis the milliseconds to add to standard offset
* @param fromYear the first year that rule is in effect, MIN_VALUE indicates
* beginning of time
* @param toYear the last year (inclusive) that rule is in effect, MAX_VALUE
* indicates end of time
* @param mode 'u' - transitions are calculated against UTC, 'w' -
* transitions are calculated against wall offset, 's' - transitions are
* calculated against standard offset
* @param monthOfYear the month from 1 (January) to 12 (December)
* @param dayOfMonth if negative, set to ((last day of month) - ~dayOfMonth).
* For example, if -1, set to last day of month
* @param dayOfWeek from 1 (Monday) to 7 (Sunday), if 0 then ignore
* @param advanceDayOfWeek if dayOfMonth does not fall on dayOfWeek, advance to
* dayOfWeek when true, retreat when false.
* @param millisOfDay additional precision for specifying time of day of transitions
*/
public DateTimeZoneBuilder addRecurringSavings(String nameKey, int saveMillis,
int fromYear, int toYear,
char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek,
boolean advanceDayOfWeek,
int millisOfDay)
{
if (fromYear <= toYear) {
OfYear ofYear = new OfYear
(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, millisOfDay);
Recurrence recurrence = new Recurrence(ofYear, nameKey, saveMillis);
Rule rule = new Rule(recurrence, fromYear, toYear);
getLastRuleSet().addRule(rule);
}
return this;
}
private RuleSet getLastRuleSet() {
if (iRuleSets.size() == 0) {
addCutover(Integer.MIN_VALUE, 'w', 1, 1, 0, false, 0);
}
return iRuleSets.get(iRuleSets.size() - 1);
}
/**
* Processes all the rules and builds a DateTimeZone.
*
* @param id time zone id to assign
* @param outputID true if the zone id should be output
*/
public DateTimeZone toDateTimeZone(String id, boolean outputID) {
if (id == null) {
throw new IllegalArgumentException();
}
// Discover where all the transitions occur and store the results in
// these lists.
ArrayList<Transition> transitions = new ArrayList<Transition>();
// Tail zone picks up remaining transitions in the form of an endless
// DST cycle.
DSTZone tailZone = null;
long millis = Long.MIN_VALUE;
int saveMillis = 0;
int ruleSetCount = iRuleSets.size();
for (int i=0; i<ruleSetCount; i++) {
RuleSet rs = iRuleSets.get(i);
Transition next = rs.firstTransition(millis);
if (next == null) {
continue;
}
addTransition(transitions, next);
millis = next.getMillis();
saveMillis = next.getSaveMillis();
// Copy it since we're going to destroy it.
rs = new RuleSet(rs);
while ((next = rs.nextTransition(millis, saveMillis)) != null) {
if (addTransition(transitions, next) && tailZone != null) {
// Got the extra transition before DSTZone.
break;
}
millis = next.getMillis();
saveMillis = next.getSaveMillis();
if (tailZone == null && i == ruleSetCount - 1) {
tailZone = rs.buildTailZone(id);
// If tailZone is not null, don't break out of main loop until
// at least one more transition is calculated. This ensures a
// correct 'seam' to the DSTZone.
}
}
millis = rs.getUpperLimit(saveMillis);
}
// Check if a simpler zone implementation can be returned.
if (transitions.size() == 0) {
if (tailZone != null) {
// This shouldn't happen, but handle just in case.
return tailZone;
}
return buildFixedZone(id, "UTC", 0, 0);
}
if (transitions.size() == 1 && tailZone == null) {
Transition tr = transitions.get(0);
return buildFixedZone(id, tr.getNameKey(),
tr.getWallOffset(), tr.getStandardOffset());
}
PrecalculatedZone zone = PrecalculatedZone.create(id, outputID, transitions, tailZone);
if (zone.isCachable()) {
return CachedDateTimeZone.forZone(zone);
}
return zone;
}
private boolean addTransition(ArrayList<Transition> transitions, Transition tr) {
int size = transitions.size();
if (size == 0) {
transitions.add(tr);
return true;
}
Transition last = transitions.get(size - 1);
if (!tr.isTransitionFrom(last)) {
return false;
}
// If local time of new transition is same as last local time, just
// replace last transition with new one.
int offsetForLast = 0;
if (size >= 2) {
offsetForLast = transitions.get(size - 2).getWallOffset();
}
int offsetForNew = last.getWallOffset();
long lastLocal = last.getMillis() + offsetForLast;
long newLocal = tr.getMillis() + offsetForNew;
if (newLocal != lastLocal) {
transitions.add(tr);
return true;
}
transitions.remove(size - 1);
return addTransition(transitions, tr);
}
/**
* Encodes a built DateTimeZone to the given stream. Call readFrom to
* decode the data into a DateTimeZone object.
*
* @param out the output stream to receive the encoded DateTimeZone
* @since 1.5 (parameter added)
*/
public void writeTo(String zoneID, OutputStream out) throws IOException {
if (out instanceof DataOutput) {
writeTo(zoneID, (DataOutput)out);
} else {
writeTo(zoneID, (DataOutput)new DataOutputStream(out));
}
}
/**
* Encodes a built DateTimeZone to the given stream. Call readFrom to
* decode the data into a DateTimeZone object.
*
* @param out the output stream to receive the encoded DateTimeZone
* @since 1.5 (parameter added)
*/
public void writeTo(String zoneID, DataOutput out) throws IOException {
// pass false so zone id is not written out
DateTimeZone zone = toDateTimeZone(zoneID, false);
if (zone instanceof FixedDateTimeZone) {
out.writeByte('F'); // 'F' for fixed
out.writeUTF(zone.getNameKey(0));
writeMillis(out, zone.getOffset(0));
writeMillis(out, zone.getStandardOffset(0));
} else {
if (zone instanceof CachedDateTimeZone) {
out.writeByte('C'); // 'C' for cached, precalculated
zone = ((CachedDateTimeZone)zone).getUncachedZone();
} else {
out.writeByte('P'); // 'P' for precalculated, uncached
}
((PrecalculatedZone)zone).writeTo(out);
}
}
/**
* Supports setting fields of year and moving between transitions.
*/
private static final class OfYear {
static OfYear readFrom(DataInput in) throws IOException {
return new OfYear((char)in.readUnsignedByte(),
(int)in.readUnsignedByte(),
(int)in.readByte(),
(int)in.readUnsignedByte(),
in.readBoolean(),
(int)readMillis(in));
}
// Is 'u', 'w', or 's'.
final char iMode;
final int iMonthOfYear;
final int iDayOfMonth;
final int iDayOfWeek;
final boolean iAdvance;
final int iMillisOfDay;
OfYear(char mode,
int monthOfYear,
int dayOfMonth,
int dayOfWeek, boolean advanceDayOfWeek,
int millisOfDay)
{
if (mode != 'u' && mode != 'w' && mode != 's') {
throw new IllegalArgumentException("Unknown mode: " + mode);
}
iMode = mode;
iMonthOfYear = monthOfYear;
iDayOfMonth = dayOfMonth;
iDayOfWeek = dayOfWeek;
iAdvance = advanceDayOfWeek;
iMillisOfDay = millisOfDay;
}
/**
* @param standardOffset standard offset just before instant
*/
public long setInstant(int year, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
Chronology chrono = ISOChronology.getInstanceUTC();
long millis = chrono.year().set(0, year);
millis = chrono.monthOfYear().set(millis, iMonthOfYear);
millis = chrono.millisOfDay().set(millis, iMillisOfDay);
millis = setDayOfMonth(chrono, millis);
if (iDayOfWeek != 0) {
millis = setDayOfWeek(chrono, millis);
}
// Convert from local time to UTC.
return millis - offset;
}
/**
* @param standardOffset standard offset just before next recurrence
*/
public long next(long instant, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
// Convert from UTC to local time.
instant += offset;
Chronology chrono = ISOChronology.getInstanceUTC();
long next = chrono.monthOfYear().set(instant, iMonthOfYear);
// Be lenient with millisOfDay.
next = chrono.millisOfDay().set(next, 0);
next = chrono.millisOfDay().add(next, iMillisOfDay);
next = setDayOfMonthNext(chrono, next);
if (iDayOfWeek == 0) {
if (next <= instant) {
next = chrono.year().add(next, 1);
next = setDayOfMonthNext(chrono, next);
}
} else {
next = setDayOfWeek(chrono, next);
if (next <= instant) {
next = chrono.year().add(next, 1);
next = chrono.monthOfYear().set(next, iMonthOfYear);
next = setDayOfMonthNext(chrono, next);
next = setDayOfWeek(chrono, next);
}
}
// Convert from local time to UTC.
return next - offset;
}
/**
* @param standardOffset standard offset just before previous recurrence
*/
public long previous(long instant, int standardOffset, int saveMillis) {
int offset;
if (iMode == 'w') {
offset = standardOffset + saveMillis;
} else if (iMode == 's') {
offset = standardOffset;
} else {
offset = 0;
}
// Convert from UTC to local time.
instant += offset;
Chronology chrono = ISOChronology.getInstanceUTC();
long prev = chrono.monthOfYear().set(instant, iMonthOfYear);
// Be lenient with millisOfDay.
prev = chrono.millisOfDay().set(prev, 0);
prev = chrono.millisOfDay().add(prev, iMillisOfDay);
prev = setDayOfMonthPrevious(chrono, prev);
if (iDayOfWeek == 0) {
if (prev >= instant) {
prev = chrono.year().add(prev, -1);
prev = setDayOfMonthPrevious(chrono, prev);
}
} else {
prev = setDayOfWeek(chrono, prev);
if (prev >= instant) {
prev = chrono.year().add(prev, -1);
prev = chrono.monthOfYear().set(prev, iMonthOfYear);
prev = setDayOfMonthPrevious(chrono, prev);
prev = setDayOfWeek(chrono, prev);
}
}
// Convert from local time to UTC.
return prev - offset;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof OfYear) {
OfYear other = (OfYear)obj;
return
iMode == other.iMode &&
iMonthOfYear == other.iMonthOfYear &&
iDayOfMonth == other.iDayOfMonth &&
iDayOfWeek == other.iDayOfWeek &&
iAdvance == other.iAdvance &&
iMillisOfDay == other.iMillisOfDay;
}
return false;
}
/*
public String toString() {
return
"[OfYear]\n" +
"Mode: " + iMode + '\n' +
"MonthOfYear: " + iMonthOfYear + '\n' +
"DayOfMonth: " + iDayOfMonth + '\n' +
"DayOfWeek: " + iDayOfWeek + '\n' +
"AdvanceDayOfWeek: " + iAdvance + '\n' +
"MillisOfDay: " + iMillisOfDay + '\n';
}
*/
public void writeTo(DataOutput out) throws IOException {
out.writeByte(iMode);
out.writeByte(iMonthOfYear);
out.writeByte(iDayOfMonth);
out.writeByte(iDayOfWeek);
out.writeBoolean(iAdvance);
writeMillis(out, iMillisOfDay);
}
/**
* If month-day is 02-29 and year isn't leap, advances to next leap year.
*/
private long setDayOfMonthNext(Chronology chrono, long next) {
try {
next = setDayOfMonth(chrono, next);
} catch (IllegalArgumentException e) {
if (iMonthOfYear == 2 && iDayOfMonth == 29) {
while (chrono.year().isLeap(next) == false) {
next = chrono.year().add(next, 1);
}
next = setDayOfMonth(chrono, next);
} else {
throw e;
}
}
return next;
}
/**
* If month-day is 02-29 and year isn't leap, retreats to previous leap year.
*/
private long setDayOfMonthPrevious(Chronology chrono, long prev) {
try {
prev = setDayOfMonth(chrono, prev);
} catch (IllegalArgumentException e) {
if (iMonthOfYear == 2 && iDayOfMonth == 29) {
while (chrono.year().isLeap(prev) == false) {
prev = chrono.year().add(prev, -1);
}
prev = setDayOfMonth(chrono, prev);
} else {
throw e;
}
}
return prev;
}
private long setDayOfMonth(Chronology chrono, long instant) {
if (iDayOfMonth >= 0) {
instant = chrono.dayOfMonth().set(instant, iDayOfMonth);
} else {
instant = chrono.dayOfMonth().set(instant, 1);
instant = chrono.monthOfYear().add(instant, 1);
instant = chrono.dayOfMonth().add(instant, iDayOfMonth);
}
return instant;
}
private long setDayOfWeek(Chronology chrono, long instant) {
int dayOfWeek = chrono.dayOfWeek().get(instant);
int daysToAdd = iDayOfWeek - dayOfWeek;
if (daysToAdd != 0) {
if (iAdvance) {
if (daysToAdd < 0) {
daysToAdd += 7;
}
} else {
if (daysToAdd > 0) {
daysToAdd -= 7;
}
}
instant = chrono.dayOfWeek().add(instant, daysToAdd);
}
return instant;
}
}
/**
* Extends OfYear with a nameKey and savings.
*/
private static final class Recurrence {
static Recurrence readFrom(DataInput in) throws IOException {
return new Recurrence(OfYear.readFrom(in), in.readUTF(), (int)readMillis(in));
}
final OfYear iOfYear;
final String iNameKey;
final int iSaveMillis;
Recurrence(OfYear ofYear, String nameKey, int saveMillis) {
iOfYear = ofYear;
iNameKey = nameKey;
iSaveMillis = saveMillis;
}
public OfYear getOfYear() {
return iOfYear;
}
/**
* @param standardOffset standard offset just before next recurrence
*/
public long next(long instant, int standardOffset, int saveMillis) {
return iOfYear.next(instant, standardOffset, saveMillis);
}
/**
* @param standardOffset standard offset just before previous recurrence
*/
public long previous(long instant, int standardOffset, int saveMillis) {
return iOfYear.previous(instant, standardOffset, saveMillis);
}
public String getNameKey() {
return iNameKey;
}
public int getSaveMillis() {
return iSaveMillis;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Recurrence) {
Recurrence other = (Recurrence)obj;
return
iSaveMillis == other.iSaveMillis &&
iNameKey.equals(other.iNameKey) &&
iOfYear.equals(other.iOfYear);
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
iOfYear.writeTo(out);
out.writeUTF(iNameKey);
writeMillis(out, iSaveMillis);
}
Recurrence rename(String nameKey) {
return new Recurrence(iOfYear, nameKey, iSaveMillis);
}
Recurrence renameAppend(String appendNameKey) {
return rename((iNameKey + appendNameKey).intern());
}
}
/**
* Extends Recurrence with inclusive year limits.
*/
private static final class Rule {
final Recurrence iRecurrence;
final int iFromYear; // inclusive
final int iToYear; // inclusive
Rule(Recurrence recurrence, int fromYear, int toYear) {
iRecurrence = recurrence;
iFromYear = fromYear;
iToYear = toYear;
}
@SuppressWarnings("unused")
public int getFromYear() {
return iFromYear;
}
public int getToYear() {
return iToYear;
}
@SuppressWarnings("unused")
public OfYear getOfYear() {
return iRecurrence.getOfYear();
}
public String getNameKey() {
return iRecurrence.getNameKey();
}
public int getSaveMillis() {
return iRecurrence.getSaveMillis();
}
public long next(final long instant, int standardOffset, int saveMillis) {
Chronology chrono = ISOChronology.getInstanceUTC();
final int wallOffset = standardOffset + saveMillis;
long testInstant = instant;
int year;
if (instant == Long.MIN_VALUE) {
year = Integer.MIN_VALUE;
} else {
year = chrono.year().get(instant + wallOffset);
}
if (year < iFromYear) {
// First advance instant to start of from year.
testInstant = chrono.year().set(0, iFromYear) - wallOffset;
// Back off one millisecond to account for next recurrence
// being exactly at the beginning of the year.
testInstant -= 1;
}
long next = iRecurrence.next(testInstant, standardOffset, saveMillis);
if (next > instant) {
year = chrono.year().get(next + wallOffset);
if (year > iToYear) {
// Out of range, return original value.
next = instant;
}
}
return next;
}
}
private static final class Transition {
private final long iMillis;
private final String iNameKey;
private final int iWallOffset;
private final int iStandardOffset;
Transition(long millis, Transition tr) {
iMillis = millis;
iNameKey = tr.iNameKey;
iWallOffset = tr.iWallOffset;
iStandardOffset = tr.iStandardOffset;
}
Transition(long millis, Rule rule, int standardOffset) {
iMillis = millis;
iNameKey = rule.getNameKey();
iWallOffset = standardOffset + rule.getSaveMillis();
iStandardOffset = standardOffset;
}
Transition(long millis, String nameKey,
int wallOffset, int standardOffset) {
iMillis = millis;
iNameKey = nameKey;
iWallOffset = wallOffset;
iStandardOffset = standardOffset;
}
public long getMillis() {
return iMillis;
}
public String getNameKey() {
return iNameKey;
}
public int getWallOffset() {
return iWallOffset;
}
public int getStandardOffset() {
return iStandardOffset;
}
public int getSaveMillis() {
return iWallOffset - iStandardOffset;
}
/**
* There must be a change in the millis, wall offsets or name keys.
*/
public boolean isTransitionFrom(Transition other) {
if (other == null) {
return true;
}
return iMillis > other.iMillis &&
(iWallOffset != other.iWallOffset ||
//iStandardOffset != other.iStandardOffset ||
!(iNameKey.equals(other.iNameKey)));
}
}
private static final class RuleSet {
private static final int YEAR_LIMIT;
static {
// Don't pre-calculate more than 100 years into the future. Almost
// all zones will stop pre-calculating far sooner anyhow. Either a
// simple DST cycle is detected or the last rule is a fixed
// offset. If a zone has a fixed offset set more than 100 years
// into the future, then it won't be observed.
long now = DateTimeUtils.currentTimeMillis();
YEAR_LIMIT = ISOChronology.getInstanceUTC().year().get(now) + 100;
}
private int iStandardOffset;
private ArrayList<Rule> iRules;
// Optional.
private String iInitialNameKey;
private int iInitialSaveMillis;
// Upper limit is exclusive.
private int iUpperYear;
private OfYear iUpperOfYear;
RuleSet() {
iRules = new ArrayList<Rule>(10);
iUpperYear = Integer.MAX_VALUE;
}
/**
* Copy constructor.
*/
RuleSet(RuleSet rs) {
iStandardOffset = rs.iStandardOffset;
iRules = new ArrayList<Rule>(rs.iRules);
iInitialNameKey = rs.iInitialNameKey;
iInitialSaveMillis = rs.iInitialSaveMillis;
iUpperYear = rs.iUpperYear;
iUpperOfYear = rs.iUpperOfYear;
}
@SuppressWarnings("unused")
public int getStandardOffset() {
return iStandardOffset;
}
public void setStandardOffset(int standardOffset) {
iStandardOffset = standardOffset;
}
public void setFixedSavings(String nameKey, int saveMillis) {
iInitialNameKey = nameKey;
iInitialSaveMillis = saveMillis;
}
public void addRule(Rule rule) {
if (!iRules.contains(rule)) {
iRules.add(rule);
}
}
public void setUpperLimit(int year, OfYear ofYear) {
iUpperYear = year;
iUpperOfYear = ofYear;
}
/**
* Returns a transition at firstMillis with the first name key and
* offsets for this rule set. This method may return null.
*
* @param firstMillis millis of first transition
*/
public Transition firstTransition(final long firstMillis) {
if (iInitialNameKey != null) {
// Initial zone info explicitly set, so don't search the rules.
return new Transition(firstMillis, iInitialNameKey,
iStandardOffset + iInitialSaveMillis, iStandardOffset);
}
// Make a copy before we destroy the rules.
ArrayList<Rule> copy = new ArrayList<Rule>(iRules);
// Iterate through all the transitions until firstMillis is
// reached. Use the name key and savings for whatever rule reaches
// the limit.
long millis = Long.MIN_VALUE;
int saveMillis = 0;
Transition first = null;
Transition next;
while ((next = nextTransition(millis, saveMillis)) != null) {
millis = next.getMillis();
if (millis == firstMillis) {
first = new Transition(firstMillis, next);
break;
}
if (millis > firstMillis) {
if (first == null) {
// Find first rule without savings. This way a more
// accurate nameKey is found even though no rule
// extends to the RuleSet's lower limit.
for (Rule rule : copy) {
if (rule.getSaveMillis() == 0) {
first = new Transition(firstMillis, rule, iStandardOffset);
break;
}
}
}
if (first == null) {
// Found no rule without savings. Create a transition
// with no savings anyhow, and use the best available
// name key.
first = new Transition(firstMillis, next.getNameKey(),
iStandardOffset, iStandardOffset);
}
break;
}
// Set first to the best transition found so far, but next
// iteration may find something closer to lower limit.
first = new Transition(firstMillis, next);
saveMillis = next.getSaveMillis();
}
iRules = copy;
return first;
}
/**
* Returns null if RuleSet is exhausted or upper limit reached. Calling
* this method will throw away rules as they each become
* exhausted. Copy the RuleSet before using it to compute transitions.
*
* Returned transition may be a duplicate from previous
* transition. Caller must call isTransitionFrom to filter out
* duplicates.
*
* @param saveMillis savings before next transition
*/
public Transition nextTransition(final long instant, final int saveMillis) {
Chronology chrono = ISOChronology.getInstanceUTC();
// Find next matching rule.
Rule nextRule = null;
long nextMillis = Long.MAX_VALUE;
Iterator<Rule> it = iRules.iterator();
while (it.hasNext()) {
Rule rule = it.next();
long next = rule.next(instant, iStandardOffset, saveMillis);
if (next <= instant) {
it.remove();
continue;
}
// Even if next is same as previous next, choose the rule
// in order for more recently added rules to override.
if (next <= nextMillis) {
// Found a better match.
nextRule = rule;
nextMillis = next;
}
}
if (nextRule == null) {
return null;
}
// Stop precalculating if year reaches some arbitrary limit.
if (chrono.year().get(nextMillis) >= YEAR_LIMIT) {
return null;
}
// Check if upper limit reached or passed.
if (iUpperYear < Integer.MAX_VALUE) {
long upperMillis =
iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis);
if (nextMillis >= upperMillis) {
// At or after upper limit.
return null;
}
}
return new Transition(nextMillis, nextRule, iStandardOffset);
}
/**
* @param saveMillis savings before upper limit
*/
public long getUpperLimit(int saveMillis) {
if (iUpperYear == Integer.MAX_VALUE) {
return Long.MAX_VALUE;
}
return iUpperOfYear.setInstant(iUpperYear, iStandardOffset, saveMillis);
}
/**
* Returns null if none can be built.
*/
public DSTZone buildTailZone(String id) {
if (iRules.size() == 2) {
Rule startRule = iRules.get(0);
Rule endRule = iRules.get(1);
if (startRule.getToYear() == Integer.MAX_VALUE &&
endRule.getToYear() == Integer.MAX_VALUE) {
// With exactly two infinitely recurring rules left, a
// simple DSTZone can be formed.
// The order of rules can come in any order, and it doesn't
// really matter which rule was chosen the 'start' and
// which is chosen the 'end'. DSTZone works properly either
// way.
return new DSTZone(id, iStandardOffset,
startRule.iRecurrence, endRule.iRecurrence);
}
}
return null;
}
}
private static final class DSTZone extends DateTimeZone {
private static final long serialVersionUID = 6941492635554961361L;
static DSTZone readFrom(DataInput in, String id) throws IOException {
return new DSTZone(id, (int)readMillis(in),
Recurrence.readFrom(in), Recurrence.readFrom(in));
}
final int iStandardOffset;
final Recurrence iStartRecurrence;
final Recurrence iEndRecurrence;
DSTZone(String id, int standardOffset,
Recurrence startRecurrence, Recurrence endRecurrence) {
super(id);
iStandardOffset = standardOffset;
iStartRecurrence = startRecurrence;
iEndRecurrence = endRecurrence;
}
public String getNameKey(long instant) {
return findMatchingRecurrence(instant).getNameKey();
}
public int getOffset(long instant) {
return iStandardOffset + findMatchingRecurrence(instant).getSaveMillis();
}
public int getStandardOffset(long instant) {
return iStandardOffset;
}
public boolean isFixed() {
return false;
}
public long nextTransition(long instant) {
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.next
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant > 0 && start < 0) {
// Overflowed.
start = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.next
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant > 0 && end < 0) {
// Overflowed.
end = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return (start > end) ? end : start;
}
public long previousTransition(long instant) {
// Increment in order to handle the case where instant is exactly at
// a transition.
instant++;
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.previous
(instant, standardOffset, endRecurrence.getSaveMillis());
if (instant < 0 && start > 0) {
// Overflowed.
start = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.previous
(instant, standardOffset, startRecurrence.getSaveMillis());
if (instant < 0 && end > 0) {
// Overflowed.
end = instant;
}
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return ((start > end) ? start : end) - 1;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof DSTZone) {
DSTZone other = (DSTZone)obj;
return
getID().equals(other.getID()) &&
iStandardOffset == other.iStandardOffset &&
iStartRecurrence.equals(other.iStartRecurrence) &&
iEndRecurrence.equals(other.iEndRecurrence);
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
writeMillis(out, iStandardOffset);
iStartRecurrence.writeTo(out);
iEndRecurrence.writeTo(out);
}
private Recurrence findMatchingRecurrence(long instant) {
int standardOffset = iStandardOffset;
Recurrence startRecurrence = iStartRecurrence;
Recurrence endRecurrence = iEndRecurrence;
long start, end;
try {
start = startRecurrence.next
(instant, standardOffset, endRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) {
// Overflowed.
start = instant;
} catch (ArithmeticException e) {
// Overflowed.
start = instant;
}
try {
end = endRecurrence.next
(instant, standardOffset, startRecurrence.getSaveMillis());
} catch (IllegalArgumentException e) {
// Overflowed.
end = instant;
} catch (ArithmeticException e) {
// Overflowed.
end = instant;
}
return (start > end) ? startRecurrence : endRecurrence;
}
}
private static final class PrecalculatedZone extends DateTimeZone {
private static final long serialVersionUID = 7811976468055766265L;
static PrecalculatedZone readFrom(DataInput in, String id) throws IOException {
// Read string pool.
int poolSize = in.readUnsignedShort();
String[] pool = new String[poolSize];
for (int i=0; i<poolSize; i++) {
pool[i] = in.readUTF();
}
int size = in.readInt();
long[] transitions = new long[size];
int[] wallOffsets = new int[size];
int[] standardOffsets = new int[size];
String[] nameKeys = new String[size];
for (int i=0; i<size; i++) {
transitions[i] = readMillis(in);
wallOffsets[i] = (int)readMillis(in);
standardOffsets[i] = (int)readMillis(in);
try {
int index;
if (poolSize < 256) {
index = in.readUnsignedByte();
} else {
index = in.readUnsignedShort();
}
nameKeys[i] = pool[index];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IOException("Invalid encoding");
}
}
DSTZone tailZone = null;
if (in.readBoolean()) {
tailZone = DSTZone.readFrom(in, id);
}
return new PrecalculatedZone
(id, transitions, wallOffsets, standardOffsets, nameKeys, tailZone);
}
/**
* Factory to create instance from builder.
*
* @param id the zone id
* @param outputID true if the zone id should be output
* @param transitions the list of Transition objects
* @param tailZone optional zone for getting info beyond precalculated tables
*/
static PrecalculatedZone create(String id, boolean outputID, ArrayList<Transition> transitions,
DSTZone tailZone) {
int size = transitions.size();
if (size == 0) {
throw new IllegalArgumentException();
}
long[] trans = new long[size];
int[] wallOffsets = new int[size];
int[] standardOffsets = new int[size];
String[] nameKeys = new String[size];
Transition last = null;
for (int i=0; i<size; i++) {
Transition tr = transitions.get(i);
if (!tr.isTransitionFrom(last)) {
throw new IllegalArgumentException(id);
}
trans[i] = tr.getMillis();
wallOffsets[i] = tr.getWallOffset();
standardOffsets[i] = tr.getStandardOffset();
nameKeys[i] = tr.getNameKey();
last = tr;
}
// Some timezones (Australia) have the same name key for
// summer and winter which messes everything up. Fix it here.
String[] zoneNameData = new String[5];
String[][] zoneStrings = new DateFormatSymbols(Locale.ENGLISH).getZoneStrings();
for (int j = 0; j < zoneStrings.length; j++) {
String[] set = zoneStrings[j];
if (set != null && set.length == 5 && id.equals(set[0])) {
zoneNameData = set;
}
}
Chronology chrono = ISOChronology.getInstanceUTC();
for (int i = 0; i < nameKeys.length - 1; i++) {
String curNameKey = nameKeys[i];
String nextNameKey = nameKeys[i + 1];
long curOffset = wallOffsets[i];
long nextOffset = wallOffsets[i + 1];
long curStdOffset = standardOffsets[i];
long nextStdOffset = standardOffsets[i + 1];
Period p = new Period(trans[i], trans[i + 1], PeriodType.yearMonthDay(), chrono);
if (curOffset != nextOffset &&
curStdOffset == nextStdOffset &&
curNameKey.equals(nextNameKey) &&
p.getYears() == 0 && p.getMonths() > 4 && p.getMonths() < 8 &&
curNameKey.equals(zoneNameData[2]) &&
curNameKey.equals(zoneNameData[4])) {
if (ZoneInfoLogger.verbose()) {
System.out.println("Fixing duplicate name key - " + nextNameKey);
System.out.println(" - " + new DateTime(trans[i], chrono) +
" - " + new DateTime(trans[i + 1], chrono));
}
if (curOffset > nextOffset) {
nameKeys[i] = (curNameKey + "-Summer").intern();
} else if (curOffset < nextOffset) {
nameKeys[i + 1] = (nextNameKey + "-Summer").intern();
i++;
}
}
}
if (tailZone != null) {
if (tailZone.iStartRecurrence.getNameKey()
.equals(tailZone.iEndRecurrence.getNameKey())) {
if (ZoneInfoLogger.verbose()) {
System.out.println("Fixing duplicate recurrent name key - " +
tailZone.iStartRecurrence.getNameKey());
}
if (tailZone.iStartRecurrence.getSaveMillis() > 0) {
tailZone = new DSTZone(
tailZone.getID(),
tailZone.iStandardOffset,
tailZone.iStartRecurrence.renameAppend("-Summer"),
tailZone.iEndRecurrence);
} else {
tailZone = new DSTZone(
tailZone.getID(),
tailZone.iStandardOffset,
tailZone.iStartRecurrence,
tailZone.iEndRecurrence.renameAppend("-Summer"));
}
}
}
return new PrecalculatedZone
((outputID ? id : ""), trans, wallOffsets, standardOffsets, nameKeys, tailZone);
}
// All array fields have the same length.
private final long[] iTransitions;
private final int[] iWallOffsets;
private final int[] iStandardOffsets;
private final String[] iNameKeys;
private final DSTZone iTailZone;
/**
* Constructor used ONLY for valid input, loaded via static methods.
*/
private PrecalculatedZone(String id, long[] transitions, int[] wallOffsets,
int[] standardOffsets, String[] nameKeys, DSTZone tailZone)
{
super(id);
iTransitions = transitions;
iWallOffsets = wallOffsets;
iStandardOffsets = standardOffsets;
iNameKeys = nameKeys;
iTailZone = tailZone;
}
public String getNameKey(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iNameKeys[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iNameKeys[i - 1];
}
return "UTC";
}
if (iTailZone == null) {
return iNameKeys[i - 1];
}
return iTailZone.getNameKey(instant);
}
public int getOffset(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iWallOffsets[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iWallOffsets[i - 1];
}
return 0;
}
if (iTailZone == null) {
return iWallOffsets[i - 1];
}
return iTailZone.getOffset(instant);
}
public int getStandardOffset(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
return iStandardOffsets[i];
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
return iStandardOffsets[i - 1];
}
return 0;
}
if (iTailZone == null) {
return iStandardOffsets[i - 1];
}
return iTailZone.getStandardOffset(instant);
}
public boolean isFixed() {
return false;
}
public long nextTransition(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
i = (i >= 0) ? (i + 1) : ~i;
if (i < transitions.length) {
return transitions[i];
}
if (iTailZone == null) {
return instant;
}
long end = transitions[transitions.length - 1];
if (instant < end) {
instant = end;
}
return iTailZone.nextTransition(instant);
}
public long previousTransition(long instant) {
long[] transitions = iTransitions;
int i = Arrays.binarySearch(transitions, instant);
if (i >= 0) {
if (instant > Long.MIN_VALUE) {
return instant - 1;
}
return instant;
}
i = ~i;
if (i < transitions.length) {
if (i > 0) {
long prev = transitions[i - 1];
if (prev > Long.MIN_VALUE) {
return prev - 1;
}
}
return instant;
}
if (iTailZone != null) {
long prev = iTailZone.previousTransition(instant);
if (prev < instant) {
return prev;
}
}
long prev = transitions[i - 1];
if (prev > Long.MIN_VALUE) {
return prev - 1;
}
return instant;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof PrecalculatedZone) {
PrecalculatedZone other = (PrecalculatedZone)obj;
return
getID().equals(other.getID()) &&
Arrays.equals(iTransitions, other.iTransitions) &&
Arrays.equals(iNameKeys, other.iNameKeys) &&
Arrays.equals(iWallOffsets, other.iWallOffsets) &&
Arrays.equals(iStandardOffsets, other.iStandardOffsets) &&
((iTailZone == null)
? (null == other.iTailZone)
: (iTailZone.equals(other.iTailZone)));
}
return false;
}
public void writeTo(DataOutput out) throws IOException {
int size = iTransitions.length;
// Create unique string pool.
Set<String> poolSet = new HashSet<String>();
for (int i=0; i<size; i++) {
poolSet.add(iNameKeys[i]);
}
int poolSize = poolSet.size();
if (poolSize > 65535) {
throw new UnsupportedOperationException("String pool is too large");
}
String[] pool = new String[poolSize];
Iterator<String> it = poolSet.iterator();
for (int i=0; it.hasNext(); i++) {
pool[i] = it.next();
}
// Write out the pool.
out.writeShort(poolSize);
for (int i=0; i<poolSize; i++) {
out.writeUTF(pool[i]);
}
out.writeInt(size);
for (int i=0; i<size; i++) {
writeMillis(out, iTransitions[i]);
writeMillis(out, iWallOffsets[i]);
writeMillis(out, iStandardOffsets[i]);
// Find pool index and write it out.
String nameKey = iNameKeys[i];
for (int j=0; j<poolSize; j++) {
if (pool[j].equals(nameKey)) {
if (poolSize < 256) {
out.writeByte(j);
} else {
out.writeShort(j);
}
break;
}
}
}
out.writeBoolean(iTailZone != null);
if (iTailZone != null) {
iTailZone.writeTo(out);
}
}
public boolean isCachable() {
if (iTailZone != null) {
return true;
}
long[] transitions = iTransitions;
if (transitions.length <= 1) {
return false;
}
// Add up all the distances between transitions that are less than
// about two years.
double distances = 0;
int count = 0;
for (int i=1; i<transitions.length; i++) {
long diff = transitions[i] - transitions[i - 1];
if (diff < ((366L + 365) * 24 * 60 * 60 * 1000)) {
distances += (double)diff;
count++;
}
}
if (count > 0) {
double avg = distances / count;
avg /= 24 * 60 * 60 * 1000;
if (avg >= 25) {
// Only bother caching if average distance between
// transitions is at least 25 days. Why 25?
// CachedDateTimeZone is more efficient if the distance
// between transitions is large. With an average of 25, it
// will on average perform about 2 tests per cache
// hit. (49.7 / 25) is approximately 2.
return true;
}
}
return false;
}
}
}
|
Fixing usage of DataOutputStream
|
src/main/java/org/joda/time/tz/DateTimeZoneBuilder.java
|
Fixing usage of DataOutputStream
|
|
Java
|
apache-2.0
|
dc1caa818cf52f90f1fbde8565c3c649a3f0a968
| 0
|
cmusatyalab/gabriel,cmusatyalab/gabriel,cmusatyalab/gabriel
|
package edu.cmu.cs.gabriel.client.socket;
import android.app.Application;
import android.net.Network;
import android.security.NetworkSecurityPolicy;
import android.util.Log;
import androidx.annotation.NonNull;
import com.tinder.scarlet.Lifecycle;
import com.tinder.scarlet.Scarlet;
import com.tinder.scarlet.lifecycle.android.AndroidLifecycle;
import com.tinder.scarlet.websocket.okhttp.OkHttpClientUtils;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.function.Consumer;
import edu.cmu.cs.gabriel.client.observer.EventObserver;
import edu.cmu.cs.gabriel.client.observer.ResultObserver;
import edu.cmu.cs.gabriel.client.results.ErrorType;
import edu.cmu.cs.gabriel.protocol.Protos.FromClient;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
public class SocketWrapper {
private static final String TAG = "SocketWrapper";
private final EventObserver eventObserver;
private final GabrielSocket webSocketInterface;
public SocketWrapper(String endpoint, int port, Application application,
final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver) {
this(endpoint, port, application, onDisconnect, resultObserver,
new SocketFactoryTcpNoDelay());
}
public SocketWrapper(String endpoint, int port, Application application,
final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver,
@NonNull Network network) {
this(endpoint, port, application, onDisconnect, resultObserver,
new SocketFactoryTcpNoDelay(network));
}
private SocketWrapper(String endpoint, int port, Application application,
final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver,
@NonNull SocketFactoryTcpNoDelay socketFactoryTcpNoDelay) {
UriOutput uriOutput = formatURI(endpoint, port);
String wsURL;
switch (uriOutput.getOutputType()) {
case CLEARTEXT_WITHOUT_PERMISSION:
throw new RuntimeException(
"Manifest file or security config does not allow cleartext connections.");
case INVALID:
throw new RuntimeException("Invalid endpoint.");
case VALID:
wsURL = uriOutput.getOutput();
break;
default:
throw new IllegalStateException("Unexpected value: " + uriOutput.getOutputType());
}
Runnable onErrorResult = new Runnable() {
@Override
public void run() {
onDisconnect.accept(ErrorType.SERVER_ERROR);
SocketWrapper.this.stop();
}
};
resultObserver.setOnErrorResult(onErrorResult);
this.eventObserver = new EventObserver(onDisconnect);
Lifecycle androidLifecycle = AndroidLifecycle.ofApplicationForeground(application);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
try {
SSLSocketFactoryTcpNoDelay sSLSocketFactoryTcpNoDelay =
new SSLSocketFactoryTcpNoDelay();
okHttpClientBuilder.sslSocketFactory(sSLSocketFactoryTcpNoDelay.getSslSocketFactory(),
sSLSocketFactoryTcpNoDelay.getTrustManager());
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
Log.e(TAG, "TLS Socket error", e);
}
okHttpClientBuilder.socketFactory(socketFactoryTcpNoDelay);
OkHttpClient okClient = okHttpClientBuilder.build();
this.webSocketInterface = (new Scarlet.Builder())
.webSocketFactory(OkHttpClientUtils.newWebSocketFactory(okClient, wsURL))
.lifecycle(androidLifecycle.combineWith(this.eventObserver.getLifecycleRegistry()))
.build().create(GabrielSocket.class);
this.webSocketInterface.receive().start(resultObserver);
this.webSocketInterface.observeWebSocketEvent().start(this.eventObserver);
}
public boolean isRunning() {
return this.eventObserver.isRunning();
}
public void send(FromClient fromClient) {
this.webSocketInterface.send(fromClient.toByteArray());
}
public void stop() {
this.eventObserver.stop();
}
/**
* This is used to check the given URL is valid or not.
* @param endpoint (host|IP) or websocket url
* @return true if URI is valid
*/
public static boolean validUri(String endpoint, int port) {
return formatURI(endpoint, port).getOutputType() == UriOutput.OutputType.VALID;
}
/**
* Format URI with port
*
* @param endpoint (host|IP) or websocket url
* @return String url if valid, null otherwise.
*/
private static UriOutput formatURI(String endpoint, int port) {
if (endpoint.isEmpty()) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
// make sure there is a scheme before we try to parse this
if (!endpoint.matches("^[a-zA-Z]+://.*$")) {
endpoint = "ws://" + endpoint;
}
// okhttp3.HttpUrl can only parse URIs starting with http or https
endpoint = endpoint.replaceFirst("^ws://", "http://");
endpoint = endpoint.replaceFirst("^wss://", "https://");
HttpUrl httpurl = HttpUrl.parse(endpoint);
if (httpurl == null) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
if (!httpurl.isHttps() &&
!NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(httpurl.host())) {
return new UriOutput(UriOutput.OutputType.CLEARTEXT_WITHOUT_PERMISSION);
}
try {
httpurl = httpurl.newBuilder().port(port).build();
} catch (IllegalArgumentException e) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
String output = httpurl.toString().replaceFirst(
"^http://", "ws://");
output = output.replaceFirst("^https://", "wss://");
return new UriOutput(UriOutput.OutputType.VALID, output);
}
}
|
android-client/client/src/main/java/edu/cmu/cs/gabriel/client/socket/SocketWrapper.java
|
package edu.cmu.cs.gabriel.client.socket;
import android.app.Application;
import android.net.Network;
import android.security.NetworkSecurityPolicy;
import android.util.Log;
import androidx.annotation.NonNull;
import com.tinder.scarlet.Lifecycle;
import com.tinder.scarlet.Scarlet;
import com.tinder.scarlet.lifecycle.android.AndroidLifecycle;
import com.tinder.scarlet.websocket.okhttp.OkHttpClientUtils;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.function.Consumer;
import edu.cmu.cs.gabriel.client.observer.EventObserver;
import edu.cmu.cs.gabriel.client.observer.ResultObserver;
import edu.cmu.cs.gabriel.client.results.ErrorType;
import edu.cmu.cs.gabriel.protocol.Protos.FromClient;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
public class SocketWrapper {
private static final String TAG = "SocketWrapper";
private EventObserver eventObserver;
private GabrielSocket webSocketInterface;
private Network network;
public SocketWrapper(String endpoint, int port, Application application, final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver) {
this(endpoint, port, application, onDisconnect, resultObserver, new SocketFactoryTcpNoDelay());
}
public SocketWrapper(String endpoint, int port, Application application, final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver, @NonNull Network network) {
new SocketWrapper(endpoint, port, application, onDisconnect, resultObserver, new SocketFactoryTcpNoDelay(network));
}
private SocketWrapper(String endpoint, int port, Application application, final Consumer<ErrorType> onDisconnect, ResultObserver resultObserver, @NonNull SocketFactoryTcpNoDelay socketFactoryTcpNoDelay)
{
UriOutput uriOutput = formatURI(endpoint, port);
String wsURL;
switch (uriOutput.getOutputType()) {
case CLEARTEXT_WITHOUT_PERMISSION:
throw new RuntimeException(
"Manifest file or security config does not allow cleartext connections.");
case INVALID:
throw new RuntimeException("Invalid endpoint.");
case VALID:
wsURL = uriOutput.getOutput();
break;
default:
throw new IllegalStateException("Unexpected value: " + uriOutput.getOutputType());
}
Runnable onErrorResult = new Runnable() {
@Override
public void run() {
onDisconnect.accept(ErrorType.SERVER_ERROR);
SocketWrapper.this.stop();
}
};
resultObserver.setOnErrorResult(onErrorResult);
this.eventObserver = new EventObserver(onDisconnect);
Lifecycle androidLifecycle = AndroidLifecycle.ofApplicationForeground(application);
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
try {
SSLSocketFactoryTcpNoDelay sSLSocketFactoryTcpNoDelay =
new SSLSocketFactoryTcpNoDelay();
okHttpClientBuilder.sslSocketFactory(sSLSocketFactoryTcpNoDelay.getSslSocketFactory(),
sSLSocketFactoryTcpNoDelay.getTrustManager());
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
Log.e(TAG, "TLS Socket error", e);
}
okHttpClientBuilder.socketFactory(socketFactoryTcpNoDelay);
OkHttpClient okClient = okHttpClientBuilder.build();
this.webSocketInterface = (new Scarlet.Builder())
.webSocketFactory(OkHttpClientUtils.newWebSocketFactory(okClient, wsURL))
.lifecycle(androidLifecycle.combineWith(this.eventObserver.getLifecycleRegistry()))
.build().create(GabrielSocket.class);
this.webSocketInterface.receive().start(resultObserver);
this.webSocketInterface.observeWebSocketEvent().start(this.eventObserver);
}
public boolean isRunning() {
return this.eventObserver.isRunning();
}
public void send(FromClient fromClient) {
this.webSocketInterface.send(fromClient.toByteArray());
}
public void stop() {
this.eventObserver.stop();
}
/**
* This is used to check the given URL is valid or not.
* @param endpoint (host|IP) or websocket url
* @return true if URI is valid
*/
public static boolean validUri(String endpoint, int port) {
return formatURI(endpoint, port).getOutputType() == UriOutput.OutputType.VALID;
}
/**
* Format URI with port
*
* @param endpoint (host|IP) or websocket url
* @return String url if valid, null otherwise.
*/
private static UriOutput formatURI(String endpoint, int port) {
if (endpoint.isEmpty()) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
// make sure there is a scheme before we try to parse this
if (!endpoint.matches("^[a-zA-Z]+://.*$")) {
endpoint = "ws://" + endpoint;
}
// okhttp3.HttpUrl can only parse URIs starting with http or https
endpoint = endpoint.replaceFirst("^ws://", "http://");
endpoint = endpoint.replaceFirst("^wss://", "https://");
HttpUrl httpurl = HttpUrl.parse(endpoint);
if (httpurl == null) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
if (!httpurl.isHttps() &&
!NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(httpurl.host())) {
return new UriOutput(UriOutput.OutputType.CLEARTEXT_WITHOUT_PERMISSION);
}
try {
httpurl = httpurl.newBuilder().port(port).build();
} catch (IllegalArgumentException e) {
return new UriOutput(UriOutput.OutputType.INVALID);
}
String output = httpurl.toString().replaceFirst(
"^http://", "ws://");
output = output.replaceFirst("^https://", "wss://");
return new UriOutput(UriOutput.OutputType.VALID, output);
}
}
|
fix SocketWrapper constructor
|
android-client/client/src/main/java/edu/cmu/cs/gabriel/client/socket/SocketWrapper.java
|
fix SocketWrapper constructor
|
|
Java
|
apache-2.0
|
d59b7cb0cc1f69c5304f1864c4c629b7844b1602
| 0
|
skmbw/dubbox,skmbw/dubbox,skmbw/dubbox
|
package com.alibaba.dubbo.common.serialize.support;
import java.util.Set;
import java.util.TreeSet;
/**
* @author lishen
*/
public abstract class SerializableClassRegistry {
private static final Set<Class> registrations = new TreeSet<>((o1, o2) -> o1.getName().compareTo(o2.getName()));
/**
* only supposed to be called at startup time
*/
public static void registerClass(Class clazz) {
registrations.add(clazz);
}
public static Set<Class> getRegisteredClasses() {
return registrations;
}
}
|
dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java
|
package com.alibaba.dubbo.common.serialize.support;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author lishen
*/
public abstract class SerializableClassRegistry {
private static final Set<Class> registrations = new LinkedHashSet<Class>();
/**
* only supposed to be called at startup time
*/
public static void registerClass(Class clazz) {
registrations.add(clazz);
}
public static Set<Class> getRegisteredClasses() {
return registrations;
}
}
|
注册的类,使用牌序的TreeSet
|
dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java
|
注册的类,使用牌序的TreeSet
|
|
Java
|
apache-2.0
|
d50ad7ea4c5dc7f127aefcc691c4a8d104cad50e
| 0
|
michael-rapp/AndroidAdapters
|
/*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* 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
* 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 de.mrapp.android.adapter.list.selectable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import android.content.Context;
import de.mrapp.android.adapter.SelectableListDecorator;
import de.mrapp.android.adapter.SingleChoiceListAdapter;
import de.mrapp.android.adapter.datastructure.item.Item;
import de.mrapp.android.adapter.inflater.Inflater;
import de.mrapp.android.adapter.list.ListAdapterListener;
import de.mrapp.android.adapter.list.enablestate.ListEnableStateListener;
import de.mrapp.android.adapter.list.itemstate.ListItemStateListener;
import de.mrapp.android.adapter.list.sortable.ListSortingListener;
/**
* An adapter, whose underlying data is managed as a list of arbitrary items, of
* which only item can be selected at once. Such an adapter's purpose is to
* provide the underlying data for visualization using a {@link ListView}
* widget.
*
* @param <DataType>
* The type of the adapter's underlying data
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public class SingleChoiceListAdapterImplementation<DataType> extends
AbstractSelectableListAdapter<DataType> implements
SingleChoiceListAdapter<DataType> {
/**
* The constant serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* Creates and returns a listener, which allows to adapt the selections of
* the adapter's items, when an item has been removed from or added to the
* adapter.
*
* @return The listener, which has been created, as an instance of the type
* {@link ListAdapterListener}
*/
private ListAdapterListener<DataType> createAdapterListener() {
return new ListAdapterListener<DataType>() {
@Override
public void onItemAdded(final DataType item, final int index) {
if (getNumberOfItems() == 1) {
select(index);
}
}
@Override
public void onItemRemoved(final DataType item, final int index) {
if (getSelectedIndex() == -1) {
selectNearestEnabledItem(index);
}
}
};
}
/**
* Creates and returns a listener, which allows to adapt the selections of
* the adapter's items, when an item has been enabled or disabled.
*
* @return The listener, which has been created, as an instance of the type
* {@link ListEnableStateListener}
*/
private ListEnableStateListener<DataType> createEnableStateListener() {
return new ListEnableStateListener<DataType>() {
@Override
public void onItemEnabled(final DataType item, final int index) {
if (getNumberOfItems() == 1) {
select(index);
}
}
@Override
public void onItemDisabled(final DataType item, final int index) {
if (isSelected(index)) {
getItems().get(index).setSelected(false);
notifyOnItemUnselected(item, index);
notifyDataSetChanged();
selectNearestEnabledItem(index);
}
}
};
}
/**
* Selects the nearest enabled item, starting from a specific index. The
* item is searched alternately by ascending and descending indices. If no
* enabled item is available, no item will be selected.
*
* @param index
* The index, the search for the nearest enabled item should be
* started at, as an {@link Integer} value
*/
private void selectNearestEnabledItem(final int index) {
int ascendingIndex = index;
int descendingIndex = index - 1;
while (ascendingIndex < getNumberOfItems() || descendingIndex >= 0) {
if (ascendingIndex < getNumberOfItems()
&& isEnabled(ascendingIndex)) {
select(ascendingIndex);
return;
} else if (descendingIndex >= 0 && isEnabled(descendingIndex)) {
select(descendingIndex);
return;
}
ascendingIndex++;
descendingIndex--;
}
}
/**
* Creates a new adapter, whose underlying data is managed as a list of
* arbitrary items, of which only one item can be selected at once.
*
* @param context
* The context, the adapter should belong to, as an instance of
* the class {@link Context}. The context may not be null
* @param inflater
* The inflater, which should be used to inflate the views, which
* are used to visualize the adapter's items, as an instance of
* the type {@link Inflater}. The inflater may not be null
* @param decorator
* The decorator, which should be used to customize the
* appearance of the views, which are used to visualize the items
* of the adapter, as an instance of the generic type
* DecoratorType. The decorator may not be null
* @param items
* A list, which contains the the adapter's items, or an empty
* list, if the adapter should not contain any items
* @param allowDuplicates
* True, if duplicate items should be allowed, false otherwise
* @param adapterListeners
* A set, which contains the listeners, which should be notified
* when the adapter's underlying data has been modified or an
* empty set, if no listeners should be notified
* @param enableStateListeners
* A set, which contains the listeners, which should be notified
* when an item has been disabled or enabled or an empty set, if
* no listeners should be notified
* @param numberOfItemStates
* The number of states, the adapter's items may have, as an
* {@link Integer} value. The value must be at least 1
* @param triggerItemStateOnClick
* True, if the state of an item should be triggered, when it is
* clicked by the user, false otherwise
* @param itemStateListeners
* A set, which contains the listeners, which should be notified,
* when the state of an item has been changed or an empty set, if
* no listeners should be notified
* @param sortingListeners
* A set, which contains the listeners, which should be notified,
* when the adapter's underlying data has been sorted or an empty
* set, if no listeners should be notified
* @param selectItemOnClick
* True, if an item should be selected, when it is clicked by the
* user, false otherwise
* @param selectionListeners
* A set, which contains the listeners, which should be notified,
* when an item's selection has been changed or an empty set, if
* no listeners should be notified
*/
protected SingleChoiceListAdapterImplementation(final Context context,
final Inflater inflater,
final SelectableListDecorator<DataType> decorator,
final List<Item<DataType>> items, final boolean allowDuplicates,
final Set<ListAdapterListener<DataType>> adapterListeners,
final Set<ListEnableStateListener<DataType>> enableStateListeners,
final int numberOfItemStates,
final boolean triggerItemStateOnClick,
final Set<ListItemStateListener<DataType>> itemStateListeners,
final Set<ListSortingListener<DataType>> sortingListeners,
final boolean selectItemOnClick,
final Set<ListSelectionListener<DataType>> selectionListeners) {
super(context, inflater, decorator, items, allowDuplicates,
adapterListeners, enableStateListeners, numberOfItemStates,
triggerItemStateOnClick, itemStateListeners, sortingListeners,
selectItemOnClick, selectionListeners);
addAdapterListener(createAdapterListener());
addEnableStateListner(createEnableStateListener());
}
/**
* Creates a new adapter, whose underlying data is managed as a list of
* arbitrary items, of which only one item can be selected at once.
*
* @param context
* The context, the adapter should belong to, as an instance of
* the class {@link Context}. The context may not be null
* @param inflater
* The inflater, which should be used to inflate the views, which
* are used to visualize the adapter's items, as an instance of
* the type {@link Inflater}. The inflater may not be null
* @param decorator
* The decorator, which should be used to customize the
* appearance of the views, which are used to visualize the items
* of the adapter, as an instance of the generic type
* DecoratorType. The decorator may not be null
*/
public SingleChoiceListAdapterImplementation(final Context context,
final Inflater inflater,
final SelectableListDecorator<DataType> decorator) {
this(context, inflater, decorator, new ArrayList<Item<DataType>>(),
false, new LinkedHashSet<ListAdapterListener<DataType>>(),
new LinkedHashSet<ListEnableStateListener<DataType>>(), 1,
false, new LinkedHashSet<ListItemStateListener<DataType>>(),
new LinkedHashSet<ListSortingListener<DataType>>(), true,
new LinkedHashSet<ListSelectionListener<DataType>>());
}
@Override
public final int getSelectedIndex() {
for (int i = 0; i < getNumberOfItems(); i++) {
if (getItems().get(i).isSelected()) {
return i;
}
}
return -1;
}
@Override
public final DataType getSelectedItem() {
for (Item<DataType> item : getItems()) {
if (item.isSelected()) {
return item.getData();
}
}
return null;
}
@Override
public final boolean select(final int index) {
if (getItems().get(index).isEnabled()) {
for (int i = 0; i < getNumberOfItems(); i++) {
Item<DataType> item = getItems().get(i);
if (i == index && !item.isSelected()) {
item.setSelected(true);
notifyOnItemSelected(item.getData(), i);
} else if (i != index && item.isSelected()) {
item.setSelected(false);
notifyOnItemUnselected(item.getData(), i);
}
}
notifyDataSetChanged();
return true;
} else {
return false;
}
}
@Override
public final boolean select(final DataType item) {
int index = indexOf(item);
if (index != -1) {
return select(index);
} else {
throw new NoSuchElementException();
}
}
@Override
public final String toString() {
return "SingleChoiceListAdapter [sortingListeners="
+ getSortingListeners() + ", itemStateListeners="
+ getItemStateListeners() + ", numberOfItemStates="
+ getNumberOfItemStates() + ", triggerItemStateOnClick="
+ isItemStateTriggeredOnClick() + ", enableStateListeners="
+ getEnableStateListeners() + ", items=" + getItems()
+ ", adapterListeners=" + getAdapterListeners()
+ ", allowDuplicates=" + areDuplicatesAllowed()
+ ", selectItemOnClick=" + isItemSelectedOnClick()
+ ", selectionListeners=" + getSelectionListeners() + "]";
}
@Override
public final SingleChoiceListAdapterImplementation<DataType> clone()
throws CloneNotSupportedException {
return new SingleChoiceListAdapterImplementation<DataType>(
getContext(), getInflater(), getDecorator(), cloneItems(),
areDuplicatesAllowed(), getAdapterListeners(),
getEnableStateListeners(), getNumberOfItemStates(),
isItemStateTriggeredOnClick(), getItemStateListeners(),
getSortingListeners(), isItemSelectedOnClick(),
getSelectionListeners());
}
}
|
src/de/mrapp/android/adapter/list/selectable/SingleChoiceListAdapterImplementation.java
|
/*
* AndroidAdapters Copyright 2014 Michael Rapp
*
* 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
* 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 de.mrapp.android.adapter.list.selectable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import android.content.Context;
import de.mrapp.android.adapter.SelectableListDecorator;
import de.mrapp.android.adapter.SingleChoiceListAdapter;
import de.mrapp.android.adapter.datastructure.item.Item;
import de.mrapp.android.adapter.inflater.Inflater;
import de.mrapp.android.adapter.list.ListAdapterListener;
import de.mrapp.android.adapter.list.enablestate.ListEnableStateListener;
import de.mrapp.android.adapter.list.itemstate.ListItemStateListener;
import de.mrapp.android.adapter.list.sortable.ListSortingListener;
/**
* An adapter, whose underlying data is managed as a list of arbitrary items, of
* which only item can be selected at once. Such an adapter's purpose is to
* provide the underlying data for visualization using a {@link ListView}
* widget.
*
* @param <DataType>
* The type of the adapter's underlying data
*
* @author Michael Rapp
*
* @since 1.0.0
*/
public class SingleChoiceListAdapterImplementation<DataType> extends
AbstractSelectableListAdapter<DataType> implements
SingleChoiceListAdapter<DataType> {
/**
* The constant serial version UID.
*/
private static final long serialVersionUID = 1L;
/**
* Creates and returns a listener, which allows to adapt the selections of
* the adapter's items, when an item has been removed from or added to the
* adapter.
*
* @return The listener, which has been created, as an instance of the type
* {@link ListAdapterListener}
*/
private ListAdapterListener<DataType> createAdapterListener() {
return new ListAdapterListener<DataType>() {
@Override
public void onItemAdded(final DataType item, final int index) {
if (getNumberOfItems() == 1) {
select(index);
}
}
@Override
public void onItemRemoved(final DataType item, final int index) {
if (getSelectedIndex() == -1) {
selectNearestEnabledItem(index);
}
}
};
}
/**
* Creates and returns a listener, which allows to adapt the selections of
* the adapter's items, when an item has been enabled or disabled.
*
* @return The listener, which has been created, as an instance of the type
* {@link ListEnableStateListener}
*/
private ListEnableStateListener<DataType> createEnableStateListener() {
return new ListEnableStateListener<DataType>() {
@Override
public void onItemEnabled(final DataType item, final int index) {
if (getNumberOfItems() == 1) {
select(index);
}
}
@Override
public void onItemDisabled(final DataType item, final int index) {
if (isSelected(index)) {
getItems().get(index).setSelected(false);
notifyOnItemUnselected(item, index);
notifyDataSetChanged();
selectNearestEnabledItem(index);
}
}
};
}
/**
* Selects the nearest enabled item, starting from a specific index. The
* item is searched in ascending order and afterwards, if this search is not
* successful, in descending order. If no enabled item is available, no item
* will be selected.
*
* @param index
* The index, the search for the nearest enabled item should be
* started at, as an {@link Integer} value
*/
private void selectNearestEnabledItem(final int index) {
boolean selected = selectNearestEnabledItemByAscendingIndex(index);
if (!selected) {
selectNearestEnabledItemByDescendingIndex(index);
}
}
/**
* Selects the nearest enabled item, starting from a specific index. The
* item is searched in ascending order. If no enabled item is available, no
* item will be selected.
*
* @param index
* The index, the search for the nearest enabled item should be
* started at, as an {@link Integer} value
* @return True, if an item has been selected, false otherwise
*/
private boolean selectNearestEnabledItemByAscendingIndex(final int index) {
for (int i = index; i < getNumberOfItems(); i++) {
if (isEnabled(i)) {
select(i);
return true;
}
}
return false;
}
/**
* Selects the nearest enabled item, starting from a specific index. The
* item is searched in descending order. If no enabled item is available, no
* item will be selected.
*
* @param index
* The index, the search for the nearest enabled item should be
* started at, as an {@link Integer} value
*/
private void selectNearestEnabledItemByDescendingIndex(final int index) {
for (int i = index - 1; i >= 0; i--) {
if (isEnabled(i)) {
select(i);
return;
}
}
}
/**
* Creates a new adapter, whose underlying data is managed as a list of
* arbitrary items, of which only one item can be selected at once.
*
* @param context
* The context, the adapter should belong to, as an instance of
* the class {@link Context}. The context may not be null
* @param inflater
* The inflater, which should be used to inflate the views, which
* are used to visualize the adapter's items, as an instance of
* the type {@link Inflater}. The inflater may not be null
* @param decorator
* The decorator, which should be used to customize the
* appearance of the views, which are used to visualize the items
* of the adapter, as an instance of the generic type
* DecoratorType. The decorator may not be null
* @param items
* A list, which contains the the adapter's items, or an empty
* list, if the adapter should not contain any items
* @param allowDuplicates
* True, if duplicate items should be allowed, false otherwise
* @param adapterListeners
* A set, which contains the listeners, which should be notified
* when the adapter's underlying data has been modified or an
* empty set, if no listeners should be notified
* @param enableStateListeners
* A set, which contains the listeners, which should be notified
* when an item has been disabled or enabled or an empty set, if
* no listeners should be notified
* @param numberOfItemStates
* The number of states, the adapter's items may have, as an
* {@link Integer} value. The value must be at least 1
* @param triggerItemStateOnClick
* True, if the state of an item should be triggered, when it is
* clicked by the user, false otherwise
* @param itemStateListeners
* A set, which contains the listeners, which should be notified,
* when the state of an item has been changed or an empty set, if
* no listeners should be notified
* @param sortingListeners
* A set, which contains the listeners, which should be notified,
* when the adapter's underlying data has been sorted or an empty
* set, if no listeners should be notified
* @param selectItemOnClick
* True, if an item should be selected, when it is clicked by the
* user, false otherwise
* @param selectionListeners
* A set, which contains the listeners, which should be notified,
* when an item's selection has been changed or an empty set, if
* no listeners should be notified
*/
protected SingleChoiceListAdapterImplementation(final Context context,
final Inflater inflater,
final SelectableListDecorator<DataType> decorator,
final List<Item<DataType>> items, final boolean allowDuplicates,
final Set<ListAdapterListener<DataType>> adapterListeners,
final Set<ListEnableStateListener<DataType>> enableStateListeners,
final int numberOfItemStates,
final boolean triggerItemStateOnClick,
final Set<ListItemStateListener<DataType>> itemStateListeners,
final Set<ListSortingListener<DataType>> sortingListeners,
final boolean selectItemOnClick,
final Set<ListSelectionListener<DataType>> selectionListeners) {
super(context, inflater, decorator, items, allowDuplicates,
adapterListeners, enableStateListeners, numberOfItemStates,
triggerItemStateOnClick, itemStateListeners, sortingListeners,
selectItemOnClick, selectionListeners);
addAdapterListener(createAdapterListener());
addEnableStateListner(createEnableStateListener());
}
/**
* Creates a new adapter, whose underlying data is managed as a list of
* arbitrary items, of which only one item can be selected at once.
*
* @param context
* The context, the adapter should belong to, as an instance of
* the class {@link Context}. The context may not be null
* @param inflater
* The inflater, which should be used to inflate the views, which
* are used to visualize the adapter's items, as an instance of
* the type {@link Inflater}. The inflater may not be null
* @param decorator
* The decorator, which should be used to customize the
* appearance of the views, which are used to visualize the items
* of the adapter, as an instance of the generic type
* DecoratorType. The decorator may not be null
*/
public SingleChoiceListAdapterImplementation(final Context context,
final Inflater inflater,
final SelectableListDecorator<DataType> decorator) {
this(context, inflater, decorator, new ArrayList<Item<DataType>>(),
false, new LinkedHashSet<ListAdapterListener<DataType>>(),
new LinkedHashSet<ListEnableStateListener<DataType>>(), 1,
false, new LinkedHashSet<ListItemStateListener<DataType>>(),
new LinkedHashSet<ListSortingListener<DataType>>(), true,
new LinkedHashSet<ListSelectionListener<DataType>>());
}
@Override
public final int getSelectedIndex() {
for (int i = 0; i < getNumberOfItems(); i++) {
if (getItems().get(i).isSelected()) {
return i;
}
}
return -1;
}
@Override
public final DataType getSelectedItem() {
for (Item<DataType> item : getItems()) {
if (item.isSelected()) {
return item.getData();
}
}
return null;
}
@Override
public final boolean select(final int index) {
if (getItems().get(index).isEnabled()) {
for (int i = 0; i < getNumberOfItems(); i++) {
Item<DataType> item = getItems().get(i);
if (i == index && !item.isSelected()) {
item.setSelected(true);
notifyOnItemSelected(item.getData(), i);
} else if (i != index && item.isSelected()) {
item.setSelected(false);
notifyOnItemUnselected(item.getData(), i);
}
}
notifyDataSetChanged();
return true;
} else {
return false;
}
}
@Override
public final boolean select(final DataType item) {
int index = indexOf(item);
if (index != -1) {
return select(index);
} else {
throw new NoSuchElementException();
}
}
@Override
public final String toString() {
return "SingleChoiceListAdapter [sortingListeners="
+ getSortingListeners() + ", itemStateListeners="
+ getItemStateListeners() + ", numberOfItemStates="
+ getNumberOfItemStates() + ", triggerItemStateOnClick="
+ isItemStateTriggeredOnClick() + ", enableStateListeners="
+ getEnableStateListeners() + ", items=" + getItems()
+ ", adapterListeners=" + getAdapterListeners()
+ ", allowDuplicates=" + areDuplicatesAllowed()
+ ", selectItemOnClick=" + isItemSelectedOnClick()
+ ", selectionListeners=" + getSelectionListeners() + "]";
}
@Override
public final SingleChoiceListAdapterImplementation<DataType> clone()
throws CloneNotSupportedException {
return new SingleChoiceListAdapterImplementation<DataType>(
getContext(), getInflater(), getDecorator(), cloneItems(),
areDuplicatesAllowed(), getAdapterListeners(),
getEnableStateListeners(), getNumberOfItemStates(),
isItemStateTriggeredOnClick(), getItemStateListeners(),
getSortingListeners(), isItemSelectedOnClick(),
getSelectionListeners());
}
}
|
Changed algorithm, which is used to find nearest enabled item.
|
src/de/mrapp/android/adapter/list/selectable/SingleChoiceListAdapterImplementation.java
|
Changed algorithm, which is used to find nearest enabled item.
|
|
Java
|
apache-2.0
|
40ebe2fd501af3d02b24ed334767af07ef7d7d78
| 0
|
robovm/robovm-studio,tmpgit/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,caot/intellij-community,retomerz/intellij-community,kdwink/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,slisson/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,blademainer/intellij-community,fnouama/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,FHannes/intellij-community,fnouama/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,wreckJ/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ernestp/consulo,MichaelNedzelsky/intellij-community,kdwink/intellij-community,jagguli/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,jexp/idea2,robovm/robovm-studio,ryano144/intellij-community,vvv1559/intellij-community,caot/intellij-community,apixandru/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,jexp/idea2,apixandru/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,asedunov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,jexp/idea2,joewalnes/idea-community,xfournet/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,signed/intellij-community,signed/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,petteyg/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,consulo/consulo,idea4bsd/idea4bsd,ibinti/intellij-community,FHannes/intellij-community,diorcety/intellij-community,kdwink/intellij-community,clumsy/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,clumsy/intellij-community,apixandru/intellij-community,vladmm/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,holmes/intellij-community,fnouama/intellij-community,robovm/robovm-studio,dslomov/intellij-community,signed/intellij-community,diorcety/intellij-community,allotria/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,consulo/consulo,lucafavatella/intellij-community,allotria/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,izonder/intellij-community,caot/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,diorcety/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,allotria/intellij-community,caot/intellij-community,vladmm/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,allotria/intellij-community,caot/intellij-community,wreckJ/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,ernestp/consulo,ol-loginov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,da1z/intellij-community,izonder/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,FHannes/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,adedayo/intellij-community,amith01994/intellij-community,adedayo/intellij-community,apixandru/intellij-community,signed/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,holmes/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,asedunov/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,robovm/robovm-studio,idea4bsd/idea4bsd,nicolargo/intellij-community,kool79/intellij-community,blademainer/intellij-community,hurricup/intellij-community,signed/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,izonder/intellij-community,hurricup/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,FHannes/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,slisson/intellij-community,adedayo/intellij-community,jexp/idea2,salguarnieri/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,xfournet/intellij-community,slisson/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,caot/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,supersven/intellij-community,retomerz/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,fnouama/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,blademainer/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,slisson/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,holmes/intellij-community,gnuhub/intellij-community,semonte/intellij-community,hurricup/intellij-community,fitermay/intellij-community,retomerz/intellij-community,kdwink/intellij-community,apixandru/intellij-community,jexp/idea2,xfournet/intellij-community,Lekanich/intellij-community,semonte/intellij-community,amith01994/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,amith01994/intellij-community,xfournet/intellij-community,ryano144/intellij-community,amith01994/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,holmes/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,ryano144/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,jagguli/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,izonder/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,holmes/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,fnouama/intellij-community,signed/intellij-community,nicolargo/intellij-community,signed/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ibinti/intellij-community,jagguli/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ryano144/intellij-community,samthor/intellij-community,ahb0327/intellij-community,kool79/intellij-community,adedayo/intellij-community,da1z/intellij-community,allotria/intellij-community,joewalnes/idea-community,nicolargo/intellij-community,caot/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,samthor/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,kool79/intellij-community,kdwink/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,supersven/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,hurricup/intellij-community,jexp/idea2,allotria/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,consulo/consulo,lucafavatella/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,kool79/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,allotria/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,xfournet/intellij-community,slisson/intellij-community,joewalnes/idea-community,joewalnes/idea-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ibinti/intellij-community,blademainer/intellij-community,clumsy/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,jexp/idea2,joewalnes/idea-community,orekyuu/intellij-community,xfournet/intellij-community,ibinti/intellij-community,samthor/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,slisson/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,robovm/robovm-studio,adedayo/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ernestp/consulo,jagguli/intellij-community,adedayo/intellij-community,izonder/intellij-community,signed/intellij-community,nicolargo/intellij-community,signed/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,holmes/intellij-community,hurricup/intellij-community,clumsy/intellij-community,kool79/intellij-community,akosyakov/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,kdwink/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,apixandru/intellij-community,samthor/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,caot/intellij-community,kool79/intellij-community,slisson/intellij-community,apixandru/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,jexp/idea2,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,kool79/intellij-community,allotria/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,fnouama/intellij-community,semonte/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,dslomov/intellij-community,da1z/intellij-community,dslomov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,fitermay/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,slisson/intellij-community,holmes/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,caot/intellij-community,Distrotech/intellij-community,holmes/intellij-community,ernestp/consulo,Distrotech/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,consulo/consulo,ernestp/consulo,idea4bsd/idea4bsd,gnuhub/intellij-community,kool79/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,apixandru/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,consulo/consulo,SerCeMan/intellij-community,retomerz/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,blademainer/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,ryano144/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fnouama/intellij-community,diorcety/intellij-community,semonte/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community
|
package org.jetbrains.plugins.groovy.lang.completion;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import org.jetbrains.plugins.groovy.CompositeCompletionData;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.util.TestUtils;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* author ven
*/
public abstract class CompletionTestBase extends JavaCodeInsightFixtureTestCase {
protected void doTest() throws Throwable {
final List<String> stringList = TestUtils.readInput(getTestDataPath() + "/" + getTestName(true) + ".test");
final String fileName = getTestName(true) + "." + getExtension();
myFixture.addFileToProject(fileName, stringList.get(0));
myFixture.configureByFile(fileName);
CompositeCompletionData.restrictCompletion(addReferenceVariants(), addKeywords());
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = false;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
String result = "";
try {
myFixture.completeBasic();
final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
if (lookup != null) {
List<LookupElement> items = lookup.getItems();
Collections.sort(items, new Comparator<LookupElement>() {
public int compare(LookupElement o1, LookupElement o2) {
return o1.getLookupString().compareTo(o2.getLookupString());
}
});
result = "";
for (LookupElement item : items) {
result = result + "\n" + item.getLookupString();
}
result = result.trim();
LookupManager.getInstance(myFixture.getProject()).hideActiveLookup();
}
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = true;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = old;
CompositeCompletionData.restrictCompletion(true, true);
}
assertEquals(stringList.get(1), result);
}
protected String getExtension() {
return "groovy";
}
protected FileType getFileType() {
return GroovyFileType.GROOVY_FILE_TYPE;
}
protected boolean addKeywords() {
return true;
}
protected boolean addReferenceVariants() {
return true;
}
}
|
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java
|
package org.jetbrains.plugins.groovy.lang.completion;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import org.jetbrains.plugins.groovy.CompositeCompletionData;
import org.jetbrains.plugins.groovy.GroovyFileType;
import org.jetbrains.plugins.groovy.util.TestUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Comparator;
/**
* author ven
*/
public abstract class CompletionTestBase extends JavaCodeInsightFixtureTestCase {
protected void doTest() throws Throwable {
final List<String> stringList = TestUtils.readInput(getTestDataPath() + "/" + getTestName(true) + ".test");
final String fileName = getTestName(true) + "." + getExtension();
myFixture.addFileToProject(fileName, stringList.get(0));
myFixture.configureByFile(fileName);
CompositeCompletionData.restrictCompletion(addReferenceVariants(), addKeywords());
boolean old = CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = false;
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = false;
String result = "";
try {
myFixture.completeBasic();
final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myFixture.getEditor());
if (lookup != null) {
LookupElement[] items = lookup.getItems();
Arrays.sort(items, new Comparator<LookupElement>() {
public int compare(LookupElement o1, LookupElement o2) {
return o1.getLookupString().compareTo(o2.getLookupString());
}
});
result = "";
for (LookupElement item : items) {
result = result + "\n" + item.getLookupString();
}
result = result.trim();
LookupManager.getInstance(myFixture.getProject()).hideActiveLookup();
}
}
finally {
CodeInsightSettings.getInstance().AUTOCOMPLETE_ON_CODE_COMPLETION = true;
CodeInsightSettings.getInstance().AUTOCOMPLETE_COMMON_PREFIX = old;
CompositeCompletionData.restrictCompletion(true, true);
}
assertEquals(stringList.get(1), result);
}
protected String getExtension() {
return "groovy";
}
protected FileType getFileType() {
return GroovyFileType.GROOVY_FILE_TYPE;
}
protected boolean addKeywords() {
return true;
}
protected boolean addReferenceVariants() {
return true;
}
}
|
introduce LookupArranger to support different sorting strategies in lookups
|
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/completion/CompletionTestBase.java
|
introduce LookupArranger to support different sorting strategies in lookups
|
|
Java
|
apache-2.0
|
d193bd71a46d92dc9dd7147674db79ffdb2f3293
| 0
|
dzdenya/java_pft
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import java.util.List;
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void returnToHomePage() {
click(By.linkText("home page"));
}
public void returnToHomePageAfterDeletiong() {
click(By.linkText("home"));
}
public void submitContactCreation() {
click(By.name("submit"));
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("lastname"), contactData.getLastname());
type(By.name("address"), contactData.getAddress());
type(By.name("mobile"), contactData.getMobilePhone());
type(By.name("home"), contactData.getHomePhone());
type(By.name("work"), contactData.getWorkPhone());
type(By.name("email"), contactData.getEmail());
attach(By.name("photo"), contactData.getPhoto());
if (creation) {
if (contactData.getGroups().size() > 0) {
Assert.assertTrue(contactData.getGroups().size() == 1);
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroups().iterator().next().getName());
}
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
}
public void modifyContact(ContactData contact) {
initContactModificationById(contact.getId());
fillContactForm(contact, false);
submitContactModification();
contactCache = null;
returnToHomePage();
}
public void deleteContact(List<ContactData> before) {
selectContact(before.size() - 1);
deleteContact();
closeAlert();
returnToHomePageAfterDeletiong();
}
public void deleteContact(ContactData deleteContact) {
selectContactById(deleteContact.getId());
deleteContact();
closeAlert();
contactCache = null;
returnToHomePageAfterDeletiong();
}
public void closeAlert() {
wd.switchTo().alert().accept();
}
public void initContactGreation() {
click(By.linkText("add new"));
}
public void deleteContact() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
}
public void selectContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
private void selectContactById(int id) {
wd.findElement(By.cssSelector("input[id='" + id + "']")).click();
}
public void initContactModification(int index) {
wd.findElements(By.cssSelector("img[alt = 'Edit']")).get(index).click();
}
public void initContactModificationById(int id) {
// wd.findElement(By.cssSelector("input[id='" + id + "']"));
// wd.findElement(By.xpath(".//td[8]")).click();
wd.findElement(By.cssSelector(String.format("a[href='edit.php?id=%s']", id))).click();
}
public void initContactInfoDetails(int id) {
wd.findElement(By.cssSelector(String.format("a[href='view.php?id=%s']", id))).click();
}
public void submitContactModification() {
click(By.name("update"));
}
public int contactCount() {
return wd.findElements(By.name("selected[]")).size();
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
public void create(ContactData contact, boolean b) {
fillContactForm(contact, b);
submitContactCreation();
contactCache = null;
returnToHomePage();
}
private Contacts contactCache = null;
public Contacts all(){
if (contactCache != null){
return new Contacts(contactCache);
}
contactCache = new Contacts();
List<WebElement> elements = wd.findElements(By.xpath("//tr[@name = 'entry']"));
for (WebElement element: elements) {
List<WebElement> cells = element.findElements(By.tagName("td"));
int id = Integer.parseInt( element.findElement(By.tagName("input")).getAttribute("value"));
String lastname = cells.get(1).getText();
String firstname = cells.get(2).getText();
String address = cells.get(3).getText();
String allEmails = cells.get(4).getText();
String allPhones = cells.get(5).getText();
contactCache.add(new ContactData()
.withId(id)
.withLastname(lastname)
.withFirstname(firstname)
.withAddress(address)
.withAllEmails(allEmails)
.withAllPhones(allPhones));
}
return new Contacts(contactCache);
}
public ContactData infoFromEditForm(ContactData contact) {
initContactModificationById(contact.getId());
String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
String lastname = wd.findElement(By.name("lastname")).getAttribute("value");
String address = wd.findElement(By.name("address")).getAttribute("value");
String home = wd.findElement(By.name("home")).getAttribute("value");
String mobile = wd.findElement(By.name("mobile")).getAttribute("value");
String work = wd.findElement(By.name("work")).getAttribute("value");
String email = wd.findElement(By.name("email")).getAttribute("value");
String email2 = wd.findElement(By.name("email2")).getAttribute("value");
String email3 = wd.findElement(By.name("email3")).getAttribute("value");
wd.navigate().back();
return new ContactData()
.withId(contact.getId())
.withFirstname(firstname)
.withLastname(lastname)
.withAddress(address)
.withHomePhone(home)
.withMobilePhone(mobile)
.withWorkPhone(work)
.withEmail(email)
.withEmail2(email2)
.withEmail3(email3);
}
public ContactData infoFromEditFormForDetails(ContactData contact) {
initContactModificationById(contact.getId());
String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
String lastname = wd.findElement(By.name("lastname")).getAttribute("value");
String address = wd.findElement(By.name("address")).getAttribute("value");
String home = wd.findElement(By.name("home")).getAttribute("value");
String mobile = wd.findElement(By.name("mobile")).getAttribute("value");
String work = wd.findElement(By.name("work")).getAttribute("value");
String email = wd.findElement(By.name("email")).getAttribute("value");
String email2 = wd.findElement(By.name("email2")).getAttribute("value");
String email3 = wd.findElement(By.name("email3")).getAttribute("value");
if (! home.equals("")){
home = "H:" + home;
}
if (! mobile.equals("")){
mobile = "M:" + mobile;
}
if (! work.equals("")){
work = "W:" + work;
}
wd.navigate().back();
return new ContactData()
.withId(contact.getId())
.withFirstname(firstname)
.withLastname(lastname)
.withAddress(address)
.withHomePhone(home)
.withMobilePhone(mobile)
.withWorkPhone(work)
.withEmail(email)
.withEmail2(email2)
.withEmail3(email3);
}
public ContactData infoFromDetailsForm(ContactData contact) {
initContactInfoDetails(contact.getId());
String allDetails = wd.findElement(By.xpath("//*[@id='content']")).getText();
wd.navigate().back();
return new ContactData().withId(contact.getId()).withAllDetails(allDetails);
}
}
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import java.util.ArrayList;
import java.util.List;
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void returnToHomePage() {
click(By.linkText("home page"));
}
public void returnToHomePageAfterDeletiong() {
click(By.linkText("home"));
}
public void submitContactCreation() {
click(By.name("submit"));
}
public void fillContactForm(ContactData contactData, boolean creation) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("lastname"), contactData.getLastname());
type(By.name("address"), contactData.getAddress());
type(By.name("mobile"), contactData.getMobilePhone());
type(By.name("home"), contactData.getHomePhone());
type(By.name("work"), contactData.getWorkPhone());
type(By.name("email"), contactData.getEmail());
// attach(By.name("photo"), contactData.getPhoto());
if (creation) {
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
}
public void modifyContact(ContactData contact) {
initContactModificationById(contact.getId());
fillContactForm(contact, false);
submitContactModification();
contactCache = null;
returnToHomePage();
}
public void deleteContact(List<ContactData> before) {
selectContact(before.size() - 1);
deleteContact();
closeAlert();
returnToHomePageAfterDeletiong();
}
public void deleteContact(ContactData deleteContact) {
selectContactById(deleteContact.getId());
deleteContact();
closeAlert();
contactCache = null;
returnToHomePageAfterDeletiong();
}
public void closeAlert() {
wd.switchTo().alert().accept();
}
public void initContactGreation() {
click(By.linkText("add new"));
}
public void deleteContact() {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
}
public void selectContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
private void selectContactById(int id) {
wd.findElement(By.cssSelector("input[id='" + id + "']")).click();
}
public void initContactModification(int index) {
wd.findElements(By.cssSelector("img[alt = 'Edit']")).get(index).click();
}
public void initContactModificationById(int id) {
// wd.findElement(By.cssSelector("input[id='" + id + "']"));
// wd.findElement(By.xpath(".//td[8]")).click();
wd.findElement(By.cssSelector(String.format("a[href='edit.php?id=%s']", id))).click();
}
public void initContactInfoById(int id) {
// wd.findElement(By.cssSelector("input[id='" + id + "']"));
// wd.findElement(By.xpath(".//td[7]")).click();
wd.findElement(By.cssSelector(String.format("a[href='view.php?id=%s']", id))).click();
}
public void submitContactModification() {
click(By.name("update"));
}
public boolean isThereAContact() {
return isElementPresent(By.name("selected[]"));
}
public void create(ContactData contact, boolean b) {
fillContactForm(contact, b);
submitContactCreation();
contactCache = null;
returnToHomePage();
}
public ContactData infoFromEditForm(ContactData contact) {
initContactModificationById(contact.getId());
String firstname = wd.findElement(By.name("firstname")).getAttribute("value");
String lastname = wd.findElement(By.name("lastname")).getAttribute("value");
String home = wd.findElement(By.name("home")).getAttribute("value");
String mobile = wd.findElement(By.name("mobile")).getAttribute("value");
String work = wd.findElement(By.name("work")).getAttribute("value");
String email = wd.findElement(By.name("email")).getAttribute("value");
String address = wd.findElement(By.name("address")).getAttribute("value");
wd.navigate().back();
return new ContactData()
.withId(contact.getId())
.withFirstname(firstname)
.withLastname(lastname)
.withHomePhone(home)
.withMobilePhone(mobile)
.withWorkPhone(work)
.withEmail(email)
.withAddress(address);
}
public int contactCount() {
return wd.findElements(By.name("selected[]")).size();
}
private Contacts contactCache = null;
public Contacts all(){
if (contactCache != null){
return new Contacts(contactCache);
}
contactCache = new Contacts();
List<WebElement> elements = wd.findElements(By.xpath("//tr[@name = 'entry']"));
for (WebElement element: elements) {
List<WebElement> cells = element.findElements(By.tagName("td"));
int id = Integer.parseInt( element.findElement(By.tagName("input")).getAttribute("value"));
String lastname = cells.get(1).getText();
String firstname = cells.get(2).getText();
String address = cells.get(3).getText();
String email = cells.get(4).getText();
// String[] phones = element.findElement(By.xpath(".//td[6]")).getText().split("\n");
String allPhones = cells.get(5).getText();
contactCache.add(new ContactData()
.withId(id)
.withLastname(lastname)
.withFirstname(firstname)
.withAddress(address)
.withEmail(email)
.withAllPhones(allPhones));
}
return new Contacts(contactCache);
}
public ContactData infoContactDetails(ContactData contact) {
initContactInfoById(contact.getId());
String allDetails = wd.findElement(By.xpath("//*[@id='content']")).getText();
// String[] text = wd.findElement(By.xpath("//*[@id='content']")).getText().split("\n");
System.out.println(allDetails);
wd.navigate().back();
return new ContactData()
.withId(contact.getId())
.withAllDedails(allDetails);
}
}
|
Исправлены ошибки в ContactHelper
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
|
Исправлены ошибки в ContactHelper
|
|
Java
|
apache-2.0
|
4bab0f18421951acbf17314102e17631d7e4d272
| 0
|
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.slime.ArrayTraverser;
import com.yahoo.slime.Inspector;
import com.yahoo.vespa.config.SlimeUtils;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ConfigChangeActions;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud;
import com.yahoo.vespa.hosted.controller.api.integration.routing.RoutingEndpoint;
import com.yahoo.vespa.hosted.controller.api.integration.stubs.MockTesterCloud;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.application.ApplicationVersion;
import com.yahoo.vespa.hosted.controller.integration.RoutingGeneratorMock;
import com.yahoo.vespa.hosted.controller.maintenance.JobControl;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunner;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunnerTest;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.log.LogLevel.DEBUG;
import static com.yahoo.vespa.hosted.controller.deployment.InternalStepRunner.testerOf;
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.aborted;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author jonmv
* @author freva
*/
public class InternalStepRunnerTest {
private static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
private static final ApplicationId appId = ApplicationId.from("tenant", "application", "default");
private DeploymentTester tester;
private JobController jobs;
private RoutingGeneratorMock routing;
private MockTesterCloud cloud;
private JobRunner runner;
private Application app() { return tester.application(appId); }
@Before
public void setup() {
tester = new DeploymentTester();
tester.createApplication(appId.application().value(), appId.tenant().value(), 1, 1L);
jobs = tester.controller().jobController();
routing = tester.controllerTester().routingGenerator();
cloud = new MockTesterCloud();
runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()),
JobRunnerTest.inThreadExecutor(), new InternalStepRunner(tester.controller(), cloud));
routing.putEndpoints(new DeploymentId(null, null), Collections.emptyList()); // Turn off default behaviour for the mock.
// Get deployment job logs to stderr.
Logger.getLogger(InternalStepRunner.class.getName()).setLevel(DEBUG);
Logger.getLogger("").setLevel(DEBUG);
Logger.getLogger("").getHandlers()[0].setLevel(DEBUG);
}
@Test
public void canRegisterAndRunDirectly() {
deployNewSubmission();
deployNewPlatform(new Version("7.1"));
}
@Test
public void canSwitchFromScrewdriver() {
// Deploys a default application package with default build number.
tester.deployCompletely(app(), applicationPackage);
setEndpoints(appId, JobType.productionUsWest1.zone(tester.controller().system()));
deployNewSubmission();
deployNewPlatform(new Version("7.1"));
}
/** Submits a new application, and returns the version of the new submission. */
private ApplicationVersion newSubmission(ApplicationId id) {
ApplicationVersion version = jobs.submit(id, BuildJob.defaultSourceRevision, applicationPackage.zippedContent(), new byte[0]);
tester.applicationStore().putApplicationPackage(appId, version.id(), applicationPackage.zippedContent());
tester.applicationStore().putTesterPackage(testerOf(appId), version.id(), new byte[0]);
return version;
}
/** Sets a single endpoint in the routing mock; this matches that required for the tester. */
private void setEndpoints(ApplicationId id, ZoneId zone) {
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https://%s--%s--%s.%s.%s.vespa:43",
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
false)));
}
/** Completely deploys a new submission. */
private void deployNewSubmission() {
ApplicationVersion applicationVersion = newSubmission(appId);
assertFalse(app().deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(applicationVersion)));
assertEquals(applicationVersion, app().change().application().get());
assertFalse(app().change().platform().isPresent());
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
runJob(JobType.productionUsWest1);
}
/** Completely deploys the given, new platform. */
private void deployNewPlatform(Version version) {
tester.upgradeSystem(version);
assertFalse(app().deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version)));
assertEquals(version, app().change().platform().get());
assertFalse(app().change().application().isPresent());
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
runJob(JobType.productionUsWest1);
assertTrue(app().productionDeployments().values().stream()
.allMatch(deployment -> deployment.version().equals(version)));
assertTrue(tester.configServer().nodeRepository()
.list(JobType.productionUsWest1.zone(tester.controller().system()), appId).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(app().change().isPresent());
}
/** Runs the whole of the given job, successfully. */
private void runJob(JobType type) {
tester.readyJobTrigger().maintain();
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertFalse(run.status() == aborted);
ZoneId zone = type.zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(appId, zone);
// First steps are always deployments.
runner.run();
if (type == JobType.stagingTest) { // Do the initial deployment and installation of the real application.
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installInitialReal));
tester.configServer().convergeServices(appId, zone);
run.versions().sourcePlatform().ifPresent(version -> tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), version));
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installInitialReal));
}
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), run.versions().targetPlatform());
runner.run();
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installReal));
tester.configServer().convergeServices(appId, zone);
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installReal));
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installTester));
tester.configServer().convergeServices(testerOf(appId), zone);
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installTester));
// All installation is complete. We now need endpoints, and the tests will then run, and cleanup finish.
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.startTests));
setEndpoints(testerOf(appId), zone);
runner.run();
if ( ! run.versions().sourceApplication().isPresent() || ! type.isProduction()) {
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.startTests));
setEndpoints(appId, zone);
}
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.endTests));
cloud.set("Awesome!".getBytes(), TesterCloud.Status.SUCCESS);
runner.run();
assertTrue(jobs.run(run.id()).get().hasEnded());
assertFalse(jobs.run(run.id()).get().hasFailed());
assertEquals(type.isProduction(), app().deployments().containsKey(zone));
assertTrue(tester.configServer().nodeRepository().list(zone, testerOf(appId)).isEmpty());
if ( ! app().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(testerOf(appId), zone));
}
@Test
public void refeedRequirementBlocksDeployment() {
RunId id = newRun(JobType.productionUsWest1);
tester.configServer().setConfigChangeActions(new ConfigChangeActions(Collections.emptyList(),
Collections.singletonList(new RefeedAction("Refeed",
false,
"doctype",
"cluster",
Collections.emptyList(),
Collections.singletonList("Refeed it!")))));
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.deployReal));
}
@Test
public void restartsServicesAndWaitsForRestartAndReboot() {
RunId id = newRun(JobType.productionUsWest1);
ZoneId zone = id.type().zone(tester.controller().system());
HostName host = tester.configServer().hostFor(appId, zone);
tester.configServer().setConfigChangeActions(new ConfigChangeActions(Collections.singletonList(new RestartAction("cluster",
"container",
"search",
Collections.singletonList(new ServiceInfo("queries",
"search",
"config",
host.value())),
Collections.singletonList("Restart it!"))),
Collections.emptyList()));
runner.run();
assertEquals(succeeded, jobs.run(id).get().steps().get(Step.deployReal));
tester.configServer().convergeServices(appId, zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doRestart(new DeploymentId(appId, zone), Optional.of(host));
tester.configServer().nodeRepository().requestReboot(new DeploymentId(appId, zone), Optional.of(host));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.clock().advance(InternalStepRunner.installationTimeout.plus(Duration.ofSeconds(1)));
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.installReal));
}
@Test
public void waitsForEndpointsAndTimesOut() {
newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(appId, JobType.stagingTest.zone(tester.controller().system()));
runner.run();
tester.configServer().convergeServices(appId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(appId, JobType.stagingTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.stagingTest.zone(tester.controller().system()));
runner.run();
// Tester fails to show up for system tests, and the real deployment for staging tests.
setEndpoints(appId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerOf(appId), JobType.stagingTest.zone(tester.controller().system()));
tester.clock().advance(InternalStepRunner.endpointTimeout.plus(Duration.ofSeconds(1)));
runner.run();
assertEquals(failed, jobs.last(appId, JobType.systemTest).get().steps().get(Step.startTests));
assertEquals(failed, jobs.last(appId, JobType.stagingTest).get().steps().get(Step.startTests));
}
@Test
public void testsFailIfEndpointsAreGone() {
RunId id = startSystemTestTests();
cloud.set(new byte[0], TesterCloud.Status.NOT_STARTED);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
}
@Test
public void testsFailIfTestsFailRemotely() {
RunId id = startSystemTestTests();
cloud.set("Failure!".getBytes(), TesterCloud.Status.FAILURE);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tests failed.", "Failure!");
}
@Test
public void testsFailIfTestsErr() {
RunId id = startSystemTestTests();
cloud.set("Error!".getBytes(), TesterCloud.Status.ERROR);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tester failed running its tests!", "Error!");
}
@Test
public void testsSucceedWhenTheyDoRemotely() {
RunId id = startSystemTestTests();
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
assertEquals(URI.create(routing.endpoints(new DeploymentId(testerOf(appId), JobType.systemTest.zone(tester.controller().system()))).get(0).getEndpoint()),
cloud.testerUrl());
Inspector configObject = SlimeUtils.jsonToSlime(cloud.config()).get();
assertEquals(appId.serializedForm(), configObject.field("application").asString());
assertEquals(JobType.systemTest.zone(tester.controller().system()).value(), configObject.field("zone").asString());
assertEquals(tester.controller().system().name(), configObject.field("system").asString());
assertEquals(1, configObject.field("endpoints").children());
assertEquals(1, configObject.field("endpoints").field(JobType.systemTest.zone(tester.controller().system()).value()).entries());
configObject.field("endpoints").field(JobType.systemTest.zone(tester.controller().system()).value()).traverse((ArrayTraverser) (__, endpoint) ->
assertEquals(routing.endpoints(new DeploymentId(appId, JobType.systemTest.zone(tester.controller().system()))).get(0).getEndpoint(), endpoint.asString()));
cloud.set("Success!".getBytes(), TesterCloud.Status.SUCCESS);
runner.run();
assertEquals(succeeded, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tests still running ...", "Tests completed successfully.", "Success!");
}
private void assertLogMessages(RunId id, Step step, String... messages) {
String pattern = Stream.of(messages)
.map(message -> "\\[[^]]*] : " + message + "\n")
.collect(Collectors.joining());
String logs = new String(jobs.details(id).get().get(step).get());
if ( ! logs.matches(pattern))
throw new AssertionError("Expected a match for\n'''\n" + pattern + "\n'''\nbut got\n'''\n" + logs + "\n'''");
}
private RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(appId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(appId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
private RunId newRun(JobType type) {
assertFalse(app().deploymentJobs().builtInternally()); // Use this only once per test.
newSubmission(appId);
tester.readyJobTrigger().maintain();
if (type.isProduction()) {
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
tester.readyJobTrigger().maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
@Test
public void generates_correct_services_xml_test() {
assertFile("test_runner_services.xml-cd", new String(InternalStepRunner.servicesXml(SystemName.cd)));
}
private void assertFile(String resourceName, String actualContent) {
try {
Path path = Paths.get("src/test/resources/").resolve(resourceName);
String expectedContent = new String(Files.readAllBytes(path));
assertEquals(expectedContent, actualContent);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
|
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.slime.ArrayTraverser;
import com.yahoo.slime.Inspector;
import com.yahoo.vespa.config.SlimeUtils;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ConfigChangeActions;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RefeedAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.RestartAction;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.configserverbindings.ServiceInfo;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud;
import com.yahoo.vespa.hosted.controller.api.integration.routing.RoutingEndpoint;
import com.yahoo.vespa.hosted.controller.api.integration.stubs.MockTesterCloud;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.application.ApplicationVersion;
import com.yahoo.vespa.hosted.controller.integration.RoutingGeneratorMock;
import com.yahoo.vespa.hosted.controller.maintenance.JobControl;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunner;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunnerTest;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.log.LogLevel.DEBUG;
import static com.yahoo.vespa.hosted.controller.deployment.InternalStepRunner.testerOf;
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.aborted;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author jonmv
* @author freva
*/
public class InternalStepRunnerTest {
private static final ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.environment(Environment.prod)
.region("us-west-1")
.build();
private static final ApplicationId appId = ApplicationId.from("tenant", "application", "default");
private DeploymentTester tester;
private JobController jobs;
private RoutingGeneratorMock routing;
private MockTesterCloud cloud;
private JobRunner runner;
private Application app() { return tester.application(appId); }
@Before
public void setup() {
tester = new DeploymentTester();
tester.createApplication(appId.application().value(), appId.tenant().value(), 1, 1L);
jobs = tester.controller().jobController();
routing = tester.controllerTester().routingGenerator();
cloud = new MockTesterCloud();
runner = new JobRunner(tester.controller(), Duration.ofDays(1), new JobControl(tester.controller().curator()),
JobRunnerTest.inThreadExecutor(), new InternalStepRunner(tester.controller(), cloud));
routing.putEndpoints(new DeploymentId(null, null), Collections.emptyList()); // Turn off default behaviour for the mock.
// Get deployment job logs to stderr.
Logger.getLogger(InternalStepRunner.class.getName()).setLevel(DEBUG);
Logger.getLogger("").setLevel(DEBUG);
Logger.getLogger("").getHandlers()[0].setLevel(DEBUG);
}
@Test
public void canRegisterAndRunDirectly() {
deployNewSubmission();
deployNewPlatform(new Version("7.1"));
}
@Test
public void canSwitchFromScrewdriver() {
// Deploys a default application package with default build number.
tester.deployCompletely(app(), applicationPackage);
setEndpoints(appId, JobType.productionUsWest1.zone(tester.controller().system()));
deployNewSubmission();
deployNewPlatform(new Version("7.1"));
}
/** Submits a new application, and returns the version of the new submission. */
private ApplicationVersion newSubmission(ApplicationId id) {
ApplicationVersion version = jobs.submit(id, BuildJob.defaultSourceRevision, applicationPackage.zippedContent(), new byte[0]);
tester.applicationStore().putApplicationPackage(appId, version.id(), applicationPackage.zippedContent());
tester.applicationStore().putTesterPackage(testerOf(appId), version.id(), new byte[0]);
return version;
}
/** Sets a single endpoint in the routing mock; this matches that required for the tester. */
private void setEndpoints(ApplicationId id, ZoneId zone) {
routing.putEndpoints(new DeploymentId(id, zone),
Collections.singletonList(new RoutingEndpoint(String.format("https://%s--%s--%s.%s.%s.vespa:43",
id.instance().value(),
id.application().value(),
id.tenant().value(),
zone.region().value(),
zone.environment().value()),
false)));
}
/** Completely deploys a new submission. */
private void deployNewSubmission() {
ApplicationVersion applicationVersion = newSubmission(appId);
assertFalse(app().deployments().values().stream()
.anyMatch(deployment -> deployment.applicationVersion().equals(applicationVersion)));
assertEquals(applicationVersion, app().change().application().get());
assertFalse(app().change().platform().isPresent());
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
runJob(JobType.productionUsWest1);
}
/** Completely deploys the given, new platform. */
private void deployNewPlatform(Version version) {
tester.upgradeSystem(version);
assertFalse(app().deployments().values().stream()
.anyMatch(deployment -> deployment.version().equals(version)));
assertEquals(version, app().change().platform().get());
assertFalse(app().change().application().isPresent());
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
runJob(JobType.productionUsWest1);
assertTrue(app().productionDeployments().values().stream()
.allMatch(deployment -> deployment.version().equals(version)));
assertTrue(tester.configServer().nodeRepository()
.list(JobType.productionUsWest1.zone(tester.controller().system()), appId).stream()
.allMatch(node -> node.currentVersion().equals(version)));
assertFalse(app().change().isPresent());
}
/** Runs the whole of the given job, successfully. */
private void runJob(JobType type) {
tester.readyJobTrigger().maintain();
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
assertFalse(run.hasFailed());
assertFalse(run.status() == aborted);
ZoneId zone = type.zone(tester.controller().system());
DeploymentId deployment = new DeploymentId(appId, zone);
// First steps are always deployments.
runner.run();
if (type == JobType.stagingTest) { // Do the initial deployment and installation of the real application.
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installInitialReal));
tester.configServer().convergeServices(appId, zone);
run.versions().sourcePlatform().ifPresent(version -> tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), version));
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installInitialReal));
}
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doUpgrade(deployment, Optional.empty(), run.versions().targetPlatform());
runner.run();
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installReal));
tester.configServer().convergeServices(appId, zone);
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installReal));
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.installTester));
tester.configServer().convergeServices(testerOf(appId), zone);
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.installTester));
// All installation is complete. We now need endpoints, and the tests will then run, and cleanup finish.
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.startTests));
setEndpoints(testerOf(appId), zone);
runner.run();
if ( ! run.versions().sourceApplication().isPresent() || ! type.isProduction()) {
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.startTests));
setEndpoints(appId, zone);
}
runner.run();
assertEquals(Step.Status.succeeded, jobs.active(run.id()).get().steps().get(Step.startTests));
assertEquals(unfinished, jobs.active(run.id()).get().steps().get(Step.endTests));
cloud.set("Awesome!".getBytes(), TesterCloud.Status.SUCCESS);
runner.run();
assertTrue(jobs.run(run.id()).get().hasEnded());
assertFalse(jobs.run(run.id()).get().hasFailed());
assertEquals(type.isProduction(), app().deployments().containsKey(zone));
assertTrue(tester.configServer().nodeRepository().list(zone, testerOf(appId)).isEmpty());
if ( ! app().deployments().containsKey(zone))
routing.removeEndpoints(deployment);
routing.removeEndpoints(new DeploymentId(testerOf(appId), zone));
}
@Test
public void refeedRequirementBlocksDeployment() {
RunId id = newRun(JobType.productionUsWest1);
tester.configServer().setConfigChangeActions(new ConfigChangeActions(Collections.emptyList(),
Collections.singletonList(new RefeedAction("Refeed",
false,
"doctype",
"cluster",
Collections.emptyList(),
Collections.singletonList("Refeed it!")))));
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.deployReal));
}
@Test
public void restartsServicesAndWaitsForRestartAndReboot() {
RunId id = newRun(JobType.productionUsWest1);
ZoneId zone = id.type().zone(tester.controller().system());
HostName host = tester.configServer().hostFor(appId, zone);
tester.configServer().setConfigChangeActions(new ConfigChangeActions(Collections.singletonList(new RestartAction("cluster",
"container",
"search",
Collections.singletonList(new ServiceInfo("queries",
"search",
"config",
host.value())),
Collections.singletonList("Restart it!"))),
Collections.emptyList()));
runner.run();
assertEquals(succeeded, jobs.run(id).get().steps().get(Step.deployReal));
tester.configServer().convergeServices(appId, zone);
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.configServer().nodeRepository().doRestart(new DeploymentId(appId, zone), Optional.of(host));
tester.configServer().nodeRepository().requestReboot(new DeploymentId(appId, zone), Optional.of(host));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.installReal));
tester.clock().advance(InternalStepRunner.installationTimeout.plus(Duration.ofSeconds(1)));
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.installReal));
}
@Test
public void waitsForEndpointsAndTimesOut() {
newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(appId, JobType.stagingTest.zone(tester.controller().system()));
runner.run();
tester.configServer().convergeServices(appId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(appId, JobType.stagingTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.stagingTest.zone(tester.controller().system()));
runner.run();
// Tester fails to show up for system tests, and the real deployment for staging tests.
setEndpoints(appId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerOf(appId), JobType.stagingTest.zone(tester.controller().system()));
tester.clock().advance(InternalStepRunner.endpointTimeout.plus(Duration.ofSeconds(1)));
runner.run();
assertEquals(failed, jobs.last(appId, JobType.systemTest).get().steps().get(Step.startTests));
assertEquals(failed, jobs.last(appId, JobType.stagingTest).get().steps().get(Step.startTests));
}
@Test
public void testsFailIfEndpointsAreGone() {
RunId id = startSystemTestTests();
cloud.set(new byte[0], TesterCloud.Status.NOT_STARTED);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
}
@Test
public void testsFailIfTestsFailRemotely() {
RunId id = startSystemTestTests();
cloud.set("Failure!".getBytes(), TesterCloud.Status.FAILURE);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tests failed.", "Failure!");
}
@Test
public void testsFailIfTestsErr() {
RunId id = startSystemTestTests();
cloud.set("Error!".getBytes(), TesterCloud.Status.ERROR);
runner.run();
assertEquals(failed, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tester failed running its tests!", "Error!");
}
@Test
public void testsSucceedWhenTheyDoRemotely() {
RunId id = startSystemTestTests();
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
assertEquals(URI.create(routing.endpoints(new DeploymentId(testerOf(appId), JobType.systemTest.zone(tester.controller().system()))).get(0).getEndpoint()),
cloud.testerUrl());
Inspector configObject = SlimeUtils.jsonToSlime(cloud.config()).get();
assertEquals(appId.serializedForm(), configObject.field("application").asString());
assertEquals(JobType.systemTest.zone(tester.controller().system()).value(), configObject.field("zone").asString());
assertEquals(tester.controller().system().name(), configObject.field("system").asString());
assertEquals(1, configObject.field("endpoints").children());
assertEquals(1, configObject.field("endpoints").field(JobType.systemTest.zone(tester.controller().system()).value()).entries());
configObject.field("endpoints").field(JobType.systemTest.zone(tester.controller().system()).value()).traverse((ArrayTraverser) (__, endpoint) ->
assertEquals(routing.endpoints(new DeploymentId(appId, JobType.systemTest.zone(tester.controller().system()))).get(0).getEndpoint(), endpoint.asString()));
cloud.set("Success!".getBytes(), TesterCloud.Status.SUCCESS);
runner.run();
assertEquals(succeeded, jobs.run(id).get().steps().get(Step.endTests));
assertLogMessages(id, Step.endTests, "Tests still running ...", "Tests still running ...", "Tests completed successfully.", "Success!");
}
private void assertLogMessages(RunId id, Step step, String... messages) {
String pattern = Stream.of(messages)
.map(message -> "\\[[^]]*] : " + message + "\n")
.collect(Collectors.joining());
String logs = new String(jobs.details(id).get().get(step).get());
if ( ! logs.matches(pattern))
throw new AssertionError("Expected a match for\n'''\n" + pattern + "\n'''\nbut got\n'''\n" + logs + "\n'''");
}
private RunId startSystemTestTests() {
RunId id = newRun(JobType.systemTest);
runner.run();
tester.configServer().convergeServices(appId, JobType.systemTest.zone(tester.controller().system()));
tester.configServer().convergeServices(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
setEndpoints(appId, JobType.systemTest.zone(tester.controller().system()));
setEndpoints(testerOf(appId), JobType.systemTest.zone(tester.controller().system()));
runner.run();
assertEquals(unfinished, jobs.run(id).get().steps().get(Step.endTests));
return id;
}
private RunId newRun(JobType type) {
assertFalse(app().deploymentJobs().builtInternally()); // Use this only once per test.
newSubmission(appId);
tester.readyJobTrigger().maintain();
if (type.isProduction()) {
runJob(JobType.systemTest);
runJob(JobType.stagingTest);
tester.readyJobTrigger().maintain();
}
Run run = jobs.active().stream()
.filter(r -> r.id().type() == type)
.findAny()
.orElseThrow(() -> new AssertionError(type + " is not among the active: " + jobs.active()));
return run.id();
}
@Test
public void generates_correct_services_xml_test() {
assertFile("test_runner_services.xml-cd", new String(InternalStepRunner.servicesXml(SystemName.cd)));
}
private void assertFile(String resourceName, String actualContent) {
try {
Path path = Paths.get(getClass().getClassLoader().getResource(resourceName).getPath());
String expectedContent = new String(Files.readAllBytes(path));
assertEquals(expectedContent, actualContent);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
Avoid unreliable path lookup of test data
IntelliJ occasionally fails to lookup resources via class loader for me, haven't
been able to figure out the exact cause, but when it happens tests that use this
method fail with NPE.
Anyway, relative path should always work and this pattern is used elsewhere.
|
controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
|
Avoid unreliable path lookup of test data
|
|
Java
|
apache-2.0
|
d1c6c47f4ff09ac78e830cb2f61132c42c4941d5
| 0
|
metaborg/jsglr,metaborg/jsglr,metaborg/jsglr,metaborg/jsglr
|
/*
* Created on 03.des.2005
*
* Copyright (c) 2005, Karl Trygve Kalleberg <karltk near strategoxt.org>
*
* Licensed under the GNU Lesser General Public License, v2.1
*/
package org.spoofax.jsglr.client;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import org.spoofax.PushbackStringIterator;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.jsglr.shared.ArrayDeque;
import org.spoofax.jsglr.shared.BadTokenException;
import org.spoofax.jsglr.shared.SGLRException;
import org.spoofax.jsglr.shared.TokenExpectedException;
import org.spoofax.jsglr.shared.Tools;
public class SGLR {
private RecoveryPerformance performanceMeasuring;
private final Set<BadTokenException> collectedErrors = new LinkedHashSet<BadTokenException>();
public static final int EOF = ParseTable.NUM_CHARS;
static final int TAB_SIZE = 4;//8;
protected static boolean WORK_AROUND_MULTIPLE_LOOKAHEAD;
//Performance testing
private static long parseTime=0;
private static int parseCount=0;
protected Frame startFrame;
private long startTime;
protected volatile boolean asyncAborted;
protected Frame acceptingStack;
protected final ArrayDeque<Frame> activeStacks;
private ParseTable parseTable;
protected int currentToken;
protected int tokensSeen;
protected int lineNumber;
protected int columnNumber;
private final ArrayDeque<ActionState> forShifter;
private ArrayDeque<Frame> forActor;
private ArrayDeque<Frame> forActorDelayed;
private int maxBranches;
private int maxToken;
private int maxLine;
private int maxColumn;
private int maxTokenNumber;
private AmbiguityManager ambiguityManager;
protected Disambiguator disambiguator;
private int rejectCount;
private int reductionCount;
protected PushbackStringIterator currentInputStream;
private PathListPool pathCache = new PathListPool();
private ArrayDeque<Frame> activeStacksWorkQueue = new ArrayDeque<Frame>();
private ArrayDeque<Frame> recoverStacks;
private ParserHistory history;
private RecoveryConnector recoverIntegrator;
protected boolean useIntegratedRecovery;
public ParserHistory getHistory() {
return history;
}
private boolean fineGrainedOnRegion;
public void clearRecoverStacks(){
recoverStacks.clear(false);
}
public ArrayDeque<Frame> getRecoverStacks() {
return recoverStacks;
}
public Set<BadTokenException> getCollectedErrors() {
return collectedErrors;
}
/**
* Attempts to set a timeout for parsing.
* Default implementation throws an
* {@link UnsupportedOperationException}.
*
* @see org.spoofax.jsglr.io.SGLR#setTimeout(int)
*/
public void setTimeout(int timeout) {
throw new UnsupportedOperationException("Use org.spoofax.jsglr.io.SGLR for setting a timeout");
}
protected void initParseTimer() {
// Default does nothing (not supported by GWT)
}
@Deprecated
public SGLR(ITermFactory pf, ParseTable parseTable) {
this(new Asfix2TreeBuilder(pf), parseTable);
}
@Deprecated
public SGLR(ParseTable parseTable) {
this(new Asfix2TreeBuilder(), parseTable);
}
public SGLR(ITreeBuilder treeBuilder, ParseTable parseTable) {
assert parseTable != null;
// Init with a new factory for both serialized or BAF instances.
this.parseTable = parseTable;
activeStacks = new ArrayDeque<Frame>();
forActor = new ArrayDeque<Frame>();
forActorDelayed = new ArrayDeque<Frame>();
forShifter = new ArrayDeque<ActionState>();
disambiguator = new Disambiguator();
useIntegratedRecovery = false;
recoverIntegrator = null;
history = new ParserHistory();
setTreeBuilder(treeBuilder);
}
public void setUseStructureRecovery(boolean useRecovery, IRecoveryParser parser) {
useIntegratedRecovery = useRecovery;
recoverIntegrator = new RecoveryConnector(this, parser);
}
/**
* Enables error recovery based on region recovery and, if available, recovery rules.
* Does not enable bridge parsing.
*
* @see ParseTable#hasRecovers() Determines if the parse table supports recovery rules
*/
public final void setUseStructureRecovery(boolean useRecovery) {
setUseStructureRecovery(useRecovery, null);
}
protected void setFineGrainedOnRegion(boolean fineGrainedMode) {
fineGrainedOnRegion = fineGrainedMode;
recoverStacks = new ArrayDeque<Frame>();
}
@Deprecated
protected void setUseFineGrained(boolean useFG) {
recoverIntegrator.setUseFineGrained(useFG);
}
// FIXME: we have way to many of these accessors; does this have to be public?
// if not for normal use, it should at least be 'internalSet....'
@Deprecated
public void setCombinedRecovery(boolean useBP, boolean useFG,
boolean useOnlyFG) {
recoverIntegrator.setOnlyFineGrained(useOnlyFG);
recoverIntegrator.setUseBridgeParser(useBP);
recoverIntegrator.setUseFineGrained(useFG);
}
public RecoveryPerformance getPerformanceMeasuring() {
return performanceMeasuring;
}
/**
* @deprecated Use {@link #asyncCancel()} instead.
*/
@Deprecated
public void asyncAbort() {
asyncCancel();
}
/**
* Aborts an asynchronously running parse job, causing it to throw an exception.
*
* (Provides no guarantee that the parser is actually cancelled.)
*/
public void asyncCancel() {
asyncAborted = true;
}
public void asyncCancelReset() {
asyncAborted = false;
}
public static boolean isDebugging() {
return Tools.debugging;
}
public static boolean isLogging() {
return Tools.logging;
}
/**
* Initializes the active stacks. At the start of parsing there is only one
* active stack, and this stack contains the start symbol obtained from the
* parse table.
*
* @return top-level frame of the initial stack
*/
private Frame initActiveStacks() {
activeStacks.clear();
final Frame st0 = newStack(parseTable.getInitialState());
addStack(st0);
return st0;
}
@Deprecated
public Object parse(String fis) throws BadTokenException,
TokenExpectedException, ParseException, SGLRException {
return parse(fis, null, null);
}
@Deprecated
public final Object parse(String input, String filename) throws BadTokenException,
TokenExpectedException, ParseException, SGLRException {
return parse(input, filename, null);
}
/**
* Parses a string and constructs a new tree using the tree builder.
*
* @param input The input string.
* @param filename The source filename of the string, or null if not available.
* @param startSymbol The start symbol to use, or null if any applicable.
*/
public Object parse(String input, String filename, String startSymbol) throws BadTokenException, TokenExpectedException, ParseException,
SGLRException {
logBeforeParsing();
initParseVariables(input, filename);
startTime = System.currentTimeMillis();
initParseTimer();
Object result = sglrParse(startSymbol);
return result;
}
private Object sglrParse(String startSymbol)
throws BadTokenException, TokenExpectedException,
ParseException, SGLRException {
getPerformanceMeasuring().startParse();
try {
do {
readNextToken();
history.keepTokenAndState(this);
doParseStep();
} while (currentToken != SGLR.EOF && activeStacks.size() > 0);
if (acceptingStack == null) {
collectedErrors.add(createBadTokenException());
}
if(useIntegratedRecovery && acceptingStack==null){
recoverIntegrator.recover();
if(acceptingStack==null && activeStacks.size()>0) {
return sglrParse(startSymbol);
}
}
getPerformanceMeasuring().endParse(acceptingStack!=null);
} catch (final TaskCancellationException e) {
throw new ParseTimeoutException(this, currentToken, tokensSeen - 1, lineNumber,
columnNumber, collectedErrors);
} finally {
pathCache.reset();
activeStacks.clear(false);
activeStacksWorkQueue.clear(false);
forShifter.clear(false);
if (recoverStacks != null) recoverStacks.clear(false);
}
logAfterParsing();
final Link s = acceptingStack.findDirectLink(startFrame);
if (s == null) {
throw new ParseException(this, "Accepting stack has no link");
}
logParseResult(s);
Tools.debug("avoids: ", s.recoverCount);
//Tools.debug(s.label.toParseTree(parseTable));
if (parseTable.getTreeBuilder() instanceof NullTreeBuilder) {
return null;
} else {
return disambiguator.applyFilters(this, s.label, startSymbol, tokensSeen);
}
}
void readNextToken() {
logCurrentToken();
currentToken = getNextToken();
}
protected void doParseStep() {
logBeforeParseCharacter();
parseCharacter(); //applies reductions on active stack structure and fills forshifter
shifter(); //renewes active stacks with states in forshifter
}
private void initParseVariables(String input, String filename) {
forActor.clear();
forActorDelayed.clear();
forShifter.clear();
history.clear();
startFrame = initActiveStacks();
tokensSeen = 0;
columnNumber = 0;
lineNumber = 1;
currentInputStream = new PushbackStringIterator(input);
acceptingStack = null;
collectedErrors.clear();
history=new ParserHistory();
performanceMeasuring=new RecoveryPerformance();
parseTable.getTreeBuilder().initializeInput(input, filename);
PooledPathList.resetPerformanceCounters();
PathListPool.resetPerformanceCounters();
ambiguityManager = new AmbiguityManager(input.length());
pathCache.reset();
}
private BadTokenException createBadTokenException() {
final Frame singlePreviousStack = activeStacks.size() == 1 ? activeStacks.get(0) : null;
if (singlePreviousStack != null) {
Action action = singlePreviousStack.peek().getSingularAction();
if (action != null && action.getActionItems().length == 1) {
final StringBuilder expected = new StringBuilder();
do {
final int token = action.getSingularRange();
if (token == -1) {
break;
}
expected.append((char) token);
final ActionItem[] items = action.getActionItems();
if (!(items.length == 1 && items[0].type == ActionItem.SHIFT)) {
break;
}
final Shift shift = (Shift) items[0];
action = parseTable.getState(shift.nextState).getSingularAction();
} while (action != null);
if (expected.length() > 0) {
return new TokenExpectedException(this, expected.toString(), currentToken,
tokensSeen - 1, lineNumber, columnNumber);
}
}
}
return new BadTokenException(this, currentToken, tokensSeen - 1, lineNumber,
columnNumber);
}
private void shifter() {
logBeforeShifter();
clearActiveStacks();
final AbstractParseNode prod = parseTable.lookupProduction(currentToken);
while (forShifter.size() > 0) {
final ActionState as = forShifter.remove();
if (!parseTable.hasRejects() || !as.st.allLinksRejected()) {
Frame st1 = findStack(activeStacks, as.s);
if (st1 == null) {
st1 = newStack(as.s);
addStack(st1);
}
st1.addLink(as.st, prod, 1);
} else {
if (Tools.logging) {
Tools.logger("Shifter: skipping rejected stack with state ",
as.st.state.stateNumber);
}
}
}
logAfterShifter();
}
protected void addStack(Frame st1) {
if(Tools.tracing) {
TRACE("SG_AddStack() - " + st1.state.stateNumber);
}
activeStacks.addFirst(st1);
}
private void parseCharacter() {
logBeforeParseCharacter();
activeStacksWorkQueue.clear(true);
activeStacksWorkQueue.addAll(activeStacks);
clearForActorDelayed();
clearForShifter();
while (activeStacksWorkQueue.size() > 0 || forActor.size() > 0) {
final Frame st = pickStackNodeFromActivesOrForActor(activeStacksWorkQueue);
if (!st.allLinksRejected()) {
actor(st);
}
if(activeStacksWorkQueue.size() == 0 && forActor.size() == 0) {
fillForActorWithDelayedFrames(); //Fills foractor, clears foractor delayed
}
}
}
private void fillForActorWithDelayedFrames() {
if(Tools.tracing) {
TRACE("SG_ - both empty");
}
final ArrayDeque<Frame> empty = forActor;
forActor = forActorDelayed;
empty.clear(true);
forActorDelayed = empty;
}
private Frame pickStackNodeFromActivesOrForActor(ArrayDeque<Frame> actives) {
Frame st;
if(actives.size() > 0) {
if(Tools.tracing) {
TRACE("SG_ - took active");
}
st = actives.remove();
} else {
if(Tools.tracing) {
TRACE("SG_ - took foractor");
}
st = forActor.remove();
}
return st;
}
private void actor(Frame st) {
final State s = st.peek();
logBeforeActor(st, s);
for (final Action action : s.getActions()) {
if (action.accepts(currentToken)) {
for (final ActionItem ai : action.getActionItems()) {
switch (ai.type) {
case ActionItem.SHIFT: {
final Shift sh = (Shift) ai;
final ActionState actState = new ActionState(st, parseTable.getState(sh.nextState));
actState.currentToken = currentToken;
addShiftPair(actState); //Adds StackNode to forshifter
statsRecordParsers(); //sets some values un current parse state
break;
}
case ActionItem.REDUCE: {
final Reduce red = (Reduce) ai;
doReductions(st, red.production);
break;
}
case ActionItem.REDUCE_LOOKAHEAD: {
final ReduceLookahead red = (ReduceLookahead) ai;
if(checkLookahead(red)) {
if(Tools.tracing) {
TRACE("SG_ - ok");
}
doReductions(st, red.production);
}
break;
}
case ActionItem.ACCEPT: {
if (!st.allLinksRejected()) {
acceptingStack = st;
if (Tools.logging) {
Tools.logger("Reached the accept state");
}
}
break;
}
default:
throw new IllegalStateException("Unknown action type: " + ai.type);
}
}
}
}
if(Tools.tracing) {
TRACE("SG_ - actor done");
}
}
private boolean checkLookahead(ReduceLookahead red) {
return doCheckLookahead(red, red.getCharRanges(), 0);
}
private boolean doCheckLookahead(ReduceLookahead red, RangeList[] charClass, int pos) {
if(Tools.tracing) {
TRACE("SG_CheckLookAhead() - ");
}
final int c = currentInputStream.read();
// EOF
if(c == -1) {
return true;
}
boolean permit = true;
if(pos < charClass.length) {
permit = charClass[pos].within(c) ? false : doCheckLookahead(red, charClass, pos + 1);
}
currentInputStream.unread(c);
return permit;
}
private void addShiftPair(ActionState state) {
if(Tools.tracing) {
TRACE("SG_AddShiftPair() - " + state.s.stateNumber);
}
forShifter.add(state);
}
private void statsRecordParsers() {
if (forShifter.size() > maxBranches) {
maxBranches = forShifter.size();
maxToken = currentToken;
maxColumn = columnNumber;
maxLine = lineNumber;
maxTokenNumber = tokensSeen;
}
}
private void doReductions(Frame st, Production prod) {
if(!recoverModeOk(st, prod)) {
return;
}
final PooledPathList paths = pathCache.create();
//System.out.println(paths.size());
st.findAllPaths(paths, prod.arity);
//System.out.println(paths.size());
logBeforeDoReductions(st, prod, paths.size());
reduceAllPaths(prod, paths);
logAfterDoReductions();
paths.end();
}
private boolean recoverModeOk(Frame st, Production prod) {
return !prod.isRecoverProduction() || fineGrainedOnRegion;
}
private void doLimitedReductions(Frame st, Production prod, Link l) { //Todo: Look add sharing code with doReductions
if(!recoverModeOk(st, prod)) {
return;
}
final PooledPathList limitedPool = pathCache.create();
st.findLimitedPaths(limitedPool, prod.arity, l); //find paths containing the link
logBeforeLimitedReductions(st, prod, l, limitedPool);
reduceAllPaths(prod, limitedPool);
limitedPool.end();
}
private void reduceAllPaths(Production prod, PooledPathList paths) {
for(int i = 0; i < paths.size(); i++) {
final Path path = paths.get(i);
final AbstractParseNode[] kids = path.getParseNodes();
final Frame st0 = path.getEnd();
final State next = parseTable.go(st0.peek(), prod.label);
logReductionPath(prod, path, st0, next);
if(!prod.isRecoverProduction())
reducer(st0, next, prod, kids, path);
else
reducerRecoverProduction(st0, next, prod, kids, path);
}
if (asyncAborted) {
// Rethrown as ParseTimeoutException in SGLR.sglrParse()
throw new TaskCancellationException("Long-running parse job aborted");
}
}
private void reducer(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) {
assert(!prod.isRecoverProduction());
logBeforeReducer(s, prod, path.getLength());
increaseReductionCount();
final int length = path.getLength();
final int numberOfRecoveries = calcRecoverCount(prod, path);
final AbstractParseNode t = prod.apply(kids);
final Frame st1 = findStack(activeStacks, s);
if (st1 == null) {
// Found no existing stack with for state s; make new stack
addNewStack(st0, s, prod, length, numberOfRecoveries, t);
} else {
/* A stack with state s exists; check for ambiguities */
Link nl = st1.findDirectLink(st0);
if (nl != null) {
logAmbiguity(st0, prod, st1, nl);
if (prod.isRejectProduction()) {
nl.reject();
}
if(numberOfRecoveries == 0 && nl.recoverCount == 0 || nl.isRejected()) {
// UNDONE: this doesn't quite work yet
//boolean createdByRecursion=kids.length==1 && kids[0]==nl.label && nl.label instanceof Amb;
//if(!createdByRecursion){
createAmbNode(t, nl);
//actorOnActiveStacksOverNewLink(nl);//reductions on st1 should have used the Amb link, so they must be redone
//}
} else if (numberOfRecoveries < nl.recoverCount) {
nl.label = t;
nl.recoverCount = numberOfRecoveries;
actorOnActiveStacksOverNewLink(nl);
} else if (numberOfRecoveries == nl.recoverCount) {
nl.label = t;
}
} else {
nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
if (prod.isRejectProduction()) {
nl.reject();
increaseRejectCount();
}
logAddedLink(st0, st1, nl);
actorOnActiveStacksOverNewLink(nl);
}
}
if(Tools.tracing) {
TRACE_ActiveStacks();
TRACE("SG_ - reducer done");
}
}
private void reducerRecoverProduction(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) {
assert(prod.isRecoverProduction());
final int length = path.getLength();
final int numberOfRecoveries = calcRecoverCount(prod, path);
final AbstractParseNode t = prod.apply(kids);
final Frame stActive = findStack(activeStacks, s);
if(stActive!=null){
Link lnActive=stActive.findDirectLink(st0);
if(lnActive!=null){
return; //TODO: ambiguity
}
}
final Frame stRecover = findStack(recoverStacks, s);
if(stRecover!=null){
Link nlRecover = stRecover.findDirectLink(st0);
if(nlRecover!=null){
return; //TODO: ambiguity
}
nlRecover = stRecover.addLink(st0, t, length);
nlRecover.recoverCount = numberOfRecoveries;
return;
}
addNewRecoverStack(st0, s, prod, length, numberOfRecoveries, t);
}
private void createAmbNode(AbstractParseNode t, Link nl) {
nl.addAmbiguity(t, tokensSeen);
ambiguityManager.increaseAmbiguityCalls();
}
/**
* Found no existing stack with for state s; make new stack
*/
private void addNewStack(Frame st0, State s, Production prod, int length,
int numberOfRecoveries, AbstractParseNode t) {
final Frame st1 = newStack(s);
final Link nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
addStack(st1);
forActorDelayed.addFirst(st1);
if(Tools.tracing) {
TRACE("SG_AddStack() - " + st1.state.stateNumber);
}
if (prod.isRejectProduction()) {
if (Tools.logging) {
Tools.logger("Reject [new]");
}
nl.reject();
increaseRejectCount();
}
}
/**
* Found no existing stack with for state s; make new stack
*/
private void addNewRecoverStack(Frame st0, State s, Production prod, int length,
int numberOfRecoveries, AbstractParseNode t) {
if (!(fineGrainedOnRegion && !prod.isRejectProduction())) {
return;
}
final Frame st1 = newStack(s);
final Link nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
recoverStacks.addFirst(st1);
}
private void actorOnActiveStacksOverNewLink(Link nl) {
// Note: ActiveStacks can be modified inside doLimitedReductions
// new elements may be inserted at the beginning
final int sz = activeStacks.size();
for (int i = 0; i < sz; i++) {
// for(Frame st2 : activeStacks) {
if(Tools.tracing) {
TRACE("SG_ activeStack - ");
}
final int pos = activeStacks.size() - sz + i;
final Frame st2 = activeStacks.get(pos);
if (st2.allLinksRejected() || inReduceStacks(forActor, st2) || inReduceStacks(forActorDelayed, st2))
{
continue; //stacknode will find reduction in regular process
}
for (final Action action : st2.peek().getActions()) {
if (action.accepts(currentToken)) {
for (final ActionItem ai : action.getActionItems()) {
switch(ai.type) {
case ActionItem.REDUCE:
final Reduce red = (Reduce) ai;
doLimitedReductions(st2, red.production, nl);
break;
case ActionItem.REDUCE_LOOKAHEAD:
final ReduceLookahead red2 = (ReduceLookahead) ai;
if(checkLookahead(red2)) {
doLimitedReductions(st2, red2.production, nl);
}
break;
}
}
}
}
}
}
private int calcRecoverCount(Production prod, Path path) {
return path.getRecoverCount() + (prod.isRecoverProduction() ? 1 : 0);
}
private boolean inReduceStacks(Queue<Frame> q, Frame frame) {
if(Tools.tracing) {
TRACE("SG_InReduceStacks() - " + frame.state.stateNumber);
}
return q.contains(frame);
}
protected Frame newStack(State s) {
if(Tools.tracing) {
TRACE("SG_NewStack() - " + s.stateNumber);
}
return new Frame(s);
}
private void increaseReductionCount() {
reductionCount++;
}
protected void increaseRejectCount() {
rejectCount++;
}
protected int getRejectCount() {
return rejectCount;
}
Frame findStack(ArrayDeque<Frame> stacks, State s) {
if(Tools.tracing) {
TRACE("SG_FindStack() - " + s.stateNumber);
}
// We need only check the top frames of the active stacks.
if (Tools.debugging) {
Tools.debug("findStack() - ", dumpActiveStacks());
Tools.debug(" looking for ", s.stateNumber);
}
final int size = stacks.size();
for (int i = 0; i < size; i++) {
Frame stack = stacks.get(i);
if (stack.state.stateNumber == s.stateNumber) {
if(Tools.tracing) {
TRACE("SG_ - found stack");
}
return stack;
}
}
if(Tools.tracing) {
TRACE("SG_ - stack not found");
}
return null;
}
private int getNextToken() {
if(Tools.tracing) {
TRACE("SG_NextToken() - ");
}
final int ch = currentInputStream.read();
updateLineAndColumnInfo(ch);
if(ch == -1) {
return SGLR.EOF;
}
return ch;
}
protected void updateLineAndColumnInfo(int ch) {
tokensSeen++;
if (Tools.debugging) {
Tools.debug("getNextToken() - ", ch, "(", (char) ch, ")");
}
switch (ch) {
case '\n':
lineNumber++;
columnNumber = 0;
break;
case '\t':
columnNumber = (columnNumber / TAB_SIZE + 1) * TAB_SIZE;
break;
case -1:
break;
default:
columnNumber++;
}
}
@Deprecated
public void setFilter(boolean filter) {
getDisambiguator().setFilterAny(filter);
}
private void clearForShifter() {
forShifter.clear(true);
}
private void clearForActorDelayed() {
forActorDelayed.clear(true);
}
private void clearActiveStacks() {
activeStacks.clear(true);
}
public ParseTable getParseTable() {
return parseTable;
}
public void setTreeBuilder(ITreeBuilder treeBuilder) {
parseTable.setTreeBuilder(treeBuilder);
}
public ITreeBuilder getTreeBuilder() {
return parseTable.getTreeBuilder();
}
AmbiguityManager getAmbiguityManager() {
return ambiguityManager;
}
public Disambiguator getDisambiguator() {
return disambiguator;
}
public void setDisambiguator(Disambiguator disambiguator) {
this.disambiguator = disambiguator;
}
@Deprecated
public ITermFactory getFactory() {
return parseTable.getFactory();
}
protected int getReductionCount() {
return reductionCount;
}
protected int getRejectionCount() {
return rejectCount;
}
@Deprecated
public static void setWorkAroundMultipleLookahead(boolean value) {
WORK_AROUND_MULTIPLE_LOOKAHEAD = value;
}
////////////////////////////////////////////////////// Log functions ///////////////////////////////////////////////////////////////////////////////
private static int traceCallCount = 0;
static void TRACE(String string) {
System.err.println("[" + traceCallCount + "] " + string);
traceCallCount++;
}
private String dumpActiveStacks() {
final StringBuffer sb = new StringBuffer();
boolean first = true;
if (activeStacks == null) {
sb.append(" GSS unitialized");
} else {
sb.append("{").append(activeStacks.size()).append("} ");
for (final Frame f : activeStacks) {
if (!first) {
sb.append(", ");
}
sb.append(f.dumpStack());
first = false;
}
}
return sb.toString();
}
private void logParseResult(Link s) {
if (isDebugging()) {
Tools.debug("internal parse tree:\n", s.label);
}
if(Tools.tracing) {
TRACE("SG_ - internal tree: " + s.label);
}
if (Tools.measuring) {
final Measures m = new Measures();
//Tools.debug("Time (ms): " + (System.currentTimeMillis()-startTime));
m.setTime(System.currentTimeMillis() - startTime);
//Tools.debug("Red.: " + reductionCount);
m.setReductionCount(reductionCount);
//Tools.debug("Nodes: " + Frame.framesCreated);
m.setFramesCreated(Frame.framesCreated);
//Tools.debug("Links: " + Link.linksCreated);
m.setLinkedCreated(Link.linksCreated);
//Tools.debug("avoids: " + s.avoidCount);
m.setAvoidCount(s.recoverCount);
//Tools.debug("Total Time: " + parseTime);
m.setParseTime(parseTime);
//Tools.debug("Total Count: " + parseCount);
Measures.setParseCount(++parseCount);
//Tools.debug("Average Time: " + (int)parseTime / parseCount);
m.setAverageParseTime((int)parseTime / parseCount);
m.setRecoverTime(-1);
Tools.setMeasures(m);
}
}
private void logBeforeParsing() {
if(Tools.tracing) {
TRACE("SG_Parse() - ");
}
if (Tools.debugging) {
Tools.debug("parse() - ", dumpActiveStacks());
}
}
private void logAfterParsing()
throws BadTokenException, TokenExpectedException {
if (isLogging()) {
Tools.logger("Number of lines: ", lineNumber);
Tools.logger("Maximum ", maxBranches, " parse branches reached at token ",
logCharify(maxToken), ", line ", maxLine, ", column ", maxColumn,
" (token #", maxTokenNumber, ")");
final long elapsed = System.currentTimeMillis() - startTime;
Tools.logger("Parse time: " + elapsed / 1000.0f + "s");
}
if (isDebugging()) {
Tools.debug("Parsing complete: all tokens read");
}
if (acceptingStack == null) {
final BadTokenException bad = createBadTokenException();
if (collectedErrors.isEmpty()) {
throw bad;
} else {
collectedErrors.add(bad);
throw new MultiBadTokenException(this, collectedErrors);
}
}
if (isDebugging()) {
Tools.debug("Accepting stack exists");
}
}
private void logCurrentToken() {
if (isLogging()) {
Tools.logger("Current token (#", tokensSeen, "): ", logCharify(currentToken));
}
}
private void logAfterShifter() {
if(Tools.tracing) {
TRACE("SG_DiscardShiftPairs() - ");
TRACE_ActiveStacks();
}
}
private void logBeforeShifter() {
if(Tools.tracing) {
TRACE("SG_Shifter() - ");
TRACE_ActiveStacks();
}
if (Tools.logging) {
Tools.logger("#", tokensSeen, ": shifting ", forShifter.size(), " parser(s) -- token ",
logCharify(currentToken), ", line ", lineNumber, ", column ", columnNumber);
}
if (Tools.debugging) {
Tools.debug("shifter() - " + dumpActiveStacks());
Tools.debug(" token : " + currentToken);
Tools.debug(" parsers : " + forShifter.size());
}
}
private void logBeforeParseCharacter() {
if(Tools.tracing) {
TRACE("SG_ParseToken() - ");
}
if (Tools.debugging) {
Tools.debug("parseCharacter() - " + dumpActiveStacks());
Tools.debug(" # active stacks : " + activeStacks.size());
}
/* forActor = *///computeStackOfStacks(activeStacks);
if (Tools.debugging) {
Tools.debug(" # for actor : " + forActor.size());
}
}
private String logCharify(int currentToken) {
switch (currentToken) {
case 32:
return "\\32";
case SGLR.EOF:
return "EOF";
case '\n':
return "\\n";
case 0:
return "\\0";
default:
return "" + (char) currentToken;
}
}
@SuppressWarnings("deprecation")
private void logBeforeActor(Frame st, State s) {
List<ActionItem> actionItems = null;
if (Tools.debugging || Tools.tracing) {
actionItems = s.getActionItems(currentToken);
}
if(Tools.tracing) {
TRACE("SG_Actor() - " + st.state.stateNumber);
TRACE_ActiveStacks();
}
if (Tools.debugging) {
Tools.debug("actor() - ", dumpActiveStacks());
}
if (Tools.debugging) {
Tools.debug(" state : ", s.stateNumber);
Tools.debug(" token : ", currentToken);
}
if (Tools.debugging) {
Tools.debug(" actions : ", actionItems);
}
if(Tools.tracing) {
TRACE("SG_ - actions: " + actionItems.size());
}
}
private void logAfterDoReductions() {
if (Tools.debugging) {
Tools.debug("<doReductions() - " + dumpActiveStacks());
}
if(Tools.tracing) {
TRACE("SG_ - doreductions done");
}
}
private void logReductionPath(Production prod, Path path, Frame st0, State next) {
if (Tools.debugging) {
Tools.debug(" path: ", path);
Tools.debug(st0.state);
}
if (Tools.logging) {
Tools.logger("Goto(", st0.peek().stateNumber, ",", prod.label + ") == ",
next.stateNumber);
}
}
private void logBeforeDoReductions(Frame st, Production prod,
final int pathsCount) {
if(Tools.tracing) {
TRACE("SG_DoReductions() - " + st.state.stateNumber);
}
if (Tools.debugging) {
Tools.debug("doReductions() - " + dumpActiveStacks());
logReductionInfo(st, prod);
Tools.debug(" paths : " + pathsCount);
}
}
private void logBeforeLimitedReductions(Frame st, Production prod, Link l,
PooledPathList paths) {
if(Tools.tracing) {
TRACE("SG_ - back in reducer ");
TRACE_ActiveStacks();
TRACE("SG_DoLimitedReductions() - " + st.state.stateNumber + ", " + l.parent.state.stateNumber);
}
if (Tools.debugging) {
Tools.debug("doLimitedReductions() - ", dumpActiveStacks());
logReductionInfo(st, prod);
Tools.debug(Arrays.asList(paths));
}
}
private void logReductionInfo(Frame st, Production prod) {
Tools.debug(" state : ", st.peek().stateNumber);
Tools.debug(" token : ", currentToken);
Tools.debug(" label : ", prod.label);
Tools.debug(" arity : ", prod.arity);
Tools.debug(" stack : ", st.dumpStack());
}
private void logAddedLink(Frame st0, Frame st1, Link nl) {
if (Tools.debugging) {
Tools.debug(" added link ", nl, " from ", st1.state.stateNumber, " to ",
st0.state.stateNumber);
}
if(Tools.tracing) {
TRACE_ActiveStacks();
}
}
private void logBeforeReducer(State s, Production prod, int length) {
if(Tools.tracing) {
TRACE("SG_Reducer() - " + s.stateNumber + ", " + length + ", " + prod.label);
TRACE_ActiveStacks();
}
if (Tools.logging) {
Tools.logger("Reducing; state ", s.stateNumber, ", token: ", logCharify(currentToken),
", production: ", prod.label);
}
if (Tools.debugging) {
Tools.debug("reducer() - ", dumpActiveStacks());
Tools.debug(" state : ", s.stateNumber);
Tools.debug(" token : ", logCharify(currentToken) + " (" + currentToken + ")");
Tools.debug(" production : ", prod.label);
}
}
private void TRACE_ActiveStacks() {
TRACE("SG_ - active stacks: " + activeStacks.size());
TRACE("SG_ - for_actor stacks: " + forActor.size());
TRACE("SG_ - for_actor_delayed stacks: " + forActorDelayed.size());
}
private void logAmbiguity(Frame st0, Production prod, Frame st1, Link nl) {
if (Tools.logging) {
Tools.logger("Ambiguity: direct link ", st0.state.stateNumber, " -> ",
st1.state.stateNumber, " ", (prod.isRejectProduction() ? "{reject}" : ""));
if (nl.label instanceof ParseNode) {
Tools.logger("nl is ", nl.isRejected() ? "{reject}" : "", " for ",
((ParseNode) nl.label).label);
}
}
if (Tools.debugging) {
Tools.debug("createAmbiguityCluster - ", tokensSeen - nl.getLength() - 1, "/",
nl.getLength());
}
}
}
|
org.spoofax.jsglr/src/org/spoofax/jsglr/client/SGLR.java
|
/*
* Created on 03.des.2005
*
* Copyright (c) 2005, Karl Trygve Kalleberg <karltk near strategoxt.org>
*
* Licensed under the GNU Lesser General Public License, v2.1
*/
package org.spoofax.jsglr.client;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import org.spoofax.PushbackStringIterator;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.jsglr.shared.ArrayDeque;
import org.spoofax.jsglr.shared.BadTokenException;
import org.spoofax.jsglr.shared.SGLRException;
import org.spoofax.jsglr.shared.TokenExpectedException;
import org.spoofax.jsglr.shared.Tools;
public class SGLR {
private RecoveryPerformance performanceMeasuring;
private final Set<BadTokenException> collectedErrors = new LinkedHashSet<BadTokenException>();
public static final int EOF = ParseTable.NUM_CHARS;
static final int TAB_SIZE = 4;//8;
protected static boolean WORK_AROUND_MULTIPLE_LOOKAHEAD;
//Performance testing
private static long parseTime=0;
private static int parseCount=0;
protected Frame startFrame;
private long startTime;
protected volatile boolean asyncAborted;
protected Frame acceptingStack;
protected final ArrayDeque<Frame> activeStacks;
private ParseTable parseTable;
protected int currentToken;
protected int tokensSeen;
protected int lineNumber;
protected int columnNumber;
private final ArrayDeque<ActionState> forShifter;
private ArrayDeque<Frame> forActor;
private ArrayDeque<Frame> forActorDelayed;
private int maxBranches;
private int maxToken;
private int maxLine;
private int maxColumn;
private int maxTokenNumber;
private AmbiguityManager ambiguityManager;
protected Disambiguator disambiguator;
private int rejectCount;
private int reductionCount;
protected PushbackStringIterator currentInputStream;
private PathListPool pathCache = new PathListPool();
private ArrayDeque<Frame> activeStacksWorkQueue = new ArrayDeque<Frame>();
private ArrayDeque<Frame> recoverStacks;
private ParserHistory history;
private RecoveryConnector recoverIntegrator;
protected boolean useIntegratedRecovery;
public ParserHistory getHistory() {
return history;
}
private boolean fineGrainedOnRegion;
public void clearRecoverStacks(){
recoverStacks.clear(false);
}
public ArrayDeque<Frame> getRecoverStacks() {
return recoverStacks;
}
public Set<BadTokenException> getCollectedErrors() {
return collectedErrors;
}
/**
* Attempts to set a timeout for parsing.
* Default implementation throws an
* {@link UnsupportedOperationException}.
*
* @see org.spoofax.jsglr.io.SGLR#setTimeout(int)
*/
public void setTimeout(int timeout) {
throw new UnsupportedOperationException("Use org.spoofax.jsglr.io.SGLR for setting a timeout");
}
protected void initParseTimer() {
// Default does nothing (not supported by GWT)
}
@Deprecated
public SGLR(ITermFactory pf, ParseTable parseTable) {
this(new Asfix2TreeBuilder(pf), parseTable);
}
@Deprecated
public SGLR(ParseTable parseTable) {
this(new Asfix2TreeBuilder(), parseTable);
}
public SGLR(ITreeBuilder treeBuilder, ParseTable parseTable) {
assert parseTable != null;
// Init with a new factory for both serialized or BAF instances.
this.parseTable = parseTable;
activeStacks = new ArrayDeque<Frame>();
forActor = new ArrayDeque<Frame>();
forActorDelayed = new ArrayDeque<Frame>();
forShifter = new ArrayDeque<ActionState>();
disambiguator = new Disambiguator();
useIntegratedRecovery = false;
recoverIntegrator = null;
history = new ParserHistory();
setTreeBuilder(treeBuilder);
}
public void setUseStructureRecovery(boolean useRecovery, IRecoveryParser parser) {
useIntegratedRecovery = useRecovery;
recoverIntegrator = new RecoveryConnector(this, parser);
}
/**
* Enables error recovery based on region recovery and, if available, recovery rules.
* Does not enable bridge parsing.
*
* @see ParseTable#hasRecovers() Determines if the parse table supports recovery rules
*/
public final void setUseStructureRecovery(boolean useRecovery) {
setUseStructureRecovery(useRecovery, null);
}
protected void setFineGrainedOnRegion(boolean fineGrainedMode) {
fineGrainedOnRegion = fineGrainedMode;
recoverStacks = new ArrayDeque<Frame>();
}
@Deprecated
protected void setUseFineGrained(boolean useFG) {
recoverIntegrator.setUseFineGrained(useFG);
}
// FIXME: we have way to many of these accessors; does this have to be public?
// if not for normal use, it should at least be 'internalSet....'
@Deprecated
public void setCombinedRecovery(boolean useBP, boolean useFG,
boolean useOnlyFG) {
recoverIntegrator.setOnlyFineGrained(useOnlyFG);
recoverIntegrator.setUseBridgeParser(useBP);
recoverIntegrator.setUseFineGrained(useFG);
}
public RecoveryPerformance getPerformanceMeasuring() {
return performanceMeasuring;
}
/**
* @deprecated Use {@link #asyncCancel()} instead.
*/
@Deprecated
public void asyncAbort() {
asyncCancel();
}
/**
* Aborts an asynchronously running parse job, causing it to throw an exception.
*
* (Provides no guarantee that the parser is actually cancelled.)
*/
public void asyncCancel() {
asyncAborted = true;
}
public void asyncCancelReset() {
asyncAborted = false;
}
public static boolean isDebugging() {
return Tools.debugging;
}
public static boolean isLogging() {
return Tools.logging;
}
/**
* Initializes the active stacks. At the start of parsing there is only one
* active stack, and this stack contains the start symbol obtained from the
* parse table.
*
* @return top-level frame of the initial stack
*/
private Frame initActiveStacks() {
activeStacks.clear();
final Frame st0 = newStack(parseTable.getInitialState());
addStack(st0);
return st0;
}
@Deprecated
public Object parse(String fis) throws BadTokenException,
TokenExpectedException, ParseException, SGLRException {
return parse(fis, null, null);
}
@Deprecated
public final Object parse(String input, String filename) throws BadTokenException,
TokenExpectedException, ParseException, SGLRException {
return parse(input, filename, null);
}
/**
* Parses a string and constructs a new tree using the tree builder.
*
* @param input The input string.
* @param filename The source filename of the string, or null if not available.
* @param startSymbol The start symbol to use, or null if any applicable.
*/
public Object parse(String input, String filename, String startSymbol) throws BadTokenException, TokenExpectedException, ParseException,
SGLRException {
logBeforeParsing();
initParseVariables(input, filename);
startTime = System.currentTimeMillis();
initParseTimer();
Object result = sglrParse(startSymbol);
return result;
}
private Object sglrParse(String startSymbol)
throws BadTokenException, TokenExpectedException,
ParseException, SGLRException {
getPerformanceMeasuring().startParse();
try {
do {
readNextToken();
history.keepTokenAndState(this);
doParseStep();
} while (currentToken != SGLR.EOF && activeStacks.size() > 0);
if (acceptingStack == null) {
collectedErrors.add(createBadTokenException());
}
if(useIntegratedRecovery && acceptingStack==null){
recoverIntegrator.recover();
if(acceptingStack==null && activeStacks.size()>0) {
return sglrParse(startSymbol);
}
}
getPerformanceMeasuring().endParse(acceptingStack!=null);
} catch (final TaskCancellationException e) {
throw new ParseTimeoutException(this, currentToken, tokensSeen - 1, lineNumber,
columnNumber, collectedErrors);
} finally {
pathCache.reset();
activeStacks.clear(false);
activeStacksWorkQueue.clear(false);
forShifter.clear(false);
if (recoverStacks != null) recoverStacks.clear(false);
}
logAfterParsing();
final Link s = acceptingStack.findDirectLink(startFrame);
if (s == null) {
throw new ParseException(this, "Accepting stack has no link");
}
logParseResult(s);
Tools.debug("avoids: ", s.recoverCount);
//Tools.debug(s.label.toParseTree(parseTable));
if (parseTable.getTreeBuilder() instanceof NullTreeBuilder) {
return null;
} else {
return disambiguator.applyFilters(this, s.label, startSymbol, tokensSeen);
}
}
void readNextToken() {
logCurrentToken();
currentToken = getNextToken();
}
protected void doParseStep() {
logBeforeParseCharacter();
parseCharacter(); //applies reductions on active stack structure and fills forshifter
shifter(); //renewes active stacks with states in forshifter
}
private void initParseVariables(String input, String filename) {
forActor.clear();
forActorDelayed.clear();
forShifter.clear();
history.clear();
startFrame = initActiveStacks();
tokensSeen = 0;
columnNumber = 0;
lineNumber = 1;
currentInputStream = new PushbackStringIterator(input);
acceptingStack = null;
collectedErrors.clear();
history=new ParserHistory();
performanceMeasuring=new RecoveryPerformance();
parseTable.getTreeBuilder().initializeInput(input, filename);
PooledPathList.resetPerformanceCounters();
PathListPool.resetPerformanceCounters();
ambiguityManager = new AmbiguityManager(input.length());
pathCache.reset();
}
private BadTokenException createBadTokenException() {
final Frame singlePreviousStack = activeStacks.size() == 1 ? activeStacks.get(0) : null;
if (singlePreviousStack != null) {
Action action = singlePreviousStack.peek().getSingularAction();
if (action != null && action.getActionItems().length == 1) {
final StringBuilder expected = new StringBuilder();
do {
final int token = action.getSingularRange();
if (token == -1) {
break;
}
expected.append((char) token);
final ActionItem[] items = action.getActionItems();
if (!(items.length == 1 && items[0].type == ActionItem.SHIFT)) {
break;
}
final Shift shift = (Shift) items[0];
action = parseTable.getState(shift.nextState).getSingularAction();
} while (action != null);
if (expected.length() > 0) {
return new TokenExpectedException(this, expected.toString(), currentToken,
tokensSeen - 1, lineNumber, columnNumber);
}
}
}
return new BadTokenException(this, currentToken, tokensSeen - 1, lineNumber,
columnNumber);
}
private void shifter() {
logBeforeShifter();
clearActiveStacks();
final AbstractParseNode prod = parseTable.lookupProduction(currentToken);
while (forShifter.size() > 0) {
final ActionState as = forShifter.remove();
if (!parseTable.hasRejects() || !as.st.allLinksRejected()) {
Frame st1 = findStack(activeStacks, as.s);
if (st1 == null) {
st1 = newStack(as.s);
addStack(st1);
}
st1.addLink(as.st, prod, 1);
} else {
if (Tools.logging) {
Tools.logger("Shifter: skipping rejected stack with state ",
as.st.state.stateNumber);
}
}
}
logAfterShifter();
}
protected void addStack(Frame st1) {
if(Tools.tracing) {
TRACE("SG_AddStack() - " + st1.state.stateNumber);
}
activeStacks.addFirst(st1);
}
private void parseCharacter() {
logBeforeParseCharacter();
activeStacksWorkQueue.clear(true);
activeStacksWorkQueue.addAll(activeStacks);
clearForActorDelayed();
clearForShifter();
while (activeStacksWorkQueue.size() > 0 || forActor.size() > 0) {
final Frame st = pickStackNodeFromActivesOrForActor(activeStacksWorkQueue);
if (!st.allLinksRejected()) {
actor(st);
}
if(activeStacksWorkQueue.size() == 0 && forActor.size() == 0) {
fillForActorWithDelayedFrames(); //Fills foractor, clears foractor delayed
}
}
}
private void fillForActorWithDelayedFrames() {
if(Tools.tracing) {
TRACE("SG_ - both empty");
}
final ArrayDeque<Frame> empty = forActor;
forActor = forActorDelayed;
empty.clear(true);
forActorDelayed = empty;
}
private Frame pickStackNodeFromActivesOrForActor(ArrayDeque<Frame> actives) {
Frame st;
if(actives.size() > 0) {
if(Tools.tracing) {
TRACE("SG_ - took active");
}
st = actives.remove();
} else {
if(Tools.tracing) {
TRACE("SG_ - took foractor");
}
st = forActor.remove();
}
return st;
}
private void actor(Frame st) {
final State s = st.peek();
logBeforeActor(st, s);
for (final Action action : s.getActions()) {
if (action.accepts(currentToken)) {
for (final ActionItem ai : action.getActionItems()) {
switch (ai.type) {
case ActionItem.SHIFT: {
final Shift sh = (Shift) ai;
final ActionState actState = new ActionState(st, parseTable.getState(sh.nextState));
actState.currentToken = currentToken;
addShiftPair(actState); //Adds StackNode to forshifter
statsRecordParsers(); //sets some values un current parse state
break;
}
case ActionItem.REDUCE: {
final Reduce red = (Reduce) ai;
doReductions(st, red.production);
break;
}
case ActionItem.REDUCE_LOOKAHEAD: {
final ReduceLookahead red = (ReduceLookahead) ai;
if(checkLookahead(red)) {
if(Tools.tracing) {
TRACE("SG_ - ok");
}
doReductions(st, red.production);
}
break;
}
case ActionItem.ACCEPT: {
if (!st.allLinksRejected()) {
acceptingStack = st;
if (Tools.logging) {
Tools.logger("Reached the accept state");
}
}
break;
}
default:
throw new IllegalStateException("Unknown action type: " + ai.type);
}
}
}
}
if(Tools.tracing) {
TRACE("SG_ - actor done");
}
}
private boolean checkLookahead(ReduceLookahead red) {
return doCheckLookahead(red, red.getCharRanges(), 0);
}
private boolean doCheckLookahead(ReduceLookahead red, RangeList[] charClass, int pos) {
if(Tools.tracing) {
TRACE("SG_CheckLookAhead() - ");
}
final int c = currentInputStream.read();
// EOF
if(c == -1) {
return true;
}
boolean permit = true;
if(pos < charClass.length) {
permit = charClass[pos].within(c) ? false : doCheckLookahead(red, charClass, pos + 1);
}
currentInputStream.unread(c);
return permit;
}
private void addShiftPair(ActionState state) {
if(Tools.tracing) {
TRACE("SG_AddShiftPair() - " + state.s.stateNumber);
}
forShifter.add(state);
}
private void statsRecordParsers() {
if (forShifter.size() > maxBranches) {
maxBranches = forShifter.size();
maxToken = currentToken;
maxColumn = columnNumber;
maxLine = lineNumber;
maxTokenNumber = tokensSeen;
}
}
private void doReductions(Frame st, Production prod) {
if(!recoverModeOk(st, prod)) {
return;
}
final PooledPathList paths = pathCache.create();
//System.out.println(paths.size());
st.findAllPaths(paths, prod.arity);
//System.out.println(paths.size());
logBeforeDoReductions(st, prod, paths.size());
reduceAllPaths(prod, paths);
logAfterDoReductions();
paths.end();
}
private boolean recoverModeOk(Frame st, Production prod) {
return !prod.isRecoverProduction() || fineGrainedOnRegion;
}
private void doLimitedReductions(Frame st, Production prod, Link l) { //Todo: Look add sharing code with doReductions
if(!recoverModeOk(st, prod)) {
return;
}
final PooledPathList limitedPool = pathCache.create();
st.findLimitedPaths(limitedPool, prod.arity, l); //find paths containing the link
logBeforeLimitedReductions(st, prod, l, limitedPool);
reduceAllPaths(prod, limitedPool);
limitedPool.end();
}
private void reduceAllPaths(Production prod, PooledPathList paths) {
for(int i = 0; i < paths.size(); i++) {
final Path path = paths.get(i);
final AbstractParseNode[] kids = path.getParseNodes();
final Frame st0 = path.getEnd();
final State next = parseTable.go(st0.peek(), prod.label);
logReductionPath(prod, path, st0, next);
if(!prod.isRecoverProduction())
reducer(st0, next, prod, kids, path);
else
reducerRecoverProduction(st0, next, prod, kids, path);
}
if (asyncAborted) {
// Rethrown as ParseTimeoutException in SGLR.sglrParse()
throw new TaskCancellationException("Long-running parse job aborted");
}
}
private void reducer(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) {
assert(!prod.isRecoverProduction());
logBeforeReducer(s, prod, path.getLength());
increaseReductionCount();
final int length = path.getLength();
final int numberOfRecoveries = calcRecoverCount(prod, path);
final AbstractParseNode t = prod.apply(kids);
final Frame st1 = findStack(activeStacks, s);
if (st1 == null) {
// Found no existing stack with for state s; make new stack
addNewStack(st0, s, prod, length, numberOfRecoveries, t);
} else {
/* A stack with state s exists; check for ambiguities */
Link nl = st1.findDirectLink(st0);
if (nl != null) {
logAmbiguity(st0, prod, st1, nl);
if (prod.isRejectProduction()) {
nl.reject();
}
if(numberOfRecoveries == 0 && nl.recoverCount == 0 || nl.isRejected()) {
boolean createdByRecursion=kids.length==1 && kids[0]==nl.label && nl.label instanceof Amb;
if(!createdByRecursion){
createAmbNode(t, nl);
actorOnActiveStacksOverNewLink(nl);//reductions on st1 should have used the Amb link, so they must be redone
}
} else if (numberOfRecoveries < nl.recoverCount) {
nl.label = t;
nl.recoverCount = numberOfRecoveries;
actorOnActiveStacksOverNewLink(nl);
} else if (numberOfRecoveries == nl.recoverCount) {
nl.label = t;
}
} else {
nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
if (prod.isRejectProduction()) {
nl.reject();
increaseRejectCount();
}
logAddedLink(st0, st1, nl);
actorOnActiveStacksOverNewLink(nl);
}
}
if(Tools.tracing) {
TRACE_ActiveStacks();
TRACE("SG_ - reducer done");
}
}
private void reducerRecoverProduction(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) {
assert(prod.isRecoverProduction());
final int length = path.getLength();
final int numberOfRecoveries = calcRecoverCount(prod, path);
final AbstractParseNode t = prod.apply(kids);
final Frame stActive = findStack(activeStacks, s);
if(stActive!=null){
Link lnActive=stActive.findDirectLink(st0);
if(lnActive!=null){
return; //TODO: ambiguity
}
}
final Frame stRecover = findStack(recoverStacks, s);
if(stRecover!=null){
Link nlRecover = stRecover.findDirectLink(st0);
if(nlRecover!=null){
return; //TODO: ambiguity
}
nlRecover = stRecover.addLink(st0, t, length);
nlRecover.recoverCount = numberOfRecoveries;
return;
}
addNewRecoverStack(st0, s, prod, length, numberOfRecoveries, t);
}
private void createAmbNode(AbstractParseNode t, Link nl) {
nl.addAmbiguity(t, tokensSeen);
ambiguityManager.increaseAmbiguityCalls();
}
/**
* Found no existing stack with for state s; make new stack
*/
private void addNewStack(Frame st0, State s, Production prod, int length,
int numberOfRecoveries, AbstractParseNode t) {
final Frame st1 = newStack(s);
final Link nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
addStack(st1);
forActorDelayed.addFirst(st1);
if(Tools.tracing) {
TRACE("SG_AddStack() - " + st1.state.stateNumber);
}
if (prod.isRejectProduction()) {
if (Tools.logging) {
Tools.logger("Reject [new]");
}
nl.reject();
increaseRejectCount();
}
}
/**
* Found no existing stack with for state s; make new stack
*/
private void addNewRecoverStack(Frame st0, State s, Production prod, int length,
int numberOfRecoveries, AbstractParseNode t) {
if (!(fineGrainedOnRegion && !prod.isRejectProduction())) {
return;
}
final Frame st1 = newStack(s);
final Link nl = st1.addLink(st0, t, length);
nl.recoverCount = numberOfRecoveries;
recoverStacks.addFirst(st1);
}
private void actorOnActiveStacksOverNewLink(Link nl) {
// Note: ActiveStacks can be modified inside doLimitedReductions
// new elements may be inserted at the beginning
final int sz = activeStacks.size();
for (int i = 0; i < sz; i++) {
// for(Frame st2 : activeStacks) {
if(Tools.tracing) {
TRACE("SG_ activeStack - ");
}
final int pos = activeStacks.size() - sz + i;
final Frame st2 = activeStacks.get(pos);
if (st2.allLinksRejected() || inReduceStacks(forActor, st2) || inReduceStacks(forActorDelayed, st2))
{
continue; //stacknode will find reduction in regular process
}
for (final Action action : st2.peek().getActions()) {
if (action.accepts(currentToken)) {
for (final ActionItem ai : action.getActionItems()) {
switch(ai.type) {
case ActionItem.REDUCE:
final Reduce red = (Reduce) ai;
doLimitedReductions(st2, red.production, nl);
break;
case ActionItem.REDUCE_LOOKAHEAD:
final ReduceLookahead red2 = (ReduceLookahead) ai;
if(checkLookahead(red2)) {
doLimitedReductions(st2, red2.production, nl);
}
break;
}
}
}
}
}
}
private int calcRecoverCount(Production prod, Path path) {
return path.getRecoverCount() + (prod.isRecoverProduction() ? 1 : 0);
}
private boolean inReduceStacks(Queue<Frame> q, Frame frame) {
if(Tools.tracing) {
TRACE("SG_InReduceStacks() - " + frame.state.stateNumber);
}
return q.contains(frame);
}
protected Frame newStack(State s) {
if(Tools.tracing) {
TRACE("SG_NewStack() - " + s.stateNumber);
}
return new Frame(s);
}
private void increaseReductionCount() {
reductionCount++;
}
protected void increaseRejectCount() {
rejectCount++;
}
protected int getRejectCount() {
return rejectCount;
}
Frame findStack(ArrayDeque<Frame> stacks, State s) {
if(Tools.tracing) {
TRACE("SG_FindStack() - " + s.stateNumber);
}
// We need only check the top frames of the active stacks.
if (Tools.debugging) {
Tools.debug("findStack() - ", dumpActiveStacks());
Tools.debug(" looking for ", s.stateNumber);
}
final int size = stacks.size();
for (int i = 0; i < size; i++) {
Frame stack = stacks.get(i);
if (stack.state.stateNumber == s.stateNumber) {
if(Tools.tracing) {
TRACE("SG_ - found stack");
}
return stack;
}
}
if(Tools.tracing) {
TRACE("SG_ - stack not found");
}
return null;
}
private int getNextToken() {
if(Tools.tracing) {
TRACE("SG_NextToken() - ");
}
final int ch = currentInputStream.read();
updateLineAndColumnInfo(ch);
if(ch == -1) {
return SGLR.EOF;
}
return ch;
}
protected void updateLineAndColumnInfo(int ch) {
tokensSeen++;
if (Tools.debugging) {
Tools.debug("getNextToken() - ", ch, "(", (char) ch, ")");
}
switch (ch) {
case '\n':
lineNumber++;
columnNumber = 0;
break;
case '\t':
columnNumber = (columnNumber / TAB_SIZE + 1) * TAB_SIZE;
break;
case -1:
break;
default:
columnNumber++;
}
}
@Deprecated
public void setFilter(boolean filter) {
getDisambiguator().setFilterAny(filter);
}
private void clearForShifter() {
forShifter.clear(true);
}
private void clearForActorDelayed() {
forActorDelayed.clear(true);
}
private void clearActiveStacks() {
activeStacks.clear(true);
}
public ParseTable getParseTable() {
return parseTable;
}
public void setTreeBuilder(ITreeBuilder treeBuilder) {
parseTable.setTreeBuilder(treeBuilder);
}
public ITreeBuilder getTreeBuilder() {
return parseTable.getTreeBuilder();
}
AmbiguityManager getAmbiguityManager() {
return ambiguityManager;
}
public Disambiguator getDisambiguator() {
return disambiguator;
}
public void setDisambiguator(Disambiguator disambiguator) {
this.disambiguator = disambiguator;
}
@Deprecated
public ITermFactory getFactory() {
return parseTable.getFactory();
}
protected int getReductionCount() {
return reductionCount;
}
protected int getRejectionCount() {
return rejectCount;
}
@Deprecated
public static void setWorkAroundMultipleLookahead(boolean value) {
WORK_AROUND_MULTIPLE_LOOKAHEAD = value;
}
////////////////////////////////////////////////////// Log functions ///////////////////////////////////////////////////////////////////////////////
private static int traceCallCount = 0;
static void TRACE(String string) {
System.err.println("[" + traceCallCount + "] " + string);
traceCallCount++;
}
private String dumpActiveStacks() {
final StringBuffer sb = new StringBuffer();
boolean first = true;
if (activeStacks == null) {
sb.append(" GSS unitialized");
} else {
sb.append("{").append(activeStacks.size()).append("} ");
for (final Frame f : activeStacks) {
if (!first) {
sb.append(", ");
}
sb.append(f.dumpStack());
first = false;
}
}
return sb.toString();
}
private void logParseResult(Link s) {
if (isDebugging()) {
Tools.debug("internal parse tree:\n", s.label);
}
if(Tools.tracing) {
TRACE("SG_ - internal tree: " + s.label);
}
if (Tools.measuring) {
final Measures m = new Measures();
//Tools.debug("Time (ms): " + (System.currentTimeMillis()-startTime));
m.setTime(System.currentTimeMillis() - startTime);
//Tools.debug("Red.: " + reductionCount);
m.setReductionCount(reductionCount);
//Tools.debug("Nodes: " + Frame.framesCreated);
m.setFramesCreated(Frame.framesCreated);
//Tools.debug("Links: " + Link.linksCreated);
m.setLinkedCreated(Link.linksCreated);
//Tools.debug("avoids: " + s.avoidCount);
m.setAvoidCount(s.recoverCount);
//Tools.debug("Total Time: " + parseTime);
m.setParseTime(parseTime);
//Tools.debug("Total Count: " + parseCount);
Measures.setParseCount(++parseCount);
//Tools.debug("Average Time: " + (int)parseTime / parseCount);
m.setAverageParseTime((int)parseTime / parseCount);
m.setRecoverTime(-1);
Tools.setMeasures(m);
}
}
private void logBeforeParsing() {
if(Tools.tracing) {
TRACE("SG_Parse() - ");
}
if (Tools.debugging) {
Tools.debug("parse() - ", dumpActiveStacks());
}
}
private void logAfterParsing()
throws BadTokenException, TokenExpectedException {
if (isLogging()) {
Tools.logger("Number of lines: ", lineNumber);
Tools.logger("Maximum ", maxBranches, " parse branches reached at token ",
logCharify(maxToken), ", line ", maxLine, ", column ", maxColumn,
" (token #", maxTokenNumber, ")");
final long elapsed = System.currentTimeMillis() - startTime;
Tools.logger("Parse time: " + elapsed / 1000.0f + "s");
}
if (isDebugging()) {
Tools.debug("Parsing complete: all tokens read");
}
if (acceptingStack == null) {
final BadTokenException bad = createBadTokenException();
if (collectedErrors.isEmpty()) {
throw bad;
} else {
collectedErrors.add(bad);
throw new MultiBadTokenException(this, collectedErrors);
}
}
if (isDebugging()) {
Tools.debug("Accepting stack exists");
}
}
private void logCurrentToken() {
if (isLogging()) {
Tools.logger("Current token (#", tokensSeen, "): ", logCharify(currentToken));
}
}
private void logAfterShifter() {
if(Tools.tracing) {
TRACE("SG_DiscardShiftPairs() - ");
TRACE_ActiveStacks();
}
}
private void logBeforeShifter() {
if(Tools.tracing) {
TRACE("SG_Shifter() - ");
TRACE_ActiveStacks();
}
if (Tools.logging) {
Tools.logger("#", tokensSeen, ": shifting ", forShifter.size(), " parser(s) -- token ",
logCharify(currentToken), ", line ", lineNumber, ", column ", columnNumber);
}
if (Tools.debugging) {
Tools.debug("shifter() - " + dumpActiveStacks());
Tools.debug(" token : " + currentToken);
Tools.debug(" parsers : " + forShifter.size());
}
}
private void logBeforeParseCharacter() {
if(Tools.tracing) {
TRACE("SG_ParseToken() - ");
}
if (Tools.debugging) {
Tools.debug("parseCharacter() - " + dumpActiveStacks());
Tools.debug(" # active stacks : " + activeStacks.size());
}
/* forActor = *///computeStackOfStacks(activeStacks);
if (Tools.debugging) {
Tools.debug(" # for actor : " + forActor.size());
}
}
private String logCharify(int currentToken) {
switch (currentToken) {
case 32:
return "\\32";
case SGLR.EOF:
return "EOF";
case '\n':
return "\\n";
case 0:
return "\\0";
default:
return "" + (char) currentToken;
}
}
@SuppressWarnings("deprecation")
private void logBeforeActor(Frame st, State s) {
List<ActionItem> actionItems = null;
if (Tools.debugging || Tools.tracing) {
actionItems = s.getActionItems(currentToken);
}
if(Tools.tracing) {
TRACE("SG_Actor() - " + st.state.stateNumber);
TRACE_ActiveStacks();
}
if (Tools.debugging) {
Tools.debug("actor() - ", dumpActiveStacks());
}
if (Tools.debugging) {
Tools.debug(" state : ", s.stateNumber);
Tools.debug(" token : ", currentToken);
}
if (Tools.debugging) {
Tools.debug(" actions : ", actionItems);
}
if(Tools.tracing) {
TRACE("SG_ - actions: " + actionItems.size());
}
}
private void logAfterDoReductions() {
if (Tools.debugging) {
Tools.debug("<doReductions() - " + dumpActiveStacks());
}
if(Tools.tracing) {
TRACE("SG_ - doreductions done");
}
}
private void logReductionPath(Production prod, Path path, Frame st0, State next) {
if (Tools.debugging) {
Tools.debug(" path: ", path);
Tools.debug(st0.state);
}
if (Tools.logging) {
Tools.logger("Goto(", st0.peek().stateNumber, ",", prod.label + ") == ",
next.stateNumber);
}
}
private void logBeforeDoReductions(Frame st, Production prod,
final int pathsCount) {
if(Tools.tracing) {
TRACE("SG_DoReductions() - " + st.state.stateNumber);
}
if (Tools.debugging) {
Tools.debug("doReductions() - " + dumpActiveStacks());
logReductionInfo(st, prod);
Tools.debug(" paths : " + pathsCount);
}
}
private void logBeforeLimitedReductions(Frame st, Production prod, Link l,
PooledPathList paths) {
if(Tools.tracing) {
TRACE("SG_ - back in reducer ");
TRACE_ActiveStacks();
TRACE("SG_DoLimitedReductions() - " + st.state.stateNumber + ", " + l.parent.state.stateNumber);
}
if (Tools.debugging) {
Tools.debug("doLimitedReductions() - ", dumpActiveStacks());
logReductionInfo(st, prod);
Tools.debug(Arrays.asList(paths));
}
}
private void logReductionInfo(Frame st, Production prod) {
Tools.debug(" state : ", st.peek().stateNumber);
Tools.debug(" token : ", currentToken);
Tools.debug(" label : ", prod.label);
Tools.debug(" arity : ", prod.arity);
Tools.debug(" stack : ", st.dumpStack());
}
private void logAddedLink(Frame st0, Frame st1, Link nl) {
if (Tools.debugging) {
Tools.debug(" added link ", nl, " from ", st1.state.stateNumber, " to ",
st0.state.stateNumber);
}
if(Tools.tracing) {
TRACE_ActiveStacks();
}
}
private void logBeforeReducer(State s, Production prod, int length) {
if(Tools.tracing) {
TRACE("SG_Reducer() - " + s.stateNumber + ", " + length + ", " + prod.label);
TRACE_ActiveStacks();
}
if (Tools.logging) {
Tools.logger("Reducing; state ", s.stateNumber, ", token: ", logCharify(currentToken),
", production: ", prod.label);
}
if (Tools.debugging) {
Tools.debug("reducer() - ", dumpActiveStacks());
Tools.debug(" state : ", s.stateNumber);
Tools.debug(" token : ", logCharify(currentToken) + " (" + currentToken + ")");
Tools.debug(" production : ", prod.label);
}
}
private void TRACE_ActiveStacks() {
TRACE("SG_ - active stacks: " + activeStacks.size());
TRACE("SG_ - for_actor stacks: " + forActor.size());
TRACE("SG_ - for_actor_delayed stacks: " + forActorDelayed.size());
}
private void logAmbiguity(Frame st0, Production prod, Frame st1, Link nl) {
if (Tools.logging) {
Tools.logger("Ambiguity: direct link ", st0.state.stateNumber, " -> ",
st1.state.stateNumber, " ", (prod.isRejectProduction() ? "{reject}" : ""));
if (nl.label instanceof ParseNode) {
Tools.logger("nl is ", nl.isRejected() ? "{reject}" : "", " for ",
((ParseNode) nl.label).label);
}
}
if (Tools.debugging) {
Tools.debug("createAmbiguityCluster - ", tokensSeen - nl.getLength() - 1, "/",
nl.getLength());
}
}
}
|
temporary fix for nightly build, while Maartje's ambiguity handling fix is still a work-in-progress
svn path=/spoofax/trunk/spoofax/org.spoofax.jsglr/; revision=22020
|
org.spoofax.jsglr/src/org/spoofax/jsglr/client/SGLR.java
|
temporary fix for nightly build, while Maartje's ambiguity handling fix is still a work-in-progress
|
|
Java
|
apache-2.0
|
9f272a46dda572c147de6ae46a351570223617db
| 0
|
JetBrains/teamcity-aws-codedeploy-plugin
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.runner.codedeploy;
import jetbrains.buildServer.util.amazon.AWSException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Collections;
/**
* @author vbedrosova
*/
public class LoggingDeploymentListenerTest extends LoggingTestCase {
private static final String FAKE_ID = "ID-123XYZ";
@BeforeMethod(alwaysRun = true)
public void mySetUp() throws Exception {
super.mySetUp();
}
@AfterMethod(alwaysRun = true)
public void myTearDown() throws Exception {
super.myTearDown();
}
@Test
public void common_events() throws Exception {
final LoggingDeploymentListener listener = create();
final String revisionName = "revision.zip";
final File revision = writeFile(revisionName);
final String bucketName = "bucketName";
final String key = "path/key.zip";
final String eTag = "12345";
listener.uploadRevisionStarted(revision, bucketName, key);
final String url = "https://s3-eu-west-1.amazonaws.com/bucketName/path/key.zip";
listener.uploadRevisionFinished(revision, bucketName, key, null, eTag, url);
final String applicationName = "App Name";
final String bundleType = ".zip";
listener.registerRevisionStarted(applicationName, bucketName, key, bundleType, null, eTag);
listener.registerRevisionFinished(applicationName, bucketName, key, bundleType, null, eTag);
final String groupName = "Deployment Fleet";
listener.createDeploymentStarted(applicationName, groupName, null);
listener.createDeploymentFinished(applicationName, groupName, null, FAKE_ID);
listener.deploymentWaitStarted(FAKE_ID);
assertLog(
"OPEN " + LoggingDeploymentListener.UPLOAD_REVISION,
"LOG Uploading application revision ##BASE_DIR##/" + revisionName + " to S3 bucket " + bucketName + " using key " + key,
"LOG Uploaded application revision " + url + "?etag=" + eTag,
"STATUS_TEXT Uploaded " + url + "?etag=" + eTag,
"PARAM " + CodeDeployConstants.S3_OBJECT_ETAG_CONFIG_PARAM + " -> " + eTag,
"CLOSE " + LoggingDeploymentListener.UPLOAD_REVISION,
"OPEN " + LoggingDeploymentListener.REGISTER_REVISION,
"LOG Registering application " + applicationName + " revision from S3 bucket " + bucketName + " with key " + key + ", bundle type " + bundleType + ", latest version and " + eTag + " ETag",
"STATUS_TEXT Registered revision",
"CLOSE " + LoggingDeploymentListener.REGISTER_REVISION,
"OPEN " + LoggingDeploymentListener.DEPLOY_APPLICATION,
"LOG Creating application " + applicationName + " deployment to deployment group " + groupName + " with default deployment configuration",
"PARAM " + CodeDeployConstants.DEPLOYMENT_ID_BUILD_CONFIG_PARAM + " -> " + FAKE_ID,
"LOG Deployment " + FAKE_ID + " created",
"CLOSE " + LoggingDeploymentListener.DEPLOY_APPLICATION);
}
@Test
public void deployment_progress_unknown() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus());
assertLog("PROGRESS Deployment ID-123XYZ status is unknown, 0 instances succeeded");
}
@Test
public void deployment_progress() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus("in progress", 1, 1, 1, 1, 1));
assertLog("PROGRESS Deployment ID-123XYZ in progress, 1 instance succeeded, 1 failed, 1 pending, 1 skipped, 1 in progress");
}
@Test
public void deployment_progress_finished_five_succeeded() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus("finished", 0, 0, 5, 0, 0));
assertLog("PROGRESS Deployment ID-123XYZ finished, 5 instances succeeded");
}
@Test
public void deployment_succeeded_short() throws Exception {
create().deploymentSucceeded(FAKE_ID, createStatus("finished", 0, 0, 5, 0, 0));
assertLog(
"LOG Deployment " + FAKE_ID + " finished, 5 instances succeeded, 0 failed, 0 pending, 0 skipped, 0 in progress",
"STATUS_TEXT Deployment " + FAKE_ID + " finished, 5 instances succeeded");
}
@Test
public void deployment_succeeded_long() throws Exception {
create().deploymentSucceeded(FAKE_ID, createStatus("finished", 2, 2, 1, 2, 2));
assertLog(
"LOG Deployment " + FAKE_ID + " finished, 1 instance succeeded, 2 failed, 2 pending, 2 skipped, 2 in progress",
"STATUS_TEXT Deployment " + FAKE_ID + " finished, 1 instance succeeded, 2 failed, 2 pending, 2 skipped, 2 in progress");
}
@Test
public void deployment_failed_timeout() throws Exception {
create().deploymentFailed(FAKE_ID, 2400, null, createStatus("in progress", 1, 1, 0, 0, 0));
assertLog(
"ERR Timeout 2400 sec exceeded, deployment " + FAKE_ID + " in progress, 0 instances succeeded, 0 failed, 1 pending, 0 skipped, 1 in progress",
"PROBLEM identity: -1745153132 type: CODEDEPLOY_TIMEOUT descr: Timeout 2400 sec exceeded, deployment " + FAKE_ID + " in progress, 0 instances succeeded, 1 pending, 1 in progress");
}
@Test
public void deployment_failed_timeout_with_error() throws Exception {
create().deploymentFailed(FAKE_ID, 2400, createError("abc", "Some error message"), createStatus("failed", 1, 1, 0, 1, 0));
assertLog(
"ERR Timeout 2400 sec exceeded, deployment " + FAKE_ID + " failed, 0 instances succeeded, 1 failed, 1 pending, 0 skipped, 1 in progress",
"ERR Associated error: Some error message",
"ERR Error code: abc",
"PROBLEM identity: -116108899 type: CODEDEPLOY_TIMEOUT descr: Timeout 2400 sec exceeded, deployment " + FAKE_ID + " failed, 0 instances succeeded, 1 failed, 1 pending, 1 in progress: Some error message");
}
@Test
public void deployment_failed() throws Exception {
create().deploymentFailed(FAKE_ID, null, createError("abc", "Some error message"), createStatus("failed", 0, 0, 0, 2, 0));
assertLog(
"ERR deployment " + FAKE_ID + " failed, 0 instances succeeded, 2 failed, 0 pending, 0 skipped, 0 in progress",
"ERR Associated error: Some error message",
"ERR Error code: abc",
"PROBLEM identity: 448838431 type: CODEDEPLOY_FAILURE descr: deployment " + FAKE_ID + " failed, 0 instances succeeded, 2 failed: Some error message");
}
@Test
public void deployment_exception_type() throws Exception {
create().exception(new AWSException("Some exception message", null, AWSException.EXCEPTION_BUILD_PROBLEM_TYPE, null));
assertLog(
"ERR Some exception message",
"PROBLEM identity: 2086901196 type: AWS_EXCEPTION descr: Some exception message",
"CLOSE deploy application");
}
@Test
public void deployment_exception_description_type() throws Exception {
create().exception(new AWSException("Some exception message", null, AWSException.CLIENT_PROBLEM_TYPE, "Some exception details"));
assertLog(
"ERR Some exception message",
"ERR Some exception details",
"PROBLEM identity: 2086901196 type: AWS_CLIENT descr: Some exception message",
"CLOSE deploy application");
}
@Test
public void deployment_exception_description_type_identity() throws Exception {
create().exception(new AWSException("Some exception message", "ABC123", AWSException.CLIENT_PROBLEM_TYPE, "Some exception details"));
assertLog(
"ERR Some exception message",
"ERR Some exception details",
"PROBLEM identity: -1424436592 type: AWS_CLIENT descr: Some exception message",
"CLOSE deploy application");
}
@Override
protected void performAfterTestVerification() {
// override parent behaviour
}
@NotNull
private AWSClient.Listener.InstancesStatus createStatus(@Nullable String status, int pending, int inProgress, int succeeded, int failed, int skipped) {
final AWSClient.Listener.InstancesStatus instancesStatus = new AWSClient.Listener.InstancesStatus();
instancesStatus.pending = pending;
instancesStatus.inProgress = inProgress;
instancesStatus.succeeded = succeeded;
instancesStatus.failed = failed;
instancesStatus.skipped = skipped;
if (status != null) instancesStatus.status = status;
return instancesStatus;
}
@NotNull
private AWSClient.Listener.InstancesStatus createStatus() {
return new AWSClient.Listener.InstancesStatus();
}
@NotNull
private AWSClient.Listener.ErrorInfo createError(@Nullable String code, @Nullable String message) {
final AWSClient.Listener.ErrorInfo errorInfo = new AWSClient.Listener.ErrorInfo();
errorInfo.code = code;
errorInfo.message = message;
return errorInfo;
}
@NotNull
private LoggingDeploymentListener create() {
return new LoggingDeploymentListener(Collections.<String, String>emptyMap(),
"fake_checkout_dir") {
@Override
protected void log(@NotNull String message) {
logMessage("LOG " + message);
}
@Override
protected void err(@NotNull String message) {
logMessage("ERR " + message);
}
@Override
protected void open(@NotNull String block) {
logMessage("OPEN " + block);
}
@Override
protected void close(@NotNull String block) {
logMessage("CLOSE " + block);
}
@Override
protected void parameter(@NotNull String name, @NotNull String value) {
logMessage("PARAM " + name + " -> " + value);
}
@Override
protected void problem(int identity, @NotNull String type, @NotNull String descr) {
logMessage("PROBLEM identity: " + identity + " type: " + type + " descr: " + descr);
}
@Override
protected void progress(@NotNull String message) {
logMessage("PROGRESS " + message);
}
@Override
protected void statusText(@NotNull String text) {
logMessage("STATUS_TEXT " + text);
}
};
}
}
|
aws-codedeploy-agent/src/test/java/jetbrains.buildServer.runner.codedeploy/LoggingDeploymentListenerTest.java
|
/*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.runner.codedeploy;
import jetbrains.buildServer.util.amazon.AWSException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Collections;
/**
* @author vbedrosova
*/
public class LoggingDeploymentListenerTest extends LoggingTestCase {
private static final String FAKE_ID = "ID-123XYZ";
@BeforeMethod(alwaysRun = true)
public void mySetUp() throws Exception {
super.mySetUp();
}
@AfterMethod(alwaysRun = true)
public void myTearDown() throws Exception {
super.myTearDown();
}
@Test
public void common_events() throws Exception {
final LoggingDeploymentListener listener = create();
final String revisionName = "revision.zip";
final File revision = writeFile(revisionName);
final String bucketName = "bucketName";
final String key = "path/key.zip";
final String eTag = "12345";
listener.uploadRevisionStarted(revision, bucketName, key);
final String url = "https://s3-eu-west-1.amazonaws.com/bucketName/path/key.zip";
listener.uploadRevisionFinished(revision, bucketName, key, null, eTag, url);
final String applicationName = "App Name";
final String bundleType = ".zip";
listener.registerRevisionStarted(applicationName, bucketName, key, bundleType, null, eTag);
listener.registerRevisionFinished(applicationName, bucketName, key, bundleType, null, eTag);
final String groupName = "Deployment Fleet";
listener.createDeploymentStarted(applicationName, groupName, null);
listener.createDeploymentFinished(applicationName, groupName, null, FAKE_ID);
listener.deploymentWaitStarted(FAKE_ID);
assertLog(
"OPEN " + LoggingDeploymentListener.UPLOAD_REVISION,
"LOG Uploading application revision ##BASE_DIR##/" + revisionName + " to S3 bucket " + bucketName + " using key " + key,
"LOG Uploaded application revision " + url + "?etag=" + eTag,
"STATUS_TEXT Uploaded " + url + "?etag=" + eTag,
"PARAM " + CodeDeployConstants.S3_OBJECT_ETAG_CONFIG_PARAM + " -> " + eTag,
"CLOSE " + LoggingDeploymentListener.UPLOAD_REVISION,
"OPEN " + LoggingDeploymentListener.REGISTER_REVISION,
"LOG Registering application " + applicationName + " revision from S3 bucket " + bucketName + " with key " + key + ", bundle type " + bundleType + ", latest version and " + eTag + " ETag",
"STATUS_TEXT Registered revision",
"CLOSE " + LoggingDeploymentListener.REGISTER_REVISION,
"OPEN " + LoggingDeploymentListener.DEPLOY_APPLICATION,
"LOG Creating application " + applicationName + " deployment to deployment group " + groupName + " with default deployment configuration",
"PARAM " + CodeDeployConstants.DEPLOYMENT_ID_BUILD_CONFIG_PARAM + " -> " + FAKE_ID,
"LOG Deployment " + FAKE_ID + " created",
"CLOSE " + LoggingDeploymentListener.DEPLOY_APPLICATION);
}
@Test
public void deployment_progress_unknown() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus());
assertLog("PROGRESS Deployment status is unknown, 0 instances succeeded");
}
@Test
public void deployment_progress() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus("in progress", 1, 1, 1, 1, 1));
assertLog("PROGRESS Deployment in progress, 1 instance succeeded, 1 failed, 1 pending, 1 skipped, 1 in progress");
}
@Test
public void deployment_progress_finished_five_succeeded() throws Exception {
create().deploymentInProgress(FAKE_ID, createStatus("finished", 0, 0, 5, 0, 0));
assertLog("PROGRESS Deployment finished, 5 instances succeeded");
}
@Test
public void deployment_succeeded_short() throws Exception {
create().deploymentSucceeded(FAKE_ID, createStatus("finished", 0, 0, 5, 0, 0));
assertLog(
"LOG Deployment " + FAKE_ID + " finished, 5 instances succeeded, 0 failed, 0 pending, 0 skipped, 0 in progress",
"STATUS_TEXT Deployment " + FAKE_ID + " finished, 5 instances succeeded");
}
@Test
public void deployment_succeeded_long() throws Exception {
create().deploymentSucceeded(FAKE_ID, createStatus("finished", 2, 2, 1, 2, 2));
assertLog(
"LOG Deployment " + FAKE_ID + " finished, 1 instance succeeded, 2 failed, 2 pending, 2 skipped, 2 in progress",
"STATUS_TEXT Deployment " + FAKE_ID + " finished, 1 instance succeeded, 2 failed, 2 pending, 2 skipped, 2 in progress");
}
@Test
public void deployment_failed_timeout() throws Exception {
create().deploymentFailed(FAKE_ID, 2400, null, createStatus("in progress", 1, 1, 0, 0, 0));
assertLog(
"ERR Timeout 2400 sec exceeded, deployment " + FAKE_ID + " in progress, 0 instances succeeded, 0 failed, 1 pending, 0 skipped, 1 in progress",
"PROBLEM identity: -1745153132 type: CODEDEPLOY_TIMEOUT descr: Timeout 2400 sec exceeded, deployment " + FAKE_ID + " in progress, 0 instances succeeded, 1 pending, 1 in progress");
}
@Test
public void deployment_failed_timeout_with_error() throws Exception {
create().deploymentFailed(FAKE_ID, 2400, createError("abc", "Some error message"), createStatus("failed", 1, 1, 0, 1, 0));
assertLog(
"ERR Timeout 2400 sec exceeded, deployment " + FAKE_ID + " failed, 0 instances succeeded, 1 failed, 1 pending, 0 skipped, 1 in progress",
"ERR Associated error: Some error message",
"ERR Error code: abc",
"PROBLEM identity: -116108899 type: CODEDEPLOY_TIMEOUT descr: Timeout 2400 sec exceeded, deployment " + FAKE_ID + " failed, 0 instances succeeded, 1 failed, 1 pending, 1 in progress: Some error message");
}
@Test
public void deployment_failed() throws Exception {
create().deploymentFailed(FAKE_ID, null, createError("abc", "Some error message"), createStatus("failed", 0, 0, 0, 2, 0));
assertLog(
"ERR deployment " + FAKE_ID + " failed, 0 instances succeeded, 2 failed, 0 pending, 0 skipped, 0 in progress",
"ERR Associated error: Some error message",
"ERR Error code: abc",
"PROBLEM identity: 448838431 type: CODEDEPLOY_FAILURE descr: deployment " + FAKE_ID + " failed, 0 instances succeeded, 2 failed: Some error message");
}
@Test
public void deployment_exception_type() throws Exception {
create().exception(new AWSException("Some exception message", null, AWSException.EXCEPTION_BUILD_PROBLEM_TYPE, null));
assertLog(
"ERR Some exception message",
"PROBLEM identity: 2086901196 type: AWS_EXCEPTION descr: Some exception message",
"CLOSE deploy application");
}
@Test
public void deployment_exception_description_type() throws Exception {
create().exception(new AWSException("Some exception message", null, AWSException.CLIENT_PROBLEM_TYPE, "Some exception details"));
assertLog(
"ERR Some exception message",
"ERR Some exception details",
"PROBLEM identity: 2086901196 type: AWS_CLIENT descr: Some exception message",
"CLOSE deploy application");
}
@Test
public void deployment_exception_description_type_identity() throws Exception {
create().exception(new AWSException("Some exception message", "ABC123", AWSException.CLIENT_PROBLEM_TYPE, "Some exception details"));
assertLog(
"ERR Some exception message",
"ERR Some exception details",
"PROBLEM identity: -1424436592 type: AWS_CLIENT descr: Some exception message",
"CLOSE deploy application");
}
@Override
protected void performAfterTestVerification() {
// override parent behaviour
}
@NotNull
private AWSClient.Listener.InstancesStatus createStatus(@Nullable String status, int pending, int inProgress, int succeeded, int failed, int skipped) {
final AWSClient.Listener.InstancesStatus instancesStatus = new AWSClient.Listener.InstancesStatus();
instancesStatus.pending = pending;
instancesStatus.inProgress = inProgress;
instancesStatus.succeeded = succeeded;
instancesStatus.failed = failed;
instancesStatus.skipped = skipped;
if (status != null) instancesStatus.status = status;
return instancesStatus;
}
@NotNull
private AWSClient.Listener.InstancesStatus createStatus() {
return new AWSClient.Listener.InstancesStatus();
}
@NotNull
private AWSClient.Listener.ErrorInfo createError(@Nullable String code, @Nullable String message) {
final AWSClient.Listener.ErrorInfo errorInfo = new AWSClient.Listener.ErrorInfo();
errorInfo.code = code;
errorInfo.message = message;
return errorInfo;
}
@NotNull
private LoggingDeploymentListener create() {
return new LoggingDeploymentListener(Collections.<String, String>emptyMap(),
"fake_checkout_dir") {
@Override
protected void log(@NotNull String message) {
logMessage("LOG " + message);
}
@Override
protected void err(@NotNull String message) {
logMessage("ERR " + message);
}
@Override
protected void open(@NotNull String block) {
logMessage("OPEN " + block);
}
@Override
protected void close(@NotNull String block) {
logMessage("CLOSE " + block);
}
@Override
protected void parameter(@NotNull String name, @NotNull String value) {
logMessage("PARAM " + name + " -> " + value);
}
@Override
protected void problem(int identity, @NotNull String type, @NotNull String descr) {
logMessage("PROBLEM identity: " + identity + " type: " + type + " descr: " + descr);
}
@Override
protected void progress(@NotNull String message) {
logMessage("PROGRESS " + message);
}
@Override
protected void statusText(@NotNull String text) {
logMessage("STATUS_TEXT " + text);
}
};
}
}
|
fixed tests
|
aws-codedeploy-agent/src/test/java/jetbrains.buildServer.runner.codedeploy/LoggingDeploymentListenerTest.java
|
fixed tests
|
|
Java
|
bsd-3-clause
|
482000e23ef73afbaa9a8f535156451b63f67ff8
| 0
|
krishagni/openspecimen,krishagni/openspecimen,NCIP/catissue-core,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,NCIP/catissue-core,NCIP/catissue-core,asamgir/openspecimen
|
package edu.wustl.catissuecore.applet.listener;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JTable;
import edu.wustl.catissuecore.applet.AppletConstants;
import edu.wustl.catissuecore.applet.AppletServerCommunicator;
import edu.wustl.catissuecore.applet.model.BaseAppletModel;
import edu.wustl.catissuecore.applet.model.MultipleSpecimenTableModel;
import edu.wustl.catissuecore.applet.ui.MultipleSpecimenApplet;
import edu.wustl.catissuecore.applet.util.CommonAppletUtil;
import edu.wustl.catissuecore.util.global.Constants;
public class SpecimenSubmitButtonHandler extends ButtonHandler
{
public SpecimenSubmitButtonHandler(JTable table)
{
super(table);
}
/**
* @see edu.wustl.catissuecore.applet.listener.ButtonHandler#handleAction(java.awt.event.ActionEvent)
*/
protected void handleAction(ActionEvent event)
{
MultipleSpecimenTableModel model = (MultipleSpecimenTableModel) table.getModel();
BaseAppletModel appletModel = new BaseAppletModel();
appletModel.setData(model.getMap());
model.getMap().put(AppletConstants.NO_OF_SPECIMENS,
String.valueOf(model.getTotalColumnCount()));
//------for parent specimen enable
//===========================
System.out.println("model.getCollectionGroupRadioButtonMap() : " + model.getCollectionGroupRadioButtonMap());
//===========================
model.getMap().put(AppletConstants.MULTIPLE_SPECIMEN_COLLECTION_GROUP_RADIOMAP,model.getCollectionGroupRadioButtonMap());
// --------------
System.out.println("Inside Submit Button Handler \n Map Details B4 submission: ");
HashMap map =(HashMap) model.getMap();
Iterator itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n");
// --------------
try
{
MultipleSpecimenApplet applet = (MultipleSpecimenApplet) CommonAppletUtil
.getBaseApplet(table);
String url = applet.getServerURL()
+ "/MultipleSpecimenAppletAction.do?method=submitSpecimens";
appletModel = (BaseAppletModel) AppletServerCommunicator.doAppletServerCommunication(
url, appletModel);
Map resultMap = appletModel.getData();
String target = (String) resultMap.get(Constants.MULTIPLE_SPECIMEN_RESULT);
// -------------- After submit
System.out.println("\n\n\nInside Submit Button Handler \n Map Details After submission: ");
map = (HashMap)appletModel.getData();
itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n\n\n");
// ----------------------- data map
System.out.println("Inside Submit Button Handler \n Data Map Details After submission: ");
map =(HashMap) model.getMap();
itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n");
// ----------------------- data map end
if(target.equals(Constants.SUCCESS)) {
Object[] parameters = new Object[]{target};
CommonAppletUtil.callJavaScriptFunction((JButton) event.getSource(),
"getSpecimenSubmitResult", parameters);
} else {
Object[] parameters = new Object[]{resultMap.get(Constants.ERROR_DETAIL)};
CommonAppletUtil.callJavaScriptFunction((JButton) event.getSource(),
"showSpecimenErrorMessages", parameters);
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Exception");
}
}
/* (non-Javadoc)
* @see edu.wustl.catissuecore.applet.listener.BaseActionHandler#preActionPerformed(java.awt.event.ActionEvent)
*/
protected void preActionPerformed(ActionEvent event)
{
//commented by mandar to check handling of selected data.
CommonAppletUtil.getSelectedData(table);
}
}
|
WEB-INF/src/edu/wustl/catissuecore/applet/listener/SpecimenSubmitButtonHandler.java
|
package edu.wustl.catissuecore.applet.listener;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JTable;
import edu.wustl.catissuecore.applet.AppletConstants;
import edu.wustl.catissuecore.applet.AppletServerCommunicator;
import edu.wustl.catissuecore.applet.model.BaseAppletModel;
import edu.wustl.catissuecore.applet.model.MultipleSpecimenTableModel;
import edu.wustl.catissuecore.applet.ui.MultipleSpecimenApplet;
import edu.wustl.catissuecore.applet.util.CommonAppletUtil;
import edu.wustl.catissuecore.util.global.Constants;
public class SpecimenSubmitButtonHandler extends ButtonHandler
{
public SpecimenSubmitButtonHandler(JTable table)
{
super(table);
}
/**
* @see edu.wustl.catissuecore.applet.listener.ButtonHandler#handleAction(java.awt.event.ActionEvent)
*/
protected void handleAction(ActionEvent event)
{
MultipleSpecimenTableModel model = (MultipleSpecimenTableModel) table.getModel();
BaseAppletModel appletModel = new BaseAppletModel();
appletModel.setData(model.getMap());
model.getMap().put(AppletConstants.NO_OF_SPECIMENS,
String.valueOf(model.getTotalColumnCount()));
// //------for parent specimen enable
// model.getMap().put(AppletConstants.MULTIPLE_SPECIMEN_COLLECTION_GROUP_RADIOMAP,model.getCollectionGroupRadioButtonMap());
// // --------------
System.out.println("Inside Submit Button Handler \n Map Details B4 submission: ");
HashMap map =(HashMap) model.getMap();
Iterator itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n");
//===========================
System.out.println("model.getCollectionGroupRadioButtonMap() : " + model.getCollectionGroupRadioButtonMap());
//===========================
// --------------
try
{
MultipleSpecimenApplet applet = (MultipleSpecimenApplet) CommonAppletUtil
.getBaseApplet(table);
String url = applet.getServerURL()
+ "/MultipleSpecimenAppletAction.do?method=submitSpecimens";
appletModel = (BaseAppletModel) AppletServerCommunicator.doAppletServerCommunication(
url, appletModel);
Map resultMap = appletModel.getData();
String target = (String) resultMap.get(Constants.MULTIPLE_SPECIMEN_RESULT);
// -------------- After submit
System.out.println("\n\n\nInside Submit Button Handler \n Map Details After submission: ");
map = (HashMap)appletModel.getData();
itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n\n\n");
// ----------------------- data map
System.out.println("Inside Submit Button Handler \n Data Map Details After submission: ");
map =(HashMap) model.getMap();
itr = map.keySet().iterator() ;
while(itr.hasNext())
{
String key =(String) itr.next();
System.out.println("key : "+key);
String value = map.get(key).toString() ;
System.out.println(" Value : "+ value);
}
System.out.println("\n ***********************************\n");
// ----------------------- data map end
if(target.equals(Constants.SUCCESS)) {
Object[] parameters = new Object[]{target};
CommonAppletUtil.callJavaScriptFunction((JButton) event.getSource(),
"getSpecimenSubmitResult", parameters);
} else {
Object[] parameters = new Object[]{resultMap.get(Constants.ERROR_DETAIL)};
CommonAppletUtil.callJavaScriptFunction((JButton) event.getSource(),
"showSpecimenErrorMessages", parameters);
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Exception");
}
}
/* (non-Javadoc)
* @see edu.wustl.catissuecore.applet.listener.BaseActionHandler#preActionPerformed(java.awt.event.ActionEvent)
*/
protected void preActionPerformed(ActionEvent event)
{
//commented by mandar to check handling of selected data.
CommonAppletUtil.getSelectedData(table);
}
}
|
collection group radio buttons set in map.
SVN-Revision: 5513
|
WEB-INF/src/edu/wustl/catissuecore/applet/listener/SpecimenSubmitButtonHandler.java
|
collection group radio buttons set in map.
|
|
Java
|
bsd-3-clause
|
ab81eeb7009f2810fb757a081ac2714732827f21
| 0
|
NCIP/i-spy,NCIP/i-spy
|
package gov.nih.nci.ispy.service.clinical;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import gov.nih.nci.caintegrator.application.util.StringUtils;
/**
* This class will hold the clinical data returned by the
* ClinicalDataQueryService.
*
* It represents the clinical data corresponding to a given
* patient a specific timepoint.
*
* @author harrismic
*
*/
public class ClinicalData implements Serializable{
private static final long serialVersionUID = 1L;
private String patientId;
private String labtrackId;
private TimepointType timepoint;
private DiseaseStageType diseaseStage;
private ERstatusType erStatus;
private Double erValue = null; //the summary ER score
private Double prValue = null; //the summary PR score
private Double her2Value = null; //the summary HER2 score
private PRstatusType prStatus;
private HER2statusType HER2status;
private ClinicalResponseType clinicalResponse;
private Double longestDiameter = null;
private String tumorMorphology;
private String primaryTumorNuclearGrade;
private String primaryTumorHistologyType;
private Double grossTumorSizeInCM = null; //Need to check units
private Double microscopeTumorSizeInCM = null;
private List<String> chemicalAgents = new ArrayList<String>();
private Double MRIpctChange = null; //change in tumor size (measured by MRI) wrt the baseline measurement
public ClinicalData(String labtrackId, String patientId, TimepointType timepoint) {
this.labtrackId = labtrackId;
this.patientId = patientId;
this.timepoint = timepoint;
}
public DiseaseStageType getDiseaseStage() {
return diseaseStage;
}
public void setDiseaseStage(DiseaseStageType diseaseStage) {
this.diseaseStage = diseaseStage;
}
public ERstatusType getErStatus() {
return erStatus;
}
public void setErStatus(ERstatusType erStatus) {
this.erStatus = erStatus;
}
public HER2statusType getHER2status() {
return HER2status;
}
public void setHER2status(HER2statusType her2status) {
HER2status = her2status;
}
public String getLabtrackId() {
return labtrackId;
}
public String getPatientId() {
return patientId;
}
public ClinicalResponseType getPatientResponse() {
return clinicalResponse;
}
public void setPatientResponse(ClinicalResponseType clinicalResponse) {
this.clinicalResponse = clinicalResponse;
}
public PRstatusType getPrStatus() {
return prStatus;
}
public void setPrStatus(PRstatusType prStatus) {
this.prStatus = prStatus;
}
public List<String> getChemicalAgents() {
return chemicalAgents;
}
public void setChemicalAgents(List<String> chemicalAgents) {
this.chemicalAgents = chemicalAgents;
}
public ClinicalResponseType getClinicalResponse() {
return clinicalResponse;
}
public void setClinicalResponse(ClinicalResponseType clinicalResponse) {
this.clinicalResponse = clinicalResponse;
}
public Double getErValue() {
return erValue;
}
public void setErValue(Double erValue) {
this.erValue = erValue;
if (erValue == null) {
setErStatus(ERstatusType.MISSING);
}
else if (erValue > 0.0) {
setErStatus(ERstatusType.ER_POS);
}
else {
setErStatus(ERstatusType.ER_NEG);
}
}
public Double getGrossTumorSizeInCM() {
return grossTumorSizeInCM;
}
public void setGrossTumorSizeInCM(Double grossTumorSizeInCM) {
this.grossTumorSizeInCM = grossTumorSizeInCM;
}
public Double getHer2Value() {
return her2Value;
}
public void setHer2Value(Double her2Value) {
this.her2Value = her2Value;
if (her2Value == null) {
setHER2status(HER2statusType.MISSING);
}
else if (her2Value > 0.0) {
setHER2status(HER2statusType.HER2_POS);
}
else {
setHER2status(HER2statusType.HER2_NEG);
}
}
public Double getLongestDiameter() {
return longestDiameter;
}
public void setLongestDiameter(Double longestDiameter) {
this.longestDiameter = longestDiameter;
}
public Double getMicroscopeTumorSizeInCM() {
return microscopeTumorSizeInCM;
}
public void setMicroscopeTumorSizeInCM(Double microscopeTumorSizeInCM) {
this.microscopeTumorSizeInCM = microscopeTumorSizeInCM;
}
public Double getMRIpctChange() {
return MRIpctChange;
}
public void setMRIpctChange(Double ipctChange) {
MRIpctChange = ipctChange;
}
public String getPrimaryTumorHistologyType() {
return primaryTumorHistologyType;
}
public void setPrimaryTumorHistologyType(String primaryTumorHistologyType) {
this.primaryTumorHistologyType = primaryTumorHistologyType;
}
public String getPrimaryTumorNuclearGrade() {
return primaryTumorNuclearGrade;
}
public void setPrimaryTumorNuclearGrade(String primaryTumorNuclearGrade) {
this.primaryTumorNuclearGrade = primaryTumorNuclearGrade;
}
public Double getPrValue() {
return prValue;
}
public void setPrValue(Double prValue) {
this.prValue = prValue;
if (prValue == null) {
setPrStatus(PRstatusType.MISSING);
}
else if (prValue > 0.0) {
setPrStatus(PRstatusType.PR_POS);
}
else {
setPrStatus(PRstatusType.PR_NEG);
}
}
public TimepointType getTimepoint() {
return timepoint;
}
public String getTumorMorphology() {
return tumorMorphology;
}
public void setTumorMorphology(String tumorMorphology) {
this.tumorMorphology = tumorMorphology;
}
public void setDiseaseStageFromString(String diseaseStage) {
if ((diseaseStage==null)||(diseaseStage.trim().length()==0)) {
setDiseaseStage(DiseaseStageType.MISSING);
}
else {
setDiseaseStage(DiseaseStageType.valueOf(diseaseStage));
}
}
public void setClinicalResponseFromString(String responseStr) {
if (StringUtils.isEmptyStr(responseStr)) {
setClinicalResponse(ClinicalResponseType.MISSING);
}
else if (responseStr.length() == 2) {
setClinicalResponse(ClinicalResponseType.valueOf(responseStr));
}
else if (responseStr.equalsIgnoreCase("Progressive Disease")) {
setClinicalResponse(ClinicalResponseType.PD);
}
else if (responseStr.equalsIgnoreCase("Stable Disease")) {
setClinicalResponse(ClinicalResponseType.SD);
}
else {
setClinicalResponse(ClinicalResponseType.UNKNOWN);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("LabtrackId:").append("\t").append(labtrackId).append("\n");
sb.append("PatiendId:").append("\t").append(patientId).append("\n");
sb.append("Timepoint:").append("\t").append(timepoint).append("\n");
sb.append("DiseaseStage:").append("\t").append(diseaseStage).append("\n");
sb.append("ERstatus:").append("\t").append(erStatus).append("\n");
sb.append("erValue:").append("\t").append(erValue).append("\n");
sb.append("prStatus:").append("\t").append(prStatus).append("\n");
sb.append("prValue:").append("\t").append(prValue).append("\n");
sb.append("HER2status:").append("\t").append(HER2status).append("\n");
sb.append("HER2Value:").append("\t").append(her2Value).append("\n");
sb.append("ClinicalResponse:").append("\t").append(clinicalResponse).append("\n");
sb.append("LongestDiameter:").append("\t").append(longestDiameter).append("\n");
sb.append("TumorMorphology").append("\t").append(tumorMorphology).append("\n");
sb.append("PrimaryTumorNuclearGrade:").append("\t").append(primaryTumorNuclearGrade).append("\n");
sb.append("PrimaryTumorHistologyType:").append("\t").append(primaryTumorHistologyType).append("\n");
sb.append("GrossTumorSizeInCM:").append("\t").append(grossTumorSizeInCM).append("\n");
sb.append("MicroscopeTumorSizeInCM").append("\t").append(microscopeTumorSizeInCM).append("\n");
sb.append("ChemicalAgents:").append("\t").append(StringUtils.concatinateStrings(chemicalAgents, "|")).append("\n");
sb.append("MRIpctChange:").append("\t").append(MRIpctChange).append("\n");
return sb.toString();
}
}
|
src/gov/nih/nci/ispy/service/clinical/ClinicalData.java
|
package gov.nih.nci.ispy.service.clinical;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import gov.nih.nci.caintegrator.application.util.StringUtils;
/**
* This class will hold the clinical data returned by the
* ClinicalDataQueryService.
*
* It represents the clinical data corresponding to a given
* patient a specific timepoint.
*
* @author harrismic
*
*/
public class ClinicalData implements Serializable{
private static final long serialVersionUID = 1L;
private String patientId;
private String labtrackId;
private TimepointType timepoint;
private DiseaseStageType diseaseStage;
private ERstatusType erStatus;
private double erValue = Double.MIN_VALUE; //the summary ER score
private double prValue = Double.MIN_VALUE; //the summary PR score
private double her2Value = Double.MIN_VALUE; //the summary HER2 score
private PRstatusType prStatus;
private HER2statusType HER2status;
private ClinicalResponseType clinicalResponse;
private double longestDiameter = Double.MIN_VALUE;
private String tumorMorphology;
private String primaryTumorNuclearGrade;
private String primaryTumorHistologyType;
private double grossTumorSizeInCM = Double.MIN_VALUE; //Need to check units
private double microscopeTumorSizeInCM = Double.MIN_VALUE;
private List<String> chemicalAgents = new ArrayList<String>();
private double MRIpctChange = Double.MIN_VALUE; //change in tumor size (measured by MRI) wrt the baseline measurement
public ClinicalData(String labtrackId, String patientId, TimepointType timepoint) {
this.labtrackId = labtrackId;
this.patientId = patientId;
this.timepoint = timepoint;
}
public DiseaseStageType getDiseaseStage() {
return diseaseStage;
}
public void setDiseaseStage(DiseaseStageType diseaseStage) {
this.diseaseStage = diseaseStage;
}
public ERstatusType getErStatus() {
return erStatus;
}
public void setErStatus(ERstatusType erStatus) {
this.erStatus = erStatus;
}
public HER2statusType getHER2status() {
return HER2status;
}
public void setHER2status(HER2statusType her2status) {
HER2status = her2status;
}
public String getLabtrackId() {
return labtrackId;
}
public String getPatientId() {
return patientId;
}
public ClinicalResponseType getPatientResponse() {
return clinicalResponse;
}
public void setPatientResponse(ClinicalResponseType clinicalResponse) {
this.clinicalResponse = clinicalResponse;
}
public PRstatusType getPrStatus() {
return prStatus;
}
public void setPrStatus(PRstatusType prStatus) {
this.prStatus = prStatus;
}
public List<String> getChemicalAgents() {
return chemicalAgents;
}
public void setChemicalAgents(List<String> chemicalAgents) {
this.chemicalAgents = chemicalAgents;
}
public ClinicalResponseType getClinicalResponse() {
return clinicalResponse;
}
public void setClinicalResponse(ClinicalResponseType clinicalResponse) {
this.clinicalResponse = clinicalResponse;
}
public double getErValue() {
return erValue;
}
public void setErValue(double erValue) {
this.erValue = erValue;
if (erValue > 0.0) {
setErStatus(ERstatusType.ER_POS);
}
else {
setErStatus(ERstatusType.ER_NEG);
}
}
public double getGrossTumorSizeInCM() {
return grossTumorSizeInCM;
}
public void setGrossTumorSizeInCM(double grossTumorSizeInCM) {
this.grossTumorSizeInCM = grossTumorSizeInCM;
}
public double getHer2Value() {
return her2Value;
}
public void setHer2Value(double her2Value) {
this.her2Value = her2Value;
if (her2Value > 0.0) {
setHER2status(HER2statusType.HER2_POS);
}
else {
setHER2status(HER2statusType.HER2_NEG);
}
}
public double getLongestDiameter() {
return longestDiameter;
}
public void setLongestDiameter(double longestDiameter) {
this.longestDiameter = longestDiameter;
}
public double getMicroscopeTumorSizeInCM() {
return microscopeTumorSizeInCM;
}
public void setMicroscopeTumorSizeInCM(double microscopeTumorSizeInCM) {
this.microscopeTumorSizeInCM = microscopeTumorSizeInCM;
}
public double getMRIpctChange() {
return MRIpctChange;
}
public void setMRIpctChange(double ipctChange) {
MRIpctChange = ipctChange;
}
public String getPrimaryTumorHistologyType() {
return primaryTumorHistologyType;
}
public void setPrimaryTumorHistologyType(String primaryTumorHistologyType) {
this.primaryTumorHistologyType = primaryTumorHistologyType;
}
public String getPrimaryTumorNuclearGrade() {
return primaryTumorNuclearGrade;
}
public void setPrimaryTumorNuclearGrade(String primaryTumorNuclearGrade) {
this.primaryTumorNuclearGrade = primaryTumorNuclearGrade;
}
public double getPrValue() {
return prValue;
}
public void setPrValue(double prValue) {
this.prValue = prValue;
if (prValue > 0.0) {
setPrStatus(PRstatusType.PR_POS);
}
else {
setPrStatus(PRstatusType.PR_NEG);
}
}
public TimepointType getTimepoint() {
return timepoint;
}
public String getTumorMorphology() {
return tumorMorphology;
}
public void setTumorMorphology(String tumorMorphology) {
this.tumorMorphology = tumorMorphology;
}
public void setDiseaseStageFromString(String diseaseStage) {
if ((diseaseStage==null)||(diseaseStage.trim().length()==0)) {
setDiseaseStage(DiseaseStageType.MISSING);
}
else {
setDiseaseStage(DiseaseStageType.valueOf(diseaseStage));
}
}
public void setClinicalResponseFromString(String responseStr) {
if (StringUtils.isEmptyStr(responseStr)) {
setClinicalResponse(ClinicalResponseType.MISSING);
}
else if (responseStr.length() == 2) {
setClinicalResponse(ClinicalResponseType.valueOf(responseStr));
}
else if (responseStr.equalsIgnoreCase("Progressive Disease")) {
setClinicalResponse(ClinicalResponseType.PD);
}
else if (responseStr.equalsIgnoreCase("Stable Disease")) {
setClinicalResponse(ClinicalResponseType.SD);
}
else {
setClinicalResponse(ClinicalResponseType.UNKNOWN);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("LabtrackId:").append("\t").append(labtrackId).append("\n");
sb.append("PatiendId:").append("\t").append(patientId).append("\n");
sb.append("Timepoint:").append("\t").append(timepoint).append("\n");
sb.append("DiseaseStage:").append("\t").append(diseaseStage).append("\n");
sb.append("ERstatus:").append("\t").append(erStatus).append("\n");
sb.append("erValue:").append("\t").append(erValue).append("\n");
sb.append("prStatus:").append("\t").append(prStatus).append("\n");
sb.append("prValue:").append("\t").append(prValue).append("\n");
sb.append("HER2status:").append("\t").append(HER2status).append("\n");
sb.append("HER2Value:").append("\t").append(her2Value).append("\n");
sb.append("ClinicalResponse:").append("\t").append(clinicalResponse).append("\n");
sb.append("LongestDiameter:").append("\t").append(longestDiameter).append("\n");
sb.append("TumorMorphology").append("\t").append(tumorMorphology).append("\n");
sb.append("PrimaryTumorNuclearGrade:").append("\t").append(primaryTumorNuclearGrade).append("\n");
sb.append("PrimaryTumorHistologyType:").append("\t").append(primaryTumorHistologyType).append("\n");
sb.append("GrossTumorSizeInCM:").append("\t").append(grossTumorSizeInCM).append("\n");
sb.append("MicroscopeTumorSizeInCM").append("\t").append(microscopeTumorSizeInCM).append("\n");
sb.append("ChemicalAgents:").append("\t").append(StringUtils.concatinateStrings(chemicalAgents, "|")).append("\n");
sb.append("MRIpctChange:").append("\t").append(MRIpctChange).append("\n");
return sb.toString();
}
}
|
Changed from using double to Double
SVN-Revision: 3760
|
src/gov/nih/nci/ispy/service/clinical/ClinicalData.java
|
Changed from using double to Double
|
|
Java
|
bsd-3-clause
|
33c6671b6aca15880c2c64ddf8c533b7808072fd
| 0
|
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
|
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.dto.common.GridNodeBean;
import gov.nih.nci.cananolab.exception.CaNanoLabException;
import gov.nih.nci.cananolab.exception.GridAutoDiscoveryException;
import gov.nih.nci.cananolab.exception.GridDownException;
import gov.nih.nci.cananolab.service.common.GridService;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.StringUtils;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.FormFile;
/**
* This class sets up information required for all forms.
*
* @author pansu, cais
*
*/
public class InitSetup {
private InitSetup() {
}
public static InitSetup getInstance() {
return new InitSetup();
}
public Map<String, Map<String, SortedSet<String>>> getDefaultLookupTable(
ServletContext appContext) throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = null;
if (appContext.getAttribute("defaultLookupTable") == null) {
defaultLookupTable = LookupService.findAllLookups();
appContext.setAttribute("defaultLookupTable", defaultLookupTable);
} else {
defaultLookupTable = new HashMap<String, Map<String, SortedSet<String>>>(
(Map<? extends String, Map<String, SortedSet<String>>>) appContext
.getAttribute("defaultLookupTable"));
}
return defaultLookupTable;
}
/**
* Returns a map between an object name and its display name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getClassNameToDisplayNameLookup(
ServletContext appContext) throws CaNanoLabException {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameLookup") == null) {
lookup = LookupService.findSingleAttributeLookupMap("displayName");
appContext.setAttribute("displayNameLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameLookup")));
}
return lookup;
}
/**
* Returns a map between a display name and its corresponding object name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getDisplayNameToClassNameLookup(
ServletContext appContext) throws Exception {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameReverseLookup") == null) {
Map<String, String> displayLookup = LookupService
.findSingleAttributeLookupMap("displayName");
lookup = new HashMap<String, String>();
for (Map.Entry entry : displayLookup.entrySet()) {
lookup.put(entry.getValue().toString(), entry.getKey()
.toString());
}
appContext.setAttribute("displayNameReverseLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameReverseLookup")));
}
return lookup;
}
/**
* Returns a map between a display name and its corresponding full class
* name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getDisplayNameToFullClassNameLookup(
ServletContext appContext) throws Exception {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameReverseLookup") == null) {
Map<String, String> displayLookup = LookupService
.findSingleAttributeLookupMap("displayName");
lookup = new HashMap<String, String>();
for (Map.Entry entry : displayLookup.entrySet()) {
String className = entry.getKey().toString();
String fullClassName = ClassUtils.getFullClass(className)
.getCanonicalName();
lookup.put(entry.getValue().toString(), fullClassName);
}
appContext.setAttribute("displayNameReverseLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameReverseLookup")));
}
return lookup;
}
public String getDisplayName(String objectName, ServletContext appContext)
throws CaNanoLabException {
Map<String, String> lookup = getClassNameToDisplayNameLookup(appContext);
if (lookup.get(objectName) != null) {
return lookup.get(objectName);
} else {
return "";
}
}
public String getObjectName(String displayName, ServletContext appContext)
throws Exception {
Map<String, String> lookup = getDisplayNameToClassNameLookup(appContext);
if (lookup.get(displayName) != null) {
return lookup.get(displayName);
} else {
return "";
}
}
/**
* Retrieve lookup attribute and other attribute for lookup name from the
* database and store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param lookupAttribute
* @return
* @throws CaNanoLabException
*/
public SortedSet<String> getServletContextDefaultLookupTypes(
ServletContext appContext, String contextAttribute,
String lookupName, String lookupAttribute)
throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
SortedSet<String> types = defaultLookupTable.get(lookupName).get(
lookupAttribute);
appContext.setAttribute(contextAttribute, types);
return types;
}
/**
* Retrieve lookup attribute and other attribute for lookup name from the
* database and store in the session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws CaNanoLabException
*/
public SortedSet<String> getDefaultAndOtherLookupTypes(
HttpServletRequest request, String sessionAttribute,
String lookupName, String lookupAttribute,
String otherTypeAttribute, boolean updateSession)
throws CaNanoLabException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.getDefaultAndOtherLookupTypes(lookupName,
lookupAttribute, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
public List<String> getDefaultFunctionTypes(ServletContext appContext)
throws Exception {
if (appContext.getAttribute("defaultFunctionTypes") == null) {
List<String> functionTypes = new ArrayList<String>();
List<String> functionClassNames = ClassUtils
.getChildClassNames("gov.nih.nci.cananolab.domain.particle.samplecomposition.Function");
for (String name : functionClassNames) {
if (!name.contains("Other")) {
String displayName = InitSetup.getInstance()
.getDisplayName(ClassUtils.getShortClassName(name),
appContext);
functionTypes.add(displayName);
}
}
appContext.setAttribute("defaultFunctionTypes", functionTypes);
return functionTypes;
} else {
return new ArrayList<String>((List<? extends String>) appContext
.getAttribute("defaultFunctionTypes"));
}
}
/**
* Retrieve lookup attribute and other attribute for lookup name based on
* reflection and store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param fullParentClassName
* @return
* @throws Exception
*/
public SortedSet<String> getServletContextDefaultTypesByReflection(
ServletContext appContext, String contextAttribute,
String fullParentClassName) throws Exception {
if (appContext.getAttribute(contextAttribute) == null) {
SortedSet<String> types = new TreeSet<String>();
List<String> classNames = ClassUtils
.getChildClassNames(fullParentClassName);
for (String name : classNames) {
if (!name.contains("Other")) {
String displayName = InitSetup.getInstance()
.getDisplayName(ClassUtils.getShortClassName(name),
appContext);
types.add(displayName);
}
}
appContext.setAttribute(contextAttribute, types);
return types;
} else {
return new TreeSet<String>((SortedSet<? extends String>) appContext
.getAttribute(contextAttribute));
}
}
public String getFileUriFromFormFile(FormFile file, String folderType,
String particleName, String submitType) {
if (file != null && file.getFileName().length() > 0) {
String prefix = folderType;
if (particleName != null && submitType != null
&& folderType.equals(CaNanoLabConstants.FOLDER_PARTICLE)) {
prefix += "/" + particleName + "/";
prefix += StringUtils
.getOneWordLowerCaseFirstLetter(submitType);
}
String timestamp = StringUtils.convertDateToString(new Date(),
"yyyyMMdd_HH-mm-ss-SSS");
return prefix + "/" + timestamp + "_" + file.getFileName();
} else {
return null;
}
}
// check whether the value is already stored in context
private Boolean isLookupInContext(HttpServletRequest request,
String lookupName, String attribute, String otherAttribute,
String value) throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(request
.getSession().getServletContext());
SortedSet<String> defaultValues = null;
if (defaultLookupTable.get(lookupName) != null) {
defaultValues = defaultLookupTable.get(lookupName).get(attribute);
}
if (defaultValues != null && defaultValues.contains(value)) {
return true;
} else {
SortedSet<String> otherValues = null;
if (defaultLookupTable.get(lookupName) != null) {
otherValues = defaultLookupTable.get(lookupName).get(
otherAttribute);
}
if (otherValues != null && otherValues.contains(value)) {
return true;
}
}
return false;
}
public void persistLookup(HttpServletRequest request, String lookupName,
String attribute, String otherAttribute, String value)
throws CaNanoLabException {
if (value == null || value.length() == 0) {
return;
}
if (isLookupInContext(request, lookupName, attribute, otherAttribute,
value)) {
return;
} else {
LookupService.saveOtherType(lookupName, otherAttribute, value);
}
}
public String getGridServiceUrl(HttpServletRequest request,
String gridHostName) throws Exception {
List<GridNodeBean> remoteNodes = getGridNodesInContext(request);
GridNodeBean theNode = GridService.getGridNodeByHostName(remoteNodes,
gridHostName);
if (theNode == null) {
throw new GridDownException("Grid node " + gridHostName
+ " is not available at this time.");
}
return theNode.getAddress();
}
public List<GridNodeBean> getGridNodesInContext(HttpServletRequest request)
throws Exception {
URL localURL = new URL(request.getRequestURL().toString());
String localGridURL = localURL.getProtocol() + "://"
+ localURL.getHost() + ":" + localURL.getPort() + "/"
+ CaNanoLabConstants.GRID_SERVICE_PATH;
GridDiscoveryServiceJob gridDiscoveryJob = new GridDiscoveryServiceJob();
List<GridNodeBean> gridNodes = gridDiscoveryJob.getAllGridNodes();
if (gridNodes.isEmpty()) {
throw new GridAutoDiscoveryException();
}
// remove local grid from the list
GridNodeBean localGrid = GridService.getGridNodeByURL(gridNodes,
localGridURL);
if (localGrid != null) {
gridNodes.remove(localGrid);
}
request.getSession().getServletContext().setAttribute("allGridNodes",
gridNodes);
return gridNodes;
}
}
|
src/gov/nih/nci/cananolab/ui/core/InitSetup.java
|
package gov.nih.nci.cananolab.ui.core;
import gov.nih.nci.cananolab.dto.common.GridNodeBean;
import gov.nih.nci.cananolab.exception.CaNanoLabException;
import gov.nih.nci.cananolab.exception.GridDownException;
import gov.nih.nci.cananolab.service.common.GridDiscoveryServiceJob;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.upload.FormFile;
/**
* This class sets up information required for all forms.
*
* @author pansu, cais
*
*/
public class InitSetup {
private InitSetup() {
}
public static InitSetup getInstance() {
return new InitSetup();
}
public Map<String, Map<String, SortedSet<String>>> getDefaultLookupTable(
ServletContext appContext) throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = null;
if (appContext.getAttribute("defaultLookupTable") == null) {
defaultLookupTable = LookupService.findAllLookups();
appContext.setAttribute("defaultLookupTable", defaultLookupTable);
} else {
defaultLookupTable = new HashMap<String, Map<String, SortedSet<String>>>(
(Map<? extends String, Map<String, SortedSet<String>>>) appContext
.getAttribute("defaultLookupTable"));
}
return defaultLookupTable;
}
/**
* Returns a map between an object name and its display name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getClassNameToDisplayNameLookup(
ServletContext appContext) throws CaNanoLabException {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameLookup") == null) {
lookup = LookupService.findSingleAttributeLookupMap("displayName");
appContext.setAttribute("displayNameLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameLookup")));
}
return lookup;
}
/**
* Returns a map between a display name and its corresponding object name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getDisplayNameToClassNameLookup(
ServletContext appContext) throws Exception {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameReverseLookup") == null) {
Map<String, String> displayLookup = LookupService
.findSingleAttributeLookupMap("displayName");
lookup = new HashMap<String, String>();
for (Map.Entry entry : displayLookup.entrySet()) {
lookup.put(entry.getValue().toString(), entry.getKey()
.toString());
}
appContext.setAttribute("displayNameReverseLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameReverseLookup")));
}
return lookup;
}
/**
* Returns a map between a display name and its corresponding full class
* name
*
* @param appContext
* @return
* @throws CaNanoLabException
*/
public Map<String, String> getDisplayNameToFullClassNameLookup(
ServletContext appContext) throws Exception {
Map<String, String> lookup = null;
if (appContext.getAttribute("displayNameReverseLookup") == null) {
Map<String, String> displayLookup = LookupService
.findSingleAttributeLookupMap("displayName");
lookup = new HashMap<String, String>();
for (Map.Entry entry : displayLookup.entrySet()) {
String className = entry.getKey().toString();
String fullClassName = ClassUtils.getFullClass(className)
.getCanonicalName();
lookup.put(entry.getValue().toString(), fullClassName);
}
appContext.setAttribute("displayNameReverseLookup", lookup);
} else {
lookup = new HashMap<String, String>(
(Map<? extends String, String>) (appContext
.getAttribute("displayNameReverseLookup")));
}
return lookup;
}
public String getDisplayName(String objectName, ServletContext appContext)
throws CaNanoLabException {
Map<String, String> lookup = getClassNameToDisplayNameLookup(appContext);
if (lookup.get(objectName) != null) {
return lookup.get(objectName);
} else {
return "";
}
}
public String getObjectName(String displayName, ServletContext appContext)
throws Exception {
Map<String, String> lookup = getDisplayNameToClassNameLookup(appContext);
if (lookup.get(displayName) != null) {
return lookup.get(displayName);
} else {
return "";
}
}
/**
* Retrieve lookup attribute and other attribute for lookup name from the
* database and store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param lookupAttribute
* @return
* @throws CaNanoLabException
*/
public SortedSet<String> getServletContextDefaultLookupTypes(
ServletContext appContext, String contextAttribute,
String lookupName, String lookupAttribute)
throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
SortedSet<String> types = defaultLookupTable.get(lookupName).get(
lookupAttribute);
appContext.setAttribute(contextAttribute, types);
return types;
}
/**
* Retrieve lookup attribute and other attribute for lookup name from the
* database and store in the session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws CaNanoLabException
*/
public SortedSet<String> getDefaultAndOtherLookupTypes(
HttpServletRequest request, String sessionAttribute,
String lookupName, String lookupAttribute,
String otherTypeAttribute, boolean updateSession)
throws CaNanoLabException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.getDefaultAndOtherLookupTypes(lookupName,
lookupAttribute, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
public List<String> getDefaultFunctionTypes(ServletContext appContext)
throws Exception {
if (appContext.getAttribute("defaultFunctionTypes") == null) {
List<String> functionTypes = new ArrayList<String>();
List<String> functionClassNames = ClassUtils
.getChildClassNames("gov.nih.nci.cananolab.domain.particle.samplecomposition.Function");
for (String name : functionClassNames) {
if (!name.contains("Other")) {
String displayName = InitSetup.getInstance()
.getDisplayName(ClassUtils.getShortClassName(name),
appContext);
functionTypes.add(displayName);
}
}
appContext.setAttribute("defaultFunctionTypes", functionTypes);
return functionTypes;
} else {
return new ArrayList<String>((List<? extends String>) appContext
.getAttribute("defaultFunctionTypes"));
}
}
/**
* Retrieve lookup attribute and other attribute for lookup name based on
* reflection and store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param fullParentClassName
* @return
* @throws Exception
*/
public SortedSet<String> getServletContextDefaultTypesByReflection(
ServletContext appContext, String contextAttribute,
String fullParentClassName) throws Exception {
if (appContext.getAttribute(contextAttribute) == null) {
SortedSet<String> types = new TreeSet<String>();
List<String> classNames = ClassUtils
.getChildClassNames(fullParentClassName);
for (String name : classNames) {
if (!name.contains("Other")) {
String displayName = InitSetup.getInstance()
.getDisplayName(ClassUtils.getShortClassName(name),
appContext);
types.add(displayName);
}
}
appContext.setAttribute(contextAttribute, types);
return types;
} else {
return new TreeSet<String>((SortedSet<? extends String>) appContext
.getAttribute(contextAttribute));
}
}
public String getFileUriFromFormFile(FormFile file, String folderType,
String particleName, String submitType) {
if (file != null && file.getFileName().length() > 0) {
String prefix = folderType;
if (particleName != null && submitType != null
&& folderType.equals(CaNanoLabConstants.FOLDER_PARTICLE)) {
prefix += "/" + particleName + "/";
prefix += StringUtils
.getOneWordLowerCaseFirstLetter(submitType);
}
String timestamp = StringUtils.convertDateToString(new Date(),
"yyyyMMdd_HH-mm-ss-SSS");
return prefix + "/" + timestamp + "_" + file.getFileName();
} else {
return null;
}
}
// check whether the value is already stored in context
private Boolean isLookupInContext(HttpServletRequest request,
String lookupName, String attribute, String otherAttribute,
String value) throws CaNanoLabException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(request
.getSession().getServletContext());
SortedSet<String> defaultValues = null;
if (defaultLookupTable.get(lookupName) != null) {
defaultValues = defaultLookupTable.get(lookupName).get(attribute);
}
if (defaultValues != null && defaultValues.contains(value)) {
return true;
} else {
SortedSet<String> otherValues = null;
if (defaultLookupTable.get(lookupName) != null) {
otherValues = defaultLookupTable.get(lookupName).get(
otherAttribute);
}
if (otherValues != null && otherValues.contains(value)) {
return true;
}
}
return false;
}
public void persistLookup(HttpServletRequest request, String lookupName,
String attribute, String otherAttribute, String value)
throws CaNanoLabException {
if (value == null || value.length() == 0) {
return;
}
if (isLookupInContext(request, lookupName, attribute, otherAttribute,
value)) {
return;
} else {
LookupService.saveOtherType(lookupName, otherAttribute, value);
}
}
public String getGridServiceUrl(HttpServletRequest request,
String gridHostName) throws Exception {
GridDiscoveryServiceJob gridDiscoveryJob = new GridDiscoveryServiceJob();
Map<String, GridNodeBean> gridNodeMap = gridDiscoveryJob
.getAllGridNodes();
request.getSession().getServletContext().setAttribute("allGridNodes",
gridNodeMap);
String serviceUrl = gridNodeMap.get(gridHostName).getAddress();
if (serviceUrl == null) {
throw new GridDownException("Grid node " + gridHostName
+ " is not available at this time.");
}
return serviceUrl;
}
}
|
added getGridNodesInContext and updated getGridServiceUrl
SVN-Revision: 6467
|
src/gov/nih/nci/cananolab/ui/core/InitSetup.java
|
added getGridNodesInContext and updated getGridServiceUrl
|
|
Java
|
mit
|
a93cb52e7a399ccf4304760e60f54878023735d9
| 0
|
jbosboom/streamjit,jbosboom/streamjit
|
package edu.mit.streamjit.tuner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
public final class TCPTuner implements AutoTuner {
Process tuner;
TunerConnection connection;
@Override
public String readLine() throws IOException {
if (connection == null)
throw new AssertionError(
"Connection with the Autotuner is not established yet.");
return connection.readLine();
}
@Override
public int writeLine(String message) throws IOException {
if (connection == null)
throw new AssertionError(
"Connection with the Autotuner is not established yet.");
connection.writeLine(message);
return message.length();
}
@Override
public boolean isAlive() {
if (tuner == null)
return false;
try {
tuner.exitValue();
return false;
} catch (IllegalThreadStateException ex) {
return true;
}
}
@Override
public void startTuner(String tunerPath) throws IOException {
int min = 5000;
Random rand = new Random();
Integer port = rand.nextInt(65535 - min) + min;
this.tuner = new ProcessBuilder("xterm", "-e", "python", tunerPath,
port.toString()).start();
this.connection = new TunerConnection();
connection.connect(port);
}
@Override
public void stopTuner() throws IOException {
if (tuner == null)
return;
if (connection != null && connection.isStillConnected())
connection.writeLine("exit\n");
else
tuner.destroy();
try {
tuner.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (connection != null && !isAlive()) {
connection.closeConnection();
}
}
/**
* Communicate with the Autotuner over the local host TCP connection.
*
* @author sumanan
*
*/
private final class TunerConnection {
private BufferedReader reader = null;
private BufferedWriter writter = null;
private Socket socket = null;
private boolean isconnected = false;
void connect(int port) throws IOException {
Socket socket;
while (true) {
try {
socket = new Socket("localhost", port);
System.out.println("Autotuner is connected...");
this.socket = socket;
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.reader = new BufferedReader(new InputStreamReader(is));
this.writter = new BufferedWriter(
new OutputStreamWriter(os));
isconnected = true;
break;
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
System.out
.println("Trying to make TCP connection with Autotuner. It seems Autotuner is not up yet.");
// Lets wait for a second before attempting next.
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
public void writeLine(String msg) throws IOException {
if (isStillConnected()) {
try {
writter.write(msg);
if(msg.toCharArray()[msg.length() - 1] != '\n')
writter.write('\n');
writter.flush();
} catch (IOException ix) {
isconnected = false;
throw ix;
}
} else {
throw new IOException("TCPConnection: Socket is not connected");
}
}
String readLine() throws IOException {
if (isStillConnected()) {
try {
return reader.readLine();
} catch (IOException e) {
isconnected = false;
throw e;
}
} else {
throw new IOException("TCPConnection: Socket is not connected");
}
}
public final void closeConnection() {
isconnected = false;
try {
if (reader != null)
this.reader.close();
if (writter != null)
this.writter.close();
if (socket != null)
this.socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
boolean isStillConnected() {
return isconnected;
}
}
public static void main(String[] args) throws InterruptedException,
IOException {
AutoTuner tuner = new TCPTuner();
try {
tuner.startTuner("/lib/opentuner/streamjit/streamjit.py");
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(1000);
try {
tuner.stopTuner();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
src/edu/mit/streamjit/tuner/TCPTuner.java
|
package edu.mit.streamjit.tuner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
public final class TCPTuner implements AutoTuner {
Process tuner;
TunerConnection connection;
@Override
public String readLine() throws IOException {
if (connection == null)
throw new AssertionError(
"Connection with the Autotuner is not established yet.");
return connection.readLine();
}
@Override
public int writeLine(String message) throws IOException {
if (connection == null)
throw new AssertionError(
"Connection with the Autotuner is not established yet.");
connection.writeLine(message);
return message.length();
}
@Override
public boolean isAlive() {
if (tuner == null)
return false;
try {
tuner.exitValue();
return false;
} catch (IllegalThreadStateException ex) {
return true;
}
}
@Override
public void startTuner(String tunerPath) throws IOException {
int min = 5000;
Random rand = new Random();
Integer port = rand.nextInt(65535 - min) + min;
this.tuner = new ProcessBuilder("xterm", "-e", "python", tunerPath,
port.toString()).start();
this.connection = new TunerConnection();
connection.connect(port);
}
@Override
public void stopTuner() throws IOException {
if (tuner == null)
return;
if (connection != null && connection.isStillConnected())
connection.writeLine("exit\n");
else
tuner.destroy();
try {
tuner.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (connection != null && !isAlive()) {
connection.closeConnection();
}
}
/**
* Communicate with the Autotuner over the local host TCP connection.
*
* @author sumanan
*
*/
private final class TunerConnection {
private BufferedReader reader = null;
private BufferedWriter writter = null;
private Socket socket = null;
private boolean isconnected = false;
void connect(int port) throws IOException {
Socket socket;
System.out.println("Going to make a connection with the server...");
while (true) {
try {
socket = new Socket("localhost", port);
System.out.println("Client connected...");
this.socket = socket;
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.reader = new BufferedReader(new InputStreamReader(is));
this.writter = new BufferedWriter(
new OutputStreamWriter(os));
isconnected = true;
break;
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
System.out
.println("Trying to make TCP connection with Autotuner. It seems Autotuner is not up yet.");
// Lets wait for a second before attempting next.
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
public void writeLine(String msg) throws IOException {
if (isStillConnected()) {
try {
writter.write(msg);
if(msg.toCharArray()[msg.length() - 1] != '\n')
writter.write('\n');
writter.flush();
} catch (IOException ix) {
isconnected = false;
throw ix;
}
} else {
throw new IOException("TCPConnection: Socket is not connected");
}
}
String readLine() throws IOException {
if (isStillConnected()) {
try {
return reader.readLine();
} catch (IOException e) {
isconnected = false;
throw e;
}
} else {
throw new IOException("TCPConnection: Socket is not connected");
}
}
public final void closeConnection() {
isconnected = false;
try {
if (reader != null)
this.reader.close();
if (writter != null)
this.writter.close();
if (socket != null)
this.socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
boolean isStillConnected() {
return isconnected;
}
}
public static void main(String[] args) throws InterruptedException,
IOException {
AutoTuner tuner = new TCPTuner();
try {
tuner.startTuner("/lib/opentuner/streamjit/streamjit.py");
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(1000);
try {
tuner.stopTuner();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
print messages have been formated
|
src/edu/mit/streamjit/tuner/TCPTuner.java
|
print messages have been formated
|
|
Java
|
mit
|
9e85cb6b8bb437feed28749952e23d9696ce7c2a
| 0
|
evan10s/wake-me-cgm,evan10s/wake-me-cgm
|
package at.str.evan.wakemecgm;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.Date;
import java.util.Locale;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private final String TAG = "WAKEMECGM";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(new NotificationChannel("HIGH_ALERTS", "High BG Alerts", NotificationManager.IMPORTANCE_HIGH));
notificationManager.createNotificationChannel(new NotificationChannel("LOW_ALERTS", "Low BG Alerts", NotificationManager.IMPORTANCE_HIGH));
}
}
final Button confirmAlertBtn = findViewById(R.id.confirm_alert);
confirmAlertBtn.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if (BgUpdateService.runningAlert != null) {
BgUpdateService.runningAlert.interrupt();
}
}
});
Realm realm = Realm.getDefaultInstance();
final RealmResults<BGReading> last24Hr = realm.where(BGReading.class).greaterThan("timestamp", new Date(System.currentTimeMillis() - 86400 * 1000)).findAll();
final ScatterChart chart = findViewById(R.id.chart);
RealmScatterDataSet<BGReading> dataSet = new RealmScatterDataSet<>(last24Hr, "timeDecimal", "reading");
dataSet.setColor(Color.BLACK);
dataSet.setValueTextColor(Color.BLUE);
dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
ScatterData lineData = new ScatterData(dataSet);
chart.setData(lineData);
chart.setScaleYEnabled(false);
chart.getLegend().setEnabled(false);
chart.getLegend().setForm(Legend.LegendForm.CIRCLE);
chart.getDescription().setEnabled(false);
chart.setVisibleXRangeMinimum(1);
chart.setVisibleXRangeMaximum(3);
chart.setVisibleXRangeMaximum(24);
lineData.setDrawValues(false);
YAxis rightAxis = chart.getAxisRight();
rightAxis.setAxisMinimum(40);
rightAxis.setAxisMaximum(400);
YAxis leftAxis = chart.getAxisLeft();
leftAxis.setEnabled(false);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1);
IAxisValueFormatter xAxisFormatter = new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int hours = (int) value;
float mins = value - hours;
int newHours = hours;
Log.i(TAG, "getFormattedValue: " + value);
Log.i(TAG, "getFormattedValue: " + mins);
int minsInt = Math.round(mins * 60);
String AMPM = "AM";
if (hours > 12) {
newHours = hours - 12;
AMPM = "PM";
} else if (hours == 0) {
newHours = 12;
AMPM = "AM";
} else if (hours == 12) {
newHours = 12;
AMPM = "PM";
}
String minsStr = (minsInt < 10) ? "0" + minsInt : "" + minsInt;
return newHours + ":" + minsStr + " " + AMPM;
}
};
xAxis.setValueFormatter(xAxisFormatter);
LimitLine low = new LimitLine(65, "");
low.setLineColor(Color.RED);
low.setLineWidth(1f);
low.setTextSize(12f);
LimitLine high = new LimitLine(240, "");
high.setLineColor(Color.rgb(255,171,0));
high.setLineWidth(1f);
high.setTextSize(12f);
rightAxis.addLimitLine(low);
rightAxis.addLimitLine(high);
chart.invalidate(); // refresh
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.at.str.evan.wakemecgm.BG_DATA",Context.MODE_PRIVATE);
int lastBg = sharedPref.getInt("lastBg", -1);
String lastTrend = sharedPref.getString("lastTrend","");
long startDate = sharedPref.getLong("startDate",-1);
Log.d("WAKEMECGM", "stored prev BG: " + lastBg);
if (startDate == -1) {
SharedPreferences.Editor editor2 = sharedPref.edit();
editor2.putLong("startDate",new Date().getTime());
editor2.apply();
}
RealmChangeListener<Realm> realmListener = new RealmChangeListener<Realm>() {
@Override
public void onChange(Realm realm) {
BGReading lastBGObj = realm.where(BGReading.class).sort("timestamp").findAll().last();
if (lastBGObj != null) {
int bg = (int) lastBGObj.getReading();
String trend = lastBGObj.getTrend();
Log.i(TAG, "onChange: BG reading is " + bg);
Log.i(TAG, "onChange: Trend is " + trend);
updateBGTextView(bg, trend);
chart.notifyDataSetChanged();
chart.invalidate();
}
}
};
realm.addChangeListener(realmListener);
updateBGTextView(lastBg, lastTrend);
}
private void updateBGTextView(int bg, String trend) {
//Sensor stopped, latest_bg=1
//Sensor warm-up, latest_bg=5
TextView lastBgTextView = findViewById(R.id.bg);
if (bg == 1) {
lastBgTextView.setText(R.string.sensor_stopped);
} else if (bg == 5) {
lastBgTextView.setText(R.string.sensor_warmup);
} else if (bg == 39) {
lastBgTextView.setText(R.string.LOW);
} else if (bg >= 40 && bg <= 401) {
lastBgTextView.setText(String.format(Locale.getDefault(), "%d %s", bg, trend));
} else {
lastBgTextView.setText("---");
}
}
}
|
app/src/main/java/at/str/evan/wakemecgm/MainActivity.java
|
package at.str.evan.wakemecgm;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.Date;
import java.util.Locale;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;
public class MainActivity extends AppCompatActivity {
private final String TAG = "WAKEMECGM";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.createNotificationChannel(new NotificationChannel("HIGH_ALERTS", "High BG Alerts", NotificationManager.IMPORTANCE_HIGH));
notificationManager.createNotificationChannel(new NotificationChannel("LOW_ALERTS", "Low BG Alerts", NotificationManager.IMPORTANCE_HIGH));
}
}
final Button confirmAlertBtn = findViewById(R.id.confirm_alert);
confirmAlertBtn.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
if (BgUpdateService.runningAlert != null) {
BgUpdateService.runningAlert.interrupt();
}
}
});
Realm realm = Realm.getDefaultInstance();
final RealmResults<BGReading> last24Hr = realm.where(BGReading.class).greaterThan("timestamp", new Date(System.currentTimeMillis() - 86400 * 1000)).findAll();
final ScatterChart chart = findViewById(R.id.chart);
RealmScatterDataSet<BGReading> dataSet = new RealmScatterDataSet<>(last24Hr, "timeDecimal", "reading");
dataSet.setColor(Color.BLACK);
dataSet.setValueTextColor(Color.BLUE);
dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
dataSet.setScatterShape(ScatterChart.ScatterShape.CIRCLE);
ScatterData lineData = new ScatterData(dataSet);
chart.setData(lineData);
chart.setScaleYEnabled(false);
chart.getLegend().setEnabled(false);
chart.getLegend().setForm(Legend.LegendForm.CIRCLE);
chart.getDescription().setEnabled(false);
chart.setVisibleXRangeMinimum(1);
chart.setVisibleXRangeMaximum(3);
chart.setVisibleXRangeMaximum(24);
lineData.setDrawValues(false);
YAxis rightAxis = chart.getAxisRight();
rightAxis.setAxisMinimum(40);
rightAxis.setAxisMaximum(400);
YAxis leftAxis = chart.getAxisLeft();
leftAxis.setEnabled(false);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1);
IAxisValueFormatter xAxisFormatter = new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int hours = (int) value;
int newHours = hours;
String AMPM = "AM";
if (hours > 12) {
newHours = hours - 12;
AMPM = "PM";
} else if (hours == 0) {
newHours = 12;
AMPM = "AM";
} else if (hours == 12) {
newHours = 12;
AMPM = "PM";
}
return newHours /*+ ":" + minutes + " "*/+ " " + AMPM;
}
};
xAxis.setValueFormatter(xAxisFormatter);
LimitLine low = new LimitLine(65, "");
low.setLineColor(Color.RED);
low.setLineWidth(1f);
low.setTextSize(12f);
LimitLine high = new LimitLine(240, "");
high.setLineColor(Color.rgb(255,171,0));
high.setLineWidth(1f);
high.setTextSize(12f);
rightAxis.addLimitLine(low);
rightAxis.addLimitLine(high);
chart.invalidate(); // refresh
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.at.str.evan.wakemecgm.BG_DATA",Context.MODE_PRIVATE);
int lastBg = sharedPref.getInt("lastBg", -1);
String lastTrend = sharedPref.getString("lastTrend","");
long startDate = sharedPref.getLong("startDate",-1);
Log.d("WAKEMECGM", "stored prev BG: " + lastBg);
if (startDate == -1) {
SharedPreferences.Editor editor2 = sharedPref.edit();
editor2.putLong("startDate",new Date().getTime());
editor2.apply();
}
RealmChangeListener<Realm> realmListener = new RealmChangeListener<Realm>() {
@Override
public void onChange(Realm realm) {
BGReading lastBGObj = realm.where(BGReading.class).sort("timestamp").findAll().last();
if (lastBGObj != null) {
int bg = (int) lastBGObj.getReading();
String trend = lastBGObj.getTrend();
Log.i(TAG, "onChange: BG reading is " + bg);
Log.i(TAG, "onChange: Trend is " + trend);
updateBGTextView(bg, trend);
chart.notifyDataSetChanged();
chart.invalidate();
}
}
};
realm.addChangeListener(realmListener);
updateBGTextView(lastBg, lastTrend);
}
private void updateBGTextView(int bg, String trend) {
//Sensor stopped, latest_bg=1
//Sensor warm-up, latest_bg=5
TextView lastBgTextView = findViewById(R.id.bg);
if (bg == 1) {
lastBgTextView.setText(R.string.sensor_stopped);
} else if (bg == 5) {
lastBgTextView.setText(R.string.sensor_warmup);
} else if (bg == 39) {
lastBgTextView.setText(R.string.LOW);
} else if (bg >= 40 && bg <= 401) {
lastBgTextView.setText(String.format(Locale.getDefault(), "%d %s", bg, trend));
} else {
lastBgTextView.setText("---");
}
}
}
|
Start of an attempt to fix the graph
|
app/src/main/java/at/str/evan/wakemecgm/MainActivity.java
|
Start of an attempt to fix the graph
|
|
Java
|
mit
|
bee8cad2b7f4d4ffdad4d7d45bef9e7d5320cabe
| 0
|
ebaldino/beaconz,tastybento/beaconz
|
/*
* Copyright (c) 2016 tastybento
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wasteofplastic.beaconz;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.wasteofplastic.beaconz.listeners.BeaconLinkListener;
/**
* Enables inventory switching between games. Handles food, experience and spawn points.
* @author tastybento
*
*/
public class BeaconzStore extends BeaconzPluginDependent {
private YamlConfiguration ymlIndex;
private File invFile;
private static final boolean DEBUG = false;
public BeaconzStore(Beaconz beaconzPlugin) {
super(beaconzPlugin);
ymlIndex = new YamlConfiguration();
invFile = new File(beaconzPlugin.getDataFolder(),"game_inv.yml");
try {
if (!invFile.exists()) {
ymlIndex.save(invFile);
}
ymlIndex.load(invFile);
} catch (Exception e) {
getLogger().severe("Cannot save or load game_inv.yml!");
}
}
/**
* Saves the location of all the chests to a file
*/
public void saveInventories() {
try {
ymlIndex.save(invFile);
} catch (IOException e) {
getLogger().severe("Problem saving game inventories file!");
}
}
/**
* Gets items for world. Changes the inventory of player immediately.
* @param player
* @param gameName
* @return last location of the player in the game or null if there is none
*/
public Location getInventory(Player player, String gameName) {
// Get inventory
List<?> items = ymlIndex.getList(gameName + "." + player.getUniqueId().toString() + ".inventory");
if (items != null) player.getInventory().setContents(items.toArray(new ItemStack[items.size()]));
double health = ymlIndex.getDouble(gameName + "." + player.getUniqueId().toString() + ".health", 20D);
if (health > 20D) {
health = 20D;
}
if (health < 0D) {
health = 0D;
}
player.setHealth(health);
int food = ymlIndex.getInt(gameName + "." + player.getUniqueId().toString() + ".food", 20);
if (food > 20) {
food = 20;
}
if (food < 0) {
food = 0;
}
player.setFoodLevel(food);
BeaconLinkListener.setTotalExperience(player, ymlIndex.getInt(gameName + "." + player.getUniqueId().toString() + ".exp", 0));
// Get Spawn Point
return (Location)(ymlIndex.get(gameName + "." + player.getUniqueId().toString() + ".location"));
}
/**
* Puts the player's inventory into the right chest
* @param player
* @param gameName - the game name for the inventory being store
* @param from - the last position of the player in this game
*/
public void storeInventory(Player player, String gameName, Location from) {
storeInventory(player, gameName, from, true);
}
/**
* Puts the player's inventory into the right chest
* @param player
* @param gameName
* @param from
* @param storeInv - whether the inventory should be stored or not
*/
public void storeInventory(Player player, String gameName, Location from, boolean storeInv) {
if (DEBUG)
getLogger().info("DEBUG: storeInventory for " + player.getName() + " leaving " + gameName + " from " + from);
// Copy the player's items to the chest
List<ItemStack> contents = Arrays.asList(player.getInventory().getContents());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".inventory", contents);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".health", player.getHealth());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".food", player.getFoodLevel());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".exp", BeaconLinkListener.getTotalExperience(player));
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".location", player.getLocation());
saveInventories();
// Clear the player's inventory
player.getInventory().clear();
BeaconLinkListener.setTotalExperience(player, 0);
// Done!
if (DEBUG)
getLogger().info("DEBUG: Done!");
}
/**
* Marks all the chests related to a particular game as empty. Chests are not actually emptied until they are reused.
* @param gameName
*/
public void removeGame(String gameName) {
ymlIndex.set(gameName, null);
saveInventories();
}
/**
* Clears all the items for player in game name, sets the respawn point
* @param player
* @param name
* @param spawnPoint
*/
public void clearItems(Player player, String gameName, Location from) {
getLogger().info("DEBUG: clear inventory for " + player.getName() + " in " + gameName);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".inventory", null);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".location", from);
saveInventories();
}
/**
* Sets the player's food level in game
* @param player
* @param gameName
* @param foodLevel
*/
public void setFood(Player player, String gameName, int foodLevel) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".food", foodLevel);
saveInventories();
}
/**
* Sets player's health in game
* @param player
* @param gameName
* @param maxHealth
*/
public void setHealth(Player player, String gameName, double maxHealth) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".health", maxHealth);
saveInventories();
}
/**
* Sets player's exp in game
* @param player
* @param gameName
* @param newExp
*/
public void setExp(Player player, String gameName, int newExp) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".exp", newExp);
saveInventories();
}
}
|
src/main/java/com/wasteofplastic/beaconz/BeaconzStore.java
|
/*
* Copyright (c) 2016 tastybento
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wasteofplastic.beaconz;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.wasteofplastic.beaconz.listeners.BeaconLinkListener;
/**
* Enables inventory switching between games. Handles food, experience and spawn points.
* @author tastybento
*
*/
public class BeaconzStore extends BeaconzPluginDependent {
private YamlConfiguration ymlIndex;
private File invFile;
private static final boolean DEBUG = false;
public BeaconzStore(Beaconz beaconzPlugin) {
super(beaconzPlugin);
ymlIndex = new YamlConfiguration();
invFile = new File(beaconzPlugin.getDataFolder(),"game_inv.yml");
try {
if (!invFile.exists()) {
ymlIndex.save(invFile);
}
ymlIndex.load(invFile);
} catch (Exception e) {
getLogger().severe("Cannot save or load game_inv.yml!");
}
}
/**
* Saves the location of all the chests to a file
*/
public void saveInventories() {
try {
ymlIndex.save(invFile);
} catch (IOException e) {
getLogger().severe("Problem saving game inventories file!");
}
}
/**
* Gets items for world. Changes the inventory of player immediately.
* @param player
* @param gameName
* @return last location of the player in the game or null if there is none
*/
public Location getInventory(Player player, String gameName) {
// Get inventory
List<?> items = ymlIndex.getList(gameName + "." + player.getUniqueId().toString() + ".inventory");
if (items != null) player.getInventory().setContents(items.toArray(new ItemStack[items.size()]));
player.setHealth(ymlIndex.getDouble(gameName + "." + player.getUniqueId().toString() + ".health", 20D));
player.setFoodLevel(ymlIndex.getInt(gameName + "." + player.getUniqueId().toString() + ".food", 20));
BeaconLinkListener.setTotalExperience(player, ymlIndex.getInt(gameName + "." + player.getUniqueId().toString() + ".exp", 0));
// Get Spawn Point
return (Location)(ymlIndex.get(gameName + "." + player.getUniqueId().toString() + ".location"));
}
/**
* Puts the player's inventory into the right chest
* @param player
* @param gameName - the game name for the inventory being store
* @param from - the last position of the player in this game
*/
public void storeInventory(Player player, String gameName, Location from) {
storeInventory(player, gameName, from, true);
}
/**
* Puts the player's inventory into the right chest
* @param player
* @param gameName
* @param from
* @param storeInv - whether the inventory should be stored or not
*/
public void storeInventory(Player player, String gameName, Location from, boolean storeInv) {
if (DEBUG)
getLogger().info("DEBUG: storeInventory for " + player.getName() + " leaving " + gameName + " from " + from);
// Copy the player's items to the chest
List<ItemStack> contents = Arrays.asList(player.getInventory().getContents());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".inventory", contents);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".health", player.getHealth());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".food", player.getFoodLevel());
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".exp", BeaconLinkListener.getTotalExperience(player));
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".location", player.getLocation());
saveInventories();
// Clear the player's inventory
player.getInventory().clear();
BeaconLinkListener.setTotalExperience(player, 0);
// Done!
if (DEBUG)
getLogger().info("DEBUG: Done!");
}
/**
* Marks all the chests related to a particular game as empty. Chests are not actually emptied until they are reused.
* @param gameName
*/
public void removeGame(String gameName) {
ymlIndex.set(gameName, null);
saveInventories();
}
/**
* Clears all the items for player in game name, sets the respawn point
* @param player
* @param name
* @param spawnPoint
*/
public void clearItems(Player player, String gameName, Location from) {
getLogger().info("DEBUG: clear inventory for " + player.getName() + " in " + gameName);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".inventory", null);
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".spawn", Beaconz.getStringLocation(from));
saveInventories();
}
/**
* Sets the player's food level in game
* @param player
* @param gameName
* @param foodLevel
*/
public void setFood(Player player, String gameName, int foodLevel) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".food", foodLevel);
saveInventories();
}
/**
* Sets player's health in game
* @param player
* @param gameName
* @param maxHealth
*/
public void setHealth(Player player, String gameName, double maxHealth) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".health", maxHealth);
saveInventories();
}
/**
* Sets player's exp in game
* @param player
* @param gameName
* @param newExp
*/
public void setExp(Player player, String gameName, int newExp) {
ymlIndex.set(gameName + "." + player.getUniqueId().toString() + ".exp", newExp);
saveInventories();
}
}
|
Added some checks on the limits of health and food.
|
src/main/java/com/wasteofplastic/beaconz/BeaconzStore.java
|
Added some checks on the limits of health and food.
|
|
Java
|
mit
|
38b5fb4a3b293b9ab3a315c23ac02bed2edb73f1
| 0
|
kjian279/slogo,czarlos/Simple-Logo
|
package controller;
import view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import parser.Constants;
import model.Model;
import model.State;
/**
* Command string in happens here, sends this string
* to the model to be sent to be processed.
* Controller also receives processed info and then updates
* the view based on this info.
* @author carlosreyes kevinjian
*/
public class Controller {
private Model myModel;
private View myView;
/**
* constructor for controller
* @param view - view object
* @param model - model object
*/
public Controller(View view, Model model){
myView = view;
myModel=model;
}
public void processInput(String string) {
try {
myModel.processString(string);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//List<Line> trail = getLines();
getStates();
double[] turtlePosition = getTurtle();
/* for (Line line:trail) {
//view.drawLine
}*/
myView.drawTurtle(turtlePosition);
}
/* *//**
* passes user input to model to process
* @param input - String of user input
* @throws Exception
*//*
public void processString(String string) throws Exception{
myModel.processString(string);
myView.
}*/
/**
* gets current State of turtle
* @return State of turtle
*/
public State modelCurrentState() {
return myModel.getCurrentState();
}
/**
* gets turtle states
* @return List of Lines that create trail
*/
public List<State> getStates() {
myModel.createStates();
return myModel.getStates();
}
public List<Line> getLines() {
List<State> states = getStates();
List<Line> lines = new ArrayList<Line>();
for (int i=0; i<states.size()-1; i++){
Line line = new Line();
line.setCoord1(states.get(i).getX(), states.get(i).getY());
line.setCoord2(states.get(i+1).getX(), states.get(i+1).getY());
lines.add(line);
}
return lines;
}
public double[] getTurtle() {
if (myModel.getCurrentState().getTurtleVisible().equals(Constants.TURTLE_NOTSHOWING)) return null;
else {
double[] coordinates = {myModel.getX(), myModel.getY(), myModel.getOrientation()};
return coordinates;
}
}
public Map getVariables() {
return myModel.getVariableMap();
}
}
|
src/controller/Controller.java
|
package controller;
import view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import parser.Constants;
import model.Model;
import model.State;
/**
* Command string in happens here, sends this string
* to the model to be sent to be processed.
* Controller also receives processed info and then updates
* the view based on this info.
* @author carlosreyes kevinjian
*/
public class Controller {
private Model myModel;
private View myView;
/**
* constructor for controller
* @param view - view object
* @param model - model object
*/
public Controller(View view, Model model){
myView = view;
myModel=model;
}
public void processInput(String string) {
try {
myModel.processString(string);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//List<Line> trail = getLines();
double[] turtlePosition = getTurtle();
/* for (Line line:trail) {
//view.drawLine
}*/
myView.drawTurtle(turtlePosition);
}
/* *//**
* passes user input to model to process
* @param input - String of user input
* @throws Exception
*//*
public void processString(String string) throws Exception{
myModel.processString(string);
myView.
}*/
/**
* gets current State of turtle
* @return State of turtle
*/
public State modelCurrentState() {
return myModel.getCurrentState();
}
/**
* gets turtle states
* @return List of Lines that create trail
*/
public List<State> getStates() {
myModel.createStates();
return myModel.getStates();
}
public List<Line> getLines() {
List<State> states = getStates();
List<Line> lines = new ArrayList<Line>();
for (int i=0; i<states.size()-1; i++){
Line line = new Line();
line.setCoord1(states.get(i).getX(), states.get(i).getY());
line.setCoord2(states.get(i+1).getX(), states.get(i+1).getY());
lines.add(line);
}
return lines;
}
public double[] getTurtle() {
if (myModel.getCurrentState().getTurtleVisible().equals(Constants.TURTLE_NOTSHOWING)) return null;
else {
double[] coordinates = {myModel.getX(), myModel.getY(), myModel.getOrientation()};
return coordinates;
}
}
public Map getVariables() {
return myModel.getVariableMap();
}
}
|
fixed missing method in controller
|
src/controller/Controller.java
|
fixed missing method in controller
|
|
Java
|
mit
|
82cddbc0a4d80c4fea60b9ceb59ee2321a038159
| 0
|
fanout/java-gripcontrol
|
package org.fanout.gripcontrol;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.*;
import static org.junit.Assert.*;
public class GripControlTest {
@Test
public void testCreateHold() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHold("mode", channels, null, 0);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHold("mode", channels, null, 0);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHold("mode", channels, response, 0);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
hold = GripControl.createHold("mode", channels, response, 5);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}],\"timeout\":5}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateHoldResponse() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHoldResponse(channels);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHoldResponse(channels);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHoldResponse(channels, response);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
hold = GripControl.createHoldResponse(channels, response, 5);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}],\"timeout\":5}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateHoldStream() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHoldStream(channels);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHoldStream(channels);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHoldStream(channels, response);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateGripChannelHeader() {
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String header = GripControl.createGripChannelHeader(channels);
assertEquals(header, "chan1");
channels.add(new Channel("chan2", "prev-id"));
header = GripControl.createGripChannelHeader(channels);
assertEquals(header, "chan1, chan2; prev-id=prev-id");
}
@Test
public void testWebSocketControlMessage() {
String message = GripControl.webSocketControlMessage("type", null);
assertEquals(message, "{\"type\":\"type\"}");
Map<String, Object> args = new HashMap<String, Object>();
args.put("arg1", "value1");
args.put("arg2", "value2");
message = GripControl.webSocketControlMessage("type", args);
assertEquals(message, "{\"arg2\":\"value2\",\"arg1\":\"value1\",\"type\":\"type\"}");
}
@Test
public void testParseGripUri() throws UnsupportedEncodingException, MalformedURLException {
String url = "http://test.com/path";
Map<String, Object> parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com/path");
url = "http://test.com/path?arg1=val1";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com/path?arg1=val1");
url = "http://test.com:8900/path?arg1=val1&arg2=val2";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
url = "http://test.com:8900/path?arg1=val1&arg2=val2&iss=claim";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
url = "http://test.com:8900/path?arg1=val1&arg2=val2&iss=claim&key=keyval";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
assertEquals(parsedUri.get("key"), "keyval");
url = "https://test.com:8900/path?arg1=val1&arg2=val2&iss=claim&key=base64:aGVsbG8=";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "https://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
assertEquals(parsedUri.get("key"), "hello");
}
@Test
public void testValidateSig() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwidGVzdGlzcy" +
"JdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoyNTUxMDQ2Mjg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJq" +
"cm9ja2V0QGV4YW1wbGUuY29tIn0.Wmm-ulXbOun3egbdqmxjCqegyYu8Tr5MAaguie4rmTE";
String key = "a2V5";
assertTrue(GripControl.validateSig(token, key));
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwidGVzdGlzcy" +
"JdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoyNTUxMDQ2Mjg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJq" +
"cm9ja2V0QGV4YW1wbGUuY29tIn0.Wmm-ulXbOun3egbdqmxjCqegyYu8Tr5MAaguie4rmTE";
key = "d3JvbmdrZXk=";
assertFalse(GripControl.validateSig(token, key));
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwi" +
"dGVzdGlzcyJdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoxMDA0NzQ1NDg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLC" +
"JzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIn0.W8e4mxvbMKuotkINOyZX5jDO7KFD-jpgPHbWNGV5CHQ";
key = "a2V5";
assertFalse(GripControl.validateSig(token, key));
}
@Test
public void testEncodeWebSocketEvents() {
List<WebSocketEvent> events = new ArrayList<WebSocketEvent>();
events.add(new WebSocketEvent("TEXT", "Hello"));
events.add(new WebSocketEvent("TEXT", ""));
events.add(new WebSocketEvent("TEXT"));
assertEquals(GripControl.encodeWebSocketEvents(events), "TEXT 5\r\nHello\r\nTEXT 0\r\n\r\nTEXT\r\n");
events = new ArrayList<WebSocketEvent>();
events.add(new WebSocketEvent("OPEN"));
assertEquals(GripControl.encodeWebSocketEvents(events), "OPEN\r\n");
}
@Test
public void testDecodeWebSocketEvents() throws IllegalArgumentException {
List<WebSocketEvent> events = GripControl.decodeWebSocketEvents("OPEN\r\nTEXT 5\r\nHello" +
"\r\nTEXT 0\r\n\r\nCLOSE\r\nTEXT\r\nCLOSE\r\n");
assertEquals(events.size(), 6);
assertEquals(events.get(0).type, "OPEN");
assertEquals(events.get(0).content, null);
assertEquals(events.get(1).type, "TEXT");
assertEquals(events.get(1).content, "Hello");
assertEquals(events.get(2).type, "TEXT");
assertEquals(events.get(2).content, "");
assertEquals(events.get(3).type, "CLOSE");
assertEquals(events.get(3).content, null);
assertEquals(events.get(4).type, "TEXT");
assertEquals(events.get(4).content, null);
assertEquals(events.get(5).type, "CLOSE");
assertEquals(events.get(5).content, null);
events = GripControl.decodeWebSocketEvents("OPEN\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "OPEN");
assertEquals(events.get(0).content, null);
events = GripControl.decodeWebSocketEvents("TEXT 5\r\nHello\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "TEXT");
assertEquals(events.get(0).content, "Hello");
}
@Test
public void testDecodeWebSocketEventsUnicode() {
List<WebSocketEvent> events = GripControl.decodeWebSocketEvents("TEXT 69\r\n��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "TEXT");
assertEquals(events.get(0).content, "��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל");
events = GripControl.decodeWebSocketEvents("TEXT fe\r\n�� Grinning Face.\n�� Grinning Face with Big Eyes.\n�� Grinning Face with Smiling Eyes.\n�� Beaming Face with Smiling Eyes.\n�� Grinning Squinting Face.\n�� Grinning Face with Sweat.\n�� Rolling on the Floor Laughing.\n�� Face with Tears of Joy.\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "TEXT");
assertEquals(events.get(0).content, "�� Grinning Face.\n�� Grinning Face with Big Eyes.\n�� Grinning Face with Smiling Eyes.\n�� Beaming Face with Smiling Eyes.\n�� Grinning Squinting Face.\n�� Grinning Face with Sweat.\n�� Rolling on the Floor Laughing.\n�� Face with Tears of Joy.");
events = GripControl.decodeWebSocketEvents("TEXT 69\r\n��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל\r\nTEXT 69\r\n��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל\r\nTEXT fe\r\n�� Grinning Face.\n�� Grinning Face with Big Eyes.\n�� Grinning Face with Smiling Eyes.\n�� Beaming Face with Smiling Eyes.\n�� Grinning Squinting Face.\n�� Grinning Face with Sweat.\n�� Rolling on the Floor Laughing.\n�� Face with Tears of Joy.\r\nTEXT 69\r\n��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל\r\nTEXT 69\r\n��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל\r\n");
assertEquals(events.size(), 5);
assertEquals(events.get(0).type, "TEXT");
assertEquals(events.get(0).content, "��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל");
assertEquals(events.get(1).type, "TEXT");
assertEquals(events.get(1).content, "��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל");
assertEquals(events.get(2).type, "TEXT");
assertEquals(events.get(2).content, "�� Grinning Face.\n�� Grinning Face with Big Eyes.\n�� Grinning Face with Smiling Eyes.\n�� Beaming Face with Smiling Eyes.\n�� Grinning Squinting Face.\n�� Grinning Face with Sweat.\n�� Rolling on the Floor Laughing.\n�� Face with Tears of Joy.");
assertEquals(events.get(3).type, "TEXT");
assertEquals(events.get(3).content, "��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל");
assertEquals(events.get(4).type, "TEXT");
assertEquals(events.get(4).content, "��Smiling Face with Heart-Shaped Eyes☼Sun✂︎Scissors��Heart⛺️sunset����דגל ישראל");
}
@Test(expected=IllegalArgumentException.class)
public void testDecodeWebSocketEventsException1() throws IllegalArgumentException {
GripControl.decodeWebSocketEvents("TEXT 5");
}
@Test(expected=IllegalArgumentException.class)
public void testDecodeWebSocketEventsException2() throws IllegalArgumentException {
GripControl.decodeWebSocketEvents("OPEN\r\nTEXT");
}
}
|
src/test/java/org/fanout/gripcontrol/GripControlTest.java
|
package org.fanout.gripcontrol;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.*;
import static org.junit.Assert.*;
public class GripControlTest {
@Test
public void testCreateHold() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHold("mode", channels, null, 0);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHold("mode", channels, null, 0);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHold("mode", channels, response, 0);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
hold = GripControl.createHold("mode", channels, response, 5);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"mode\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}],\"timeout\":5}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateHoldResponse() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHoldResponse(channels);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHoldResponse(channels);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHoldResponse(channels, response);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
hold = GripControl.createHoldResponse(channels, response, 5);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"response\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}],\"timeout\":5}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateHoldStream() throws UnsupportedEncodingException {
JsonParser parser = new JsonParser();
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String hold = GripControl.createHoldStream(channels);
JsonElement jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"}]}}");
JsonElement jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
channels.add(new Channel("chan2", "prev-id"));
hold = GripControl.createHoldStream(channels);
jsonElement1 = parser.parse("{\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
Response response = new Response("body");
hold = GripControl.createHoldStream(channels, response);
jsonElement1 = parser.parse("{\"response\":{\"body\":\"body\"},\"hold\":{\"mode\":\"stream\",\"channels\":[{\"name\":\"chan1\"},{\"name\":\"chan2\",\"prev-id\":\"prev-id\"}]}}");
jsonElement2 = parser.parse(hold);
assertEquals(jsonElement1, jsonElement2);
}
@Test
public void testCreateGripChannelHeader() {
List<Channel> channels = new ArrayList<Channel>();
channels.add(new Channel("chan1"));
String header = GripControl.createGripChannelHeader(channels);
assertEquals(header, "chan1");
channels.add(new Channel("chan2", "prev-id"));
header = GripControl.createGripChannelHeader(channels);
assertEquals(header, "chan1, chan2; prev-id=prev-id");
}
@Test
public void testWebSocketControlMessage() {
String message = GripControl.webSocketControlMessage("type", null);
assertEquals(message, "{\"type\":\"type\"}");
Map<String, Object> args = new HashMap<String, Object>();
args.put("arg1", "value1");
args.put("arg2", "value2");
message = GripControl.webSocketControlMessage("type", args);
assertEquals(message, "{\"arg2\":\"value2\",\"arg1\":\"value1\",\"type\":\"type\"}");
}
@Test
public void testParseGripUri() throws UnsupportedEncodingException, MalformedURLException {
String url = "http://test.com/path";
Map<String, Object> parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com/path");
url = "http://test.com/path?arg1=val1";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com/path?arg1=val1");
url = "http://test.com:8900/path?arg1=val1&arg2=val2";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
url = "http://test.com:8900/path?arg1=val1&arg2=val2&iss=claim";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
url = "http://test.com:8900/path?arg1=val1&arg2=val2&iss=claim&key=keyval";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "http://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
assertEquals(parsedUri.get("key"), "keyval");
url = "https://test.com:8900/path?arg1=val1&arg2=val2&iss=claim&key=base64:aGVsbG8=";
parsedUri = GripControl.parseGripUri(url);
assertEquals(parsedUri.get("control_uri"), "https://test.com:8900/path?arg1=val1&arg2=val2");
assertEquals(parsedUri.get("control_iss"), "claim");
assertEquals(parsedUri.get("key"), "hello");
}
@Test
public void testValidateSig() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwidGVzdGlzcy" +
"JdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoyNTUxMDQ2Mjg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJq" +
"cm9ja2V0QGV4YW1wbGUuY29tIn0.Wmm-ulXbOun3egbdqmxjCqegyYu8Tr5MAaguie4rmTE";
String key = "a2V5";
assertTrue(GripControl.validateSig(token, key));
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwidGVzdGlzcy" +
"JdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoyNTUxMDQ2Mjg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLCJzdWIiOiJq" +
"cm9ja2V0QGV4YW1wbGUuY29tIn0.Wmm-ulXbOun3egbdqmxjCqegyYu8Tr5MAaguie4rmTE";
key = "d3JvbmdrZXk=";
assertFalse(GripControl.validateSig(token, key));
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOlsiT25saW5lIEpXVCBCdWlsZGVyIiwi" +
"dGVzdGlzcyJdLCJpYXQiOjk3MzI5NTg4NSwiZXhwIjoxMDA0NzQ1NDg1LCJhdWQiOiJ3d3cuZXhhbXBsZS5jb20iLC" +
"JzdWIiOiJqcm9ja2V0QGV4YW1wbGUuY29tIn0.W8e4mxvbMKuotkINOyZX5jDO7KFD-jpgPHbWNGV5CHQ";
key = "a2V5";
assertFalse(GripControl.validateSig(token, key));
}
@Test
public void testEncodeWebSocketEvents() {
List<WebSocketEvent> events = new ArrayList<WebSocketEvent>();
events.add(new WebSocketEvent("TEXT", "Hello"));
events.add(new WebSocketEvent("TEXT", ""));
events.add(new WebSocketEvent("TEXT"));
assertEquals(GripControl.encodeWebSocketEvents(events), "TEXT 5\r\nHello\r\nTEXT 0\r\n\r\nTEXT\r\n");
events = new ArrayList<WebSocketEvent>();
events.add(new WebSocketEvent("OPEN"));
assertEquals(GripControl.encodeWebSocketEvents(events), "OPEN\r\n");
}
@Test
public void testDecodeWebSocketEvents() throws IllegalArgumentException {
List<WebSocketEvent> events = GripControl.decodeWebSocketEvents("OPEN\r\nTEXT 5\r\nHello" +
"\r\nTEXT 0\r\n\r\nCLOSE\r\nTEXT\r\nCLOSE\r\n");
assertEquals(events.size(), 6);
assertEquals(events.get(0).type, "OPEN");
assertEquals(events.get(0).content, null);
assertEquals(events.get(1).type, "TEXT");
assertEquals(events.get(1).content, "Hello");
assertEquals(events.get(2).type, "TEXT");
assertEquals(events.get(2).content, "");
assertEquals(events.get(3).type, "CLOSE");
assertEquals(events.get(3).content, null);
assertEquals(events.get(4).type, "TEXT");
assertEquals(events.get(4).content, null);
assertEquals(events.get(5).type, "CLOSE");
assertEquals(events.get(5).content, null);
events = GripControl.decodeWebSocketEvents("OPEN\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "OPEN");
assertEquals(events.get(0).content, null);
events = GripControl.decodeWebSocketEvents("TEXT 5\r\nHello\r\n");
assertEquals(events.size(), 1);
assertEquals(events.get(0).type, "TEXT");
assertEquals(events.get(0).content, "Hello");
}
@Test(expected=IllegalArgumentException.class)
public void testDecodeWebSocketEventsException1() throws IllegalArgumentException {
GripControl.decodeWebSocketEvents("TEXT 5");
}
@Test(expected=IllegalArgumentException.class)
public void testDecodeWebSocketEventsException2() throws IllegalArgumentException {
GripControl.decodeWebSocketEvents("OPEN\r\nTEXT");
}
}
|
Add unicode test (failing)
|
src/test/java/org/fanout/gripcontrol/GripControlTest.java
|
Add unicode test (failing)
|
|
Java
|
mit
|
afe80cc18d5657f7ffabb000b012111266e092e9
| 0
|
teropa/globetrotter
|
package teropa.globetrotter.client.wms;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import teropa.globetrotter.client.Grid;
import teropa.globetrotter.client.ImagePool;
import teropa.globetrotter.client.common.Bounds;
import teropa.globetrotter.client.common.Calc;
import teropa.globetrotter.client.common.Point;
import teropa.globetrotter.client.common.Size;
import teropa.globetrotter.client.event.MapViewChangedEvent;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
public class TiledWMS extends WMSBase {
private final AbsolutePanel container = new AbsolutePanel();
private final HashMap<Grid.Tile,Image> imageTiles = new HashMap<Grid.Tile, Image>();
private int buffer = 2;
private double ignoreEventsBuffer = buffer / 4.0;
private Point lastDrawnAtPoint = null;
public TiledWMS(String name, String url) {
super(name, url);
}
protected void onVisibilityChanged() {
if (visible && initialized && context.isDrawn()) {
addNewTiles();
}
}
@Override
public void onMapViewChanged(MapViewChangedEvent evt) {
if (evt.effectiveExtentChanged) {
repositionTiles();
}
if (evt.zoomed) {
removeTiles(true);
lastDrawnAtPoint = null;
}
if ((evt.zoomed || evt.panned) && visible) {
if (shouldDraw()) {
addNewTiles();
}
}
if (evt.panEnded) {
removeTiles(false);
}
}
private boolean shouldDraw() {
Point newCenter = context.getViewCenterPoint();
if (lastDrawnAtPoint == null || distanceExceedsBuffer(newCenter, lastDrawnAtPoint)) {
lastDrawnAtPoint = newCenter;
return true;
}
return false;
}
private boolean distanceExceedsBuffer(Point lhs, Point rhs) {
int xDist = Math.abs(lhs.getX() - rhs.getX());
if (xDist > ignoreEventsBuffer * context.getTileSize().getWidth()) return true;
int yDist = Math.abs(lhs.getY() - rhs.getY());
if (yDist > ignoreEventsBuffer * context.getTileSize().getHeight()) return true;
return false;
}
private void removeTiles(boolean removeAll) {
if (imageTiles.isEmpty()) return;
Bounds bufferedExtent = widenToBuffer(context.getVisibleExtent());
java.util.Iterator<Map.Entry<Grid.Tile, Image>> it = imageTiles.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Grid.Tile, Image> entry = it.next();
if (removeAll || !Calc.intersect(bufferedExtent, entry.getKey().getExtent())) {
container.remove(entry.getValue());
ImagePool.release(entry.getValue());
it.remove();
}
}
}
private void addNewTiles() {
Grid grid = context.getGrid();
Bounds extent = widenToBuffer(context.getVisibleExtent());
List<Grid.Tile> tiles = grid.getTiles(extent);
int length = tiles.size();
for (int i=0 ; i<length ; i++) {
Grid.Tile eachTile = tiles.get(i);
if (!imageTiles.containsKey(eachTile)) {
Image image = ImagePool.get();
image.setUrl(constructUrl(eachTile.getExtent(), eachTile.getSize()));
imageTiles.put(eachTile, image);
container.add(image);
Point topLeft = eachTile.getTopLeft();
fastSetElementPosition(image.getElement(), topLeft.getX(), topLeft.getY());
}
}
}
private Bounds widenToBuffer(Bounds extent) {
if (buffer > 0) {
Size viewportSize = context.getViewportSize();
Size widenedSize = new Size(viewportSize.getWidth() + 2 * buffer * context.getTileSize().getWidth(), viewportSize.getHeight() + 2 * buffer * context.getTileSize().getHeight());
Bounds widenedExtent = Calc.getExtent(context.getCenter(), context.getResolution(), widenedSize);
return Calc.narrow(widenedExtent, context.getEffectiveExtent());
} else {
return extent;
}
}
private void repositionTiles() {
for (Map.Entry<Grid.Tile, Image> each : imageTiles.entrySet()) {
Point topLeft = each.getKey().getTopLeft();
fastSetElementPosition(each.getValue().getElement(), topLeft.getX(), topLeft.getY());
}
}
private void fastSetElementPosition(Element elem, int left, int top) {
Style style = elem.getStyle();
style.setProperty("position", "absolute");
style.setPropertyPx("left", left);
style.setPropertyPx("top", top);
}
@Override
public Widget asWidget() {
return container;
}
}
|
src/main/java/teropa/globetrotter/client/wms/TiledWMS.java
|
package teropa.globetrotter.client.wms;
import java.util.List;
import teropa.globetrotter.client.Grid;
import teropa.globetrotter.client.ImagePool;
import teropa.globetrotter.client.common.Bounds;
import teropa.globetrotter.client.common.Calc;
import teropa.globetrotter.client.common.Point;
import teropa.globetrotter.client.common.Size;
import teropa.globetrotter.client.event.MapViewChangedEvent;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
public class TiledWMS extends WMSBase {
private static class TileAndImage {
public TileAndImage(Grid.Tile tile, Image image) {
this.tile = tile;
this.image = image;
}
public final Grid.Tile tile;
public final Image image;
}
private final AbsolutePanel container = new AbsolutePanel();
private TileAndImage[][] imageGrid;
private int buffer = 2;
private double ignoreEventsBuffer = buffer / 4.0;
private Point lastDrawnAtPoint = null;
public TiledWMS(String name, String url) {
super(name, url);
}
protected void onVisibilityChanged() {
if (visible && initialized && context.isDrawn()) {
maybeInitGrid();
addNewTiles();
}
}
@Override
public void onMapViewChanged(MapViewChangedEvent evt) {
if (evt.effectiveExtentChanged) {
repositionTiles();
}
if (evt.zoomed) {
removeTiles(true);
imageGrid = null;
lastDrawnAtPoint = null;
}
if ((evt.zoomed || evt.panned) && visible) {
maybeInitGrid();
if (shouldDraw()) {
addNewTiles();
}
}
if (evt.panEnded) {
removeTiles(false);
}
}
private void maybeInitGrid() {
if (imageGrid == null) {
imageGrid = new TileAndImage[context.getGrid().getNumCols()][context.getGrid().getNumRows()];
}
}
private boolean shouldDraw() {
Point newCenter = context.getViewCenterPoint();
if (lastDrawnAtPoint == null || distanceExceedsBuffer(newCenter, lastDrawnAtPoint)) {
lastDrawnAtPoint = newCenter;
return true;
}
return false;
}
private boolean distanceExceedsBuffer(Point lhs, Point rhs) {
int xDist = Math.abs(lhs.getX() - rhs.getX());
if (xDist > ignoreEventsBuffer * context.getTileSize().getWidth()) return true;
int yDist = Math.abs(lhs.getY() - rhs.getY());
if (yDist > ignoreEventsBuffer * context.getTileSize().getHeight()) return true;
return false;
}
private void removeTiles(boolean removeAll) {
if (imageGrid == null) return;
Bounds bufferedExtent = widenToBuffer(context.getVisibleExtent());
for (int i=0 ; i<imageGrid.length ; i++) {
for (int j=0 ; j<imageGrid[i].length ; j++) {
TileAndImage entry = imageGrid[i][j];
if (entry == null) continue;
if (removeAll || !Calc.intersect(bufferedExtent, entry.tile.getExtent())) {
container.remove(entry.image);
ImagePool.release(entry.image);
imageGrid[i][j] = null;
}
}
}
}
private void addNewTiles() {
Grid grid = context.getGrid();
Bounds extent = widenToBuffer(context.getVisibleExtent());
List<Grid.Tile> tiles = grid.getTiles(extent);
int length = tiles.size();
for (int i=0 ; i<length ; i++) {
Grid.Tile eachTile = tiles.get(i);
TileAndImage[] col = imageGrid[eachTile.getCol()];
if (col[eachTile.getRow()] == null) {
Image image = ImagePool.get();
image.setUrl(constructUrl(eachTile.getExtent(), eachTile.getSize()));
col[eachTile.getRow()] = new TileAndImage(eachTile, image);
container.add(image);
Point topLeft = eachTile.getTopLeft();
fastSetElementPosition(image.getElement(), topLeft.getX(), topLeft.getY());
}
}
}
private Bounds widenToBuffer(Bounds extent) {
if (buffer > 0) {
Size viewportSize = context.getViewportSize();
Size widenedSize = new Size(viewportSize.getWidth() + 2 * buffer * context.getTileSize().getWidth(), viewportSize.getHeight() + 2 * buffer * context.getTileSize().getHeight());
Bounds widenedExtent = Calc.getExtent(context.getCenter(), context.getResolution(), widenedSize);
return Calc.narrow(widenedExtent, context.getEffectiveExtent());
} else {
return extent;
}
}
private void repositionTiles() {
if (imageGrid == null) return;
for (int i=0 ; i<imageGrid.length ; i++) {
for (int j=0 ; j<imageGrid[i].length ; j++) {
TileAndImage entry = imageGrid[i][j];
if (entry != null) {
Point topLeft = entry.tile.getTopLeft();
fastSetElementPosition(entry.image.getElement(), topLeft.getX(), topLeft.getY());
}
}
}
}
private void fastSetElementPosition(Element elem, int left, int top) {
Style style = elem.getStyle();
style.setProperty("position", "absolute");
style.setPropertyPx("left", left);
style.setPropertyPx("top", top);
}
@Override
public Widget asWidget() {
return container;
}
}
|
improved tiled WMS processing performance on large grids
|
src/main/java/teropa/globetrotter/client/wms/TiledWMS.java
|
improved tiled WMS processing performance on large grids
|
|
Java
|
mit
|
ff6da041f7c63119fb56610c691ae94263c7a946
| 0
|
ihongs/HongsCORE,ihongs/HongsCORE,ihongs/HongsCORE
|
package app.hongs.util.verify;
import app.hongs.Core;
import app.hongs.action.UploadHelper;
import app.hongs.util.Synt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Part;
/**
* 文件校验
* <pre>
* 规则参数:
* pass-source yes|no 是否跳过资源链接(存在有"/"的字符)
* pass-remote yes|no 是否跳过远程链接("http://"等开头)
* down-remote yes|no 是否下载远程文件
* drop-origin yes|no 抛弃原始文件, 仅使用 checks 中新创建的
* keep-origin yes|no 返回原始路径, 不理会 checks 中新创建的
* temp 上传临时目录, 可用变量 $DATA_PATH, $BASE_PATH 等
* path 上传目标目录, 可用变量 $BASE_PATH, $DATA_PATH 等
* href 上传文件链接, 可用变量 $BASE_HREF, $BASE_LINK 等, 后者带域名前缀
* type 文件类型限制(Mime-Type), 逗号分隔
* extn 扩展名称限制, 逗号分隔
* </pre>
* @author Hongs
*/
public class IsFile extends Rule {
@Override
public Object verify(Object value) throws Wrong {
if (value == null || "".equals(value)) {
return null; // 允许为空
}
if (value instanceof String) {
// 跳过资源路径
if (Synt.declare(params.get("pass-source"), false)) {
String u = value.toString( );
if (u.indexOf( '/' ) != -1 ) {
return value;
}
}
// 跳过远程地址
if (Synt.declare(params.get("pass-remote"), false)) {
String u = value.toString( );
if (u.matches("^\\w+://.*")) {
return value;
}
}
// 下载远程文件
if (Synt.declare(params.get("down-remote"), false)) {
String u = value.toString( );
if (u.matches("^\\w+://.*")) {
do {
String x;
// 如果是本地路径则不再下载
x = (String) params.get("href");
if (x != null && !"".equals(x)) {
if (u.startsWith(x)) {
value = u;
break ;
}
}
// 如果有临时目录则下载到这
x = (String) params.get("temp");
if (x == null || "".equals(x)) {
x = Core.DATA_PATH + File.separator + "tmp";
}
value = stores(value.toString(), x);
} while(false);
}
}
} // End If
UploadHelper hlpr = new UploadHelper();
String href, path;
String x;
String[] y;
x = (String) params.get("temp");
if (x != null) hlpr.setUploadTemp(x);
x = (String) params.get("path");
if (x != null) hlpr.setUploadPath(x);
x = (String) params.get("href");
if (x != null) hlpr.setUploadHref(x);
y = (String[]) Synt.toArray(params.get("type"));
if (y != null) hlpr.setAllowTypes(y);
y = (String[]) Synt.toArray(params.get("extn"));
if (y != null) hlpr.setAllowExtns(y);
if (value instanceof Part) {
hlpr.upload((Part) value);
} else
if (value instanceof File) {
hlpr.upload((File) value);
} else {
hlpr.upload(value.toString());
}
href = hlpr.getResultHref();
path = hlpr.getResultPath();
/**
* 检查新上传的文件
* 可以返回原始路径
* 或者抛弃原始文件
*/
if ( ! href.equals(value) ) {
x = checks(href , path);
if ( ! href.equals(x) ) {
if (Synt.declare(params.get("keep-origin"), false)) {
// Keep to return origin href
} else
if (Synt.declare(params.get("drop-origin"), false)) {
new File(path).delete();
href = x;
} else {
href = x;
}
}
}
return href;
}
/**
* 远程文件预先下载到本地
* 返回临时名称
* @param href 文件链接
* @param temp 临时目录
* @return
* @throws Wrong
*/
protected String stores(String href, String temp) throws Wrong {
URL url = null;
try {
url = new URL(href);
} catch (MalformedURLException ex) {
throw new Wrong(ex, "file.url.has.error", href);
}
URLConnection cnn ;
InputStream ins = null;
FileOutputStream out = null;
try {
cnn = url.openConnection( );
ins = cnn.getInputStream( );
// 从响应头中获取到名称
String name = cnn.getHeaderField("Content-Disposition");
Pattern pat = Pattern.compile("filename=\"(.*?)\"");
Matcher mat = pat.matcher( name );
if (mat.find()) {
name = mat.group(1);
} else {
name = cnn.getURL().getPath();
}
// 重组名称避免无法存储
int i = name.lastIndexOf( '/' );
if (i != -1) {
name = name.substring(i + 1);
}
int j = name.lastIndexOf( '.' );
if (j != -1) {
name = URLEncoder.encode(name.substring(i , j), "UTF-8")
+ "."
+ URLEncoder.encode(name.substring(j + 1), "UTF-8");
} else {
name = URLEncoder.encode(name, "UTF-8");
}
name = Core.newIdentity () + "!" + name; // 加上编号避免重名
// 检查目录避免写入失败
File file = new File(temp + File.separator + name);
File fdir = file.getParentFile();
if (!fdir.exists()) {
fdir.mkdirs();
}
// 将上传的存入临时文件
out = new FileOutputStream( file );
byte[] buf = new byte[1204];
int ovr ;
while((ovr = ins.read(buf )) != -1) {
out.write(buf, 0, ovr );
}
return name;
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.fetch", href, temp);
} finally {
if (out != null) {
try {
out.close( );
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.close", temp);
}
}
if (ins != null) {
try {
ins.close( );
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.close", href);
}
}
}
}
/**
* 上传成功后的进一步检查
* 用于后续处理, 如生成缩略图, 或视频截图等
* @param href 文件链接
* @param path 文件路径
* @return
* @throws Wrong
*/
protected String checks(String href, String path) throws Wrong {
return href;
}
}
|
hongs-core/src/main/java/app/hongs/util/verify/IsFile.java
|
package app.hongs.util.verify;
import app.hongs.Core;
import app.hongs.action.UploadHelper;
import app.hongs.util.Synt;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Part;
/**
* 文件校验
* <pre>
* 规则参数:
* pass-source yes|no 是否跳过资源链接(存在有"/"的字符)
* pass-remote yes|no 是否跳过远程链接("http://"等开头)
* down-remote yes|no 是否下载远程文件
* drop-origin yes|no 抛弃原始文件, 仅使用 checks 中新创建的
* keep-origin yes|no 返回原始路径, 不理会 checks 中新创建的
* temp 上传临时目录, 可用变量 $DATA_PATH, $BASE_PATH 等
* path 上传目标目录, 可用变量 $BASE_PATH, $DATA_PATH 等
* href 上传文件链接, 可用变量 $BASE_HREF, $BASE_LINK 等, 后者带域名前缀
* type 文件类型限制(Mime-Type), 逗号分隔
* extn 扩展名称限制, 逗号分隔
* </pre>
* @author Hongs
*/
public class IsFile extends Rule {
@Override
public Object verify(Object value) throws Wrong {
if (value == null || "".equals(value)) {
return null; // 允许为空
}
if (value instanceof String) {
// 跳过资源路径
if (Synt.declare(params.get("pass-source"), false)) {
String u = value.toString( );
if (u.indexOf( '/' ) != -1 ) {
return value;
}
}
// 跳过远程地址
if (Synt.declare(params.get("pass-remote"), false)) {
String u = value.toString( );
if (u.matches("^\\w+://.*")) {
return value;
}
}
// 下载远程文件
if (Synt.declare(params.get("down-remote"), false)) {
String u = value.toString( );
if (u.matches("^\\w+://.*")) {
do {
String x;
// 如果是本地路径则不再下载
x = (String) params.get("href");
if (x != null && !"".equals(x)) {
if (u.startsWith(x)) {
value = u;
break ;
}
}
// 如果有临时目录则下载到这
x = (String) params.get("temp");
if (x == null || "".equals(x)) {
x = Core.DATA_PATH + File.separator + "tmp";
}
value = stores(value.toString(), x);
} while(false);
}
}
} // End If
UploadHelper hlpr = new UploadHelper();
String href, path;
String x;
String[] y;
x = (String) params.get("temp");
if (x != null) hlpr.setUploadTemp(x);
x = (String) params.get("path");
if (x != null) hlpr.setUploadPath(x);
x = (String) params.get("href");
if (x != null) hlpr.setUploadHref(x);
y = (String[]) Synt.toArray(params.get("type"));
if (x != null) hlpr.setAllowTypes(y);
y = (String[]) Synt.toArray(params.get("extn"));
if (x != null) hlpr.setAllowExtns(y);
if (value instanceof Part) {
hlpr.upload((Part) value);
} else
if (value instanceof File) {
hlpr.upload((File) value);
} else {
hlpr.upload(value.toString());
}
href = hlpr.getResultHref();
path = hlpr.getResultPath();
/**
* 检查新上传的文件
* 可以返回原始路径
* 或者抛弃原始文件
*/
if ( ! href.equals(value) ) {
x = checks(href , path);
if ( ! href.equals(x) ) {
if (Synt.declare(params.get("keep-origin"), false)) {
// Keep to return origin href
} else
if (Synt.declare(params.get("drop-origin"), false)) {
new File(path).delete();
href = x;
} else {
href = x;
}
}
}
return href;
}
/**
* 远程文件预先下载到本地
* 返回临时名称
* @param href 文件链接
* @param temp 临时目录
* @return
* @throws Wrong
*/
protected String stores(String href, String temp) throws Wrong {
URL url = null;
try {
url = new URL(href);
} catch (MalformedURLException ex) {
throw new Wrong(ex, "file.url.has.error", href);
}
URLConnection cnn ;
InputStream ins = null;
FileOutputStream out = null;
try {
cnn = url.openConnection( );
ins = cnn.getInputStream( );
// 从响应头中获取到名称
String name = cnn.getHeaderField("Content-Disposition");
Pattern pat = Pattern.compile("filename=\"(.*?)\"");
Matcher mat = pat.matcher( name );
if (mat.find()) {
name = mat.group(1);
} else {
name = cnn.getURL().getPath();
}
// 重组名称避免无法存储
int i = name.lastIndexOf( '/' );
if (i != -1) {
name = name.substring(i + 1);
}
int j = name.lastIndexOf( '.' );
if (j != -1) {
name = URLEncoder.encode(name.substring(i , j), "UTF-8")
+ "."
+ URLEncoder.encode(name.substring(j + 1), "UTF-8");
} else {
name = URLEncoder.encode(name, "UTF-8");
}
name = Core.newIdentity () + "!" + name; // 加上编号避免重名
// 检查目录避免写入失败
File file = new File(temp + File.separator + name);
File fdir = file.getParentFile();
if (!fdir.exists()) {
fdir.mkdirs();
}
// 将上传的存入临时文件
out = new FileOutputStream( file );
byte[] buf = new byte[1204];
int ovr ;
while((ovr = ins.read(buf )) != -1) {
out.write(buf, 0, ovr );
}
return name;
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.fetch", href, temp);
} finally {
if (out != null) {
try {
out.close( );
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.close", temp);
}
}
if (ins != null) {
try {
ins.close( );
} catch (IOException ex) {
throw new Wrong( ex, "core.file.can.not.close", href);
}
}
}
}
/**
* 上传成功后的进一步检查
* 用于后续处理, 如生成缩略图, 或视频截图等
* @param href 文件链接
* @param path 文件路径
* @return
* @throws Wrong
*/
protected String checks(String href, String path) throws Wrong {
return href;
}
}
|
修复 type,extn 参数取错的问题
|
hongs-core/src/main/java/app/hongs/util/verify/IsFile.java
|
修复 type,extn 参数取错的问题
|
|
Java
|
mit
|
3759c6aca8dfa81ff842d4072ec87d4319fcb0bf
| 0
|
ChromoZoneX/turbo-tribble
|
package com.turbo.whack;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class GamePlay extends Activity {
private static final int WH_BUTTON_MAP = 74;
private Timer check_timer = new Timer();
private Timer button_show_timer;
private boolean button_pressed = false;
private boolean exit = false;
private long level = 100;
private int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
ActivityHelper.activity_init(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
Button button[] = get_button_handles();
// disable and hide all buttons
for(int i = 10; i < 74; i+=10) {
hide_button(button[i+1]);
hide_button(button[i+2]);
hide_button(button[i+3]);
}
TimerTask task = new TimerTask() {
@Override
public void run() {
if(button_pressed) {
button_pressed = false;
exit = true;
score++;
// Cancel the timeout timer
if(score % 3 == 0 && score > 0) {
level /= ActivityHelper.WH_HARDNESS_FACTOR;
}
return;
}
}
};
check_timer.scheduleAtFixedRate(task, 0, ActivityHelper.WH_TIMER_CHECK_RATE);
start_game(button);
}
private void start_game(Button[] b) {
final Button[] button = b;
button_show_timer = new Timer();
if(level * ActivityHelper.WH_TIMER_MULTIPLIER < ActivityHelper.WH_TIMER_CHECK_RATE) {
// The player managed to beat the game.
}
TimerTask button_show_task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
show_random_button(button);
}
});
}
};
button_show_timer.schedule(button_show_task, level * ActivityHelper.WH_TIMER_MULTIPLIER);
}
/**
* This method will display any random button
* @param button
* @return
*/
private int show_random_button(Button[] button) {
int rand = ActivityHelper.get_random_number();
show_button(button[rand]);
return 0;
}
/**
* Callback for button click when you whack the mole.
* @param v View name
*/
public void game_button_clicked(View v) {
button_pressed = true;
Button b = (Button) findViewById(v.getId());
hide_button(b);
}
/**
* Make the button pressable and visible.
* @param button The button in question
* @return An integer showing success
*/
private int show_button(Button button) {
button.setEnabled(true);
button.setVisibility(View.VISIBLE);
return 0;
}
/**
* Hide the button completely.
* @param button
* @return An integer showing success
*/
private int hide_button(Button button) {
button.setEnabled(false);
button.setVisibility(View.INVISIBLE);
return 0;
}
/**
* Clean up before exiting
*/
@Override
public void onBackPressed() {
exit = true;
check_timer.cancel();
this.finish();
}
/**
* Set all button ids so that it is easy to reference by index.
* @return An array of type Button with all the ids referenced
*/
private Button[] get_button_handles() {
Button button_array[] = new Button[WH_BUTTON_MAP];
for(int i = 0; i < 74; i++) {
button_array[i] = null;
}
button_array[11] = (Button) findViewById(R.id.Button11);
button_array[12] = (Button) findViewById(R.id.Button12);
button_array[13] = (Button) findViewById(R.id.Button13);
button_array[21] = (Button) findViewById(R.id.Button21);
button_array[22] = (Button) findViewById(R.id.Button22);
button_array[23] = (Button) findViewById(R.id.Button23);
button_array[31] = (Button) findViewById(R.id.Button31);
button_array[32] = (Button) findViewById(R.id.Button32);
button_array[33] = (Button) findViewById(R.id.Button33);
button_array[41] = (Button) findViewById(R.id.Button41);
button_array[42] = (Button) findViewById(R.id.Button42);
button_array[43] = (Button) findViewById(R.id.Button43);
button_array[51] = (Button) findViewById(R.id.Button51);
button_array[52] = (Button) findViewById(R.id.Button52);
button_array[53] = (Button) findViewById(R.id.Button53);
button_array[61] = (Button) findViewById(R.id.Button61);
button_array[62] = (Button) findViewById(R.id.Button62);
button_array[63] = (Button) findViewById(R.id.Button63);
button_array[71] = (Button) findViewById(R.id.Button71);
button_array[72] = (Button) findViewById(R.id.Button72);
button_array[73] = (Button) findViewById(R.id.Button73);
return button_array;
}
}
|
whack/src/com/turbo/whack/GamePlay.java
|
package com.turbo.whack;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class GamePlay extends Activity {
private static final int WH_BUTTON_MAP = 74;
private Timer check_timer = new Timer();
private Timer button_timer;
private boolean button_pressed = false;
private boolean exit = false;
private long level = 100;
private int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
ActivityHelper.activity_init(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
Button button[] = get_button_handles();
// disable and hide all buttons
for(int i = 10; i < 74; i+=10) {
hide_button(button[i+1]);
hide_button(button[i+2]);
hide_button(button[i+3]);
}
TimerTask task = new TimerTask() {
@Override
public void run() {
if(button_pressed) {
button_pressed = false;
score++;
if(score % 3 == 0 && score > 0) {
level /= ActivityHelper.WH_HARDNESS_FACTOR;
}
return;
}
}
};
check_timer.scheduleAtFixedRate(task, 0, ActivityHelper.WH_TIMER_CHECK_RATE);
start_game();
}
private void start_game() {
// button_timer = new Timer();
// TimerTask task = new TimerTask() {
// @Override
// public void run() {
//
// }
// };
}
/**
* This method will display any random button
* @param button
* @return
*/
private int show_random_button(Button[] button) {
int rand = ActivityHelper.get_random_number();
show_button(button[rand]);
return 0;
}
/**
* Callback for button click when you whack the mole.
* @param v View name
*/
public void game_button_clicked(View v) {
button_pressed = true;
Button b = (Button) findViewById(v.getId());
hide_button(b);
}
/**
* Make the button pressable and visible.
* @param button The button in question
* @return An integer showing success
*/
private int show_button(Button button) {
button.setEnabled(true);
button.setVisibility(View.VISIBLE);
return 0;
}
/**
* Hide the button completely.
* @param button
* @return An integer showing success
*/
private int hide_button(Button button) {
button.setEnabled(false);
button.setVisibility(View.INVISIBLE);
return 0;
}
/**
* Clean up before exiting
*/
@Override
public void onBackPressed() {
exit = true;
check_timer.cancel();
this.finish();
}
/**
* Set all button ids so that it is easy to reference by index.
* @return An array of type Button with all the ids referenced
*/
private Button[] get_button_handles() {
Button button_array[] = new Button[WH_BUTTON_MAP];
for(int i = 0; i < 74; i++) {
button_array[i] = null;
}
button_array[11] = (Button) findViewById(R.id.Button11);
button_array[12] = (Button) findViewById(R.id.Button12);
button_array[13] = (Button) findViewById(R.id.Button13);
button_array[21] = (Button) findViewById(R.id.Button21);
button_array[22] = (Button) findViewById(R.id.Button22);
button_array[23] = (Button) findViewById(R.id.Button23);
button_array[31] = (Button) findViewById(R.id.Button31);
button_array[32] = (Button) findViewById(R.id.Button32);
button_array[33] = (Button) findViewById(R.id.Button33);
button_array[41] = (Button) findViewById(R.id.Button41);
button_array[42] = (Button) findViewById(R.id.Button42);
button_array[43] = (Button) findViewById(R.id.Button43);
button_array[51] = (Button) findViewById(R.id.Button51);
button_array[52] = (Button) findViewById(R.id.Button52);
button_array[53] = (Button) findViewById(R.id.Button53);
button_array[61] = (Button) findViewById(R.id.Button61);
button_array[62] = (Button) findViewById(R.id.Button62);
button_array[63] = (Button) findViewById(R.id.Button63);
button_array[71] = (Button) findViewById(R.id.Button71);
button_array[72] = (Button) findViewById(R.id.Button72);
button_array[73] = (Button) findViewById(R.id.Button73);
return button_array;
}
}
|
PR #5: Button randomly shows again.
|
whack/src/com/turbo/whack/GamePlay.java
|
PR #5: Button randomly shows again.
|
|
Java
|
mit
|
b925b38730d1036577e6639529e6fb0596abea9c
| 0
|
wojtekPi/TDD-training3
|
package bank;
/**
* Tdd training on 15.10.17.
*/
public class PaymentService {
private final ExchangeService exchangeService;
public PaymentService(ExchangeService exchangeService) {
this.exchangeService = exchangeService;
}
public void transferMoney(Account accountFrom, Account accountTo, Instrument amountToTransfer) {
checkIfCurrencyIsValid(accountFrom, accountTo, amountToTransfer);
checkIfAccountBalanceIsValid(accountFrom, amountToTransfer.getAmount());
Instrument exchangedAmountToTransfer = amountToTransfer;
if (isExchangeRequired(accountTo, amountToTransfer)) {
exchangedAmountToTransfer = exchangeService.convertInstrument(amountToTransfer, accountTo.getBalance().getCurrency());
}
accountFrom.withdraw(amountToTransfer.getAmount());
accountTo.deposit(exchangedAmountToTransfer.getAmount());
}
private boolean isExchangeRequired(Account accountTo, Instrument amountToTransfer) {
return accountTo.getBalance().getCurrency() != amountToTransfer.getCurrency();
}
private void checkIfAccountBalanceIsValid(Account accountFrom, int amountToTransfer) {
if (accountFrom.getBalance().getAmount() - amountToTransfer < -500) {
throw new IllegalArgumentException("I'm very sorry but you don't have enough money...");
}
}
private void checkIfCurrencyIsValid(Account accountFrom, Account accountTo, Instrument instrument) {
if (accountFrom.getBalance().getCurrency() != instrument.getCurrency())
throw new IllegalArgumentException();
}
}
|
src/main/java/bank/PaymentService.java
|
package bank;
/**
* Tdd training on 15.10.17.
*/
public class PaymentService {
private final ExchangeService exchangeServiceMock;
public PaymentService(ExchangeService exchangeServiceMock) {
this.exchangeServiceMock = exchangeServiceMock;
}
public void transferMoney(Account accountFrom, Account accountTo, Instrument amountToTransfer) {
checkIfCurrencyIsValid(accountFrom, accountTo, amountToTransfer);
checkIfAccountBalanceIsValid(accountFrom, amountToTransfer.getAmount());
Instrument exchangedAmountToTransfer = amountToTransfer;
if (accountTo.getBalance().getCurrency()!=amountToTransfer.getCurrency()){
ExchangeService exchangeService = exchangeServiceMock;
exchangedAmountToTransfer = exchangeService.convertInstrument(amountToTransfer, accountTo.getBalance().getCurrency());
}
accountFrom.withdraw(amountToTransfer.getAmount());
accountTo.deposit(exchangedAmountToTransfer.getAmount());
}
private void checkIfAccountBalanceIsValid(Account accountFrom, int amountToTransfer) {
if (accountFrom.getBalance().getAmount() - amountToTransfer < -500) {
throw new IllegalArgumentException("I'm very sorry but you don't have enough money...");
}
}
private void checkIfCurrencyIsValid(Account accountFrom, Account accountTo, Instrument instrument) {
if ( accountFrom.getBalance().getCurrency() != instrument.getCurrency())
throw new IllegalArgumentException();
}
}
|
Refactoring
|
src/main/java/bank/PaymentService.java
|
Refactoring
|
|
Java
|
mit
|
303ae09f92055330a133082b82edc3a13fdd4b41
| 0
|
DDoS/SpongeCommon,SpongePowered/SpongeCommon,clienthax/SpongeCommon,Grinch/SpongeCommon,DDoS/SpongeCommon,sanman00/SpongeCommon,RTLSponge/SpongeCommon,Grinch/SpongeCommon,JBYoshi/SpongeCommon,modwizcode/SpongeCommon,kenzierocks/SpongeCommon,SpongePowered/Sponge,clienthax/SpongeCommon,SpongePowered/Sponge,hsyyid/SpongeCommon,SpongePowered/Sponge,kenzierocks/SpongeCommon,RTLSponge/SpongeCommon,JBYoshi/SpongeCommon,ryantheleach/SpongeCommon,sanman00/SpongeCommon,SpongePowered/SpongeCommon,hsyyid/SpongeCommon,modwizcode/SpongeCommon,ryantheleach/SpongeCommon
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) 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 org.spongepowered.common.data.processor.data.item;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.item.ImmutableAuthorData;
import org.spongepowered.api.data.manipulator.mutable.item.AuthorData;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.common.data.manipulator.mutable.item.SpongeAuthorData;
import org.spongepowered.common.data.processor.common.AbstractItemSingleDataProcessor;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue;
import org.spongepowered.common.data.value.mutable.SpongeValue;
import org.spongepowered.common.text.SpongeTexts;
import java.util.Optional;
public class ItemAuthorDataProcessor extends AbstractItemSingleDataProcessor<Text, Value<Text>, AuthorData, ImmutableAuthorData> {
public ItemAuthorDataProcessor() {
super(input -> input.getItem() == Items.writable_book || input.getItem() == Items.written_book, Keys.BOOK_AUTHOR);
}
@Override
public DataTransactionResult removeFrom(ValueContainer<?> container) {
return DataTransactionResult.failNoData();
}
@Override
protected AuthorData createManipulator() {
return new SpongeAuthorData();
}
@Override
protected boolean set(ItemStack itemStack, Text value) {
if (!itemStack.hasTagCompound()) {
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.getTagCompound().setString(NbtDataUtil.ITEM_BOOK_AUTHOR, SpongeTexts.toLegacy(value));
return true;
}
@Override
protected Optional<Text> getVal(ItemStack itemStack) {
if (!itemStack.hasTagCompound() || !itemStack.getTagCompound().hasKey(NbtDataUtil.ITEM_BOOK_AUTHOR)) {
return Optional.empty();
}
final String json = itemStack.getTagCompound().getString(NbtDataUtil.ITEM_BOOK_AUTHOR);
final Text author = TextSerializers.JSON.deserializeUnchecked(json);
return Optional.of(author);
}
@Override
protected Value<Text> constructValue(Text actualValue) {
return new SpongeValue<>(Keys.BOOK_AUTHOR, Text.of(), actualValue);
}
@Override
protected ImmutableValue<Text> constructImmutableValue(Text value) {
return new ImmutableSpongeValue<>(Keys.BOOK_AUTHOR, Text.of(), value);
}
}
|
src/main/java/org/spongepowered/common/data/processor/data/item/ItemAuthorDataProcessor.java
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) 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 org.spongepowered.common.data.processor.data.item;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.item.ImmutableAuthorData;
import org.spongepowered.api.data.manipulator.mutable.item.AuthorData;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.common.data.manipulator.mutable.item.SpongeAuthorData;
import org.spongepowered.common.data.processor.common.AbstractItemSingleDataProcessor;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue;
import org.spongepowered.common.data.value.mutable.SpongeValue;
import org.spongepowered.common.text.SpongeTexts;
import java.util.Optional;
public class ItemAuthorDataProcessor extends AbstractItemSingleDataProcessor<Text, Value<Text>, AuthorData, ImmutableAuthorData> {
public ItemAuthorDataProcessor() {
super(input -> input.getItem() == Items.writable_book || input.getItem() == Items.written_book, Keys.BOOK_AUTHOR);
}
@Override
public DataTransactionResult removeFrom(ValueContainer<?> container) {
return DataTransactionResult.failNoData();
}
@Override
protected AuthorData createManipulator() {
return new SpongeAuthorData();
}
@Override
protected boolean set(ItemStack itemStack, Text value) {
if (!itemStack.hasTagCompound()) {
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.getTagCompound().setString(NbtDataUtil.ITEM_BOOK_AUTHOR, SpongeTexts.toLegacy(value));
return true;
}
@Override
protected Optional<Text> getVal(ItemStack itemStack) {
if (!itemStack.hasTagCompound() || !itemStack.getTagCompound().hasKey(NbtDataUtil.ITEM_BOOK_AUTHOR)) {
return Optional.empty();
}
final String json = itemStack.getTagCompound().getString(NbtDataUtil.ITEM_BOOK_AUTHOR);
final Text author = TextSerializers.JSON.deserialize(json);
return Optional.of(author);
}
@Override
protected Value<Text> constructValue(Text actualValue) {
return new SpongeValue<>(Keys.BOOK_AUTHOR, Text.of(), actualValue);
}
@Override
protected ImmutableValue<Text> constructImmutableValue(Text value) {
return new ImmutableSpongeValue<>(Keys.BOOK_AUTHOR, Text.of(), value);
}
}
|
Use TextSerializer#deserializeUnchecked when deserializing ItemStack NBT
Fixes SpongePowered/SpongeForge#591
|
src/main/java/org/spongepowered/common/data/processor/data/item/ItemAuthorDataProcessor.java
|
Use TextSerializer#deserializeUnchecked when deserializing ItemStack NBT
|
|
Java
|
epl-1.0
|
605fc8d982718e81b563450a9159f45b7369919a
| 0
|
ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio
|
package org.csstudio.nams.service.configurationaccess.localstore.internalDTOs.filterConditionSpecifics;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.csstudio.nams.common.fachwert.MessageKeyEnum;
import org.csstudio.nams.common.fachwert.Millisekunden;
import org.csstudio.nams.common.material.regelwerk.Operator;
import org.csstudio.nams.common.material.regelwerk.StringRegelOperator;
import org.csstudio.nams.service.configurationaccess.localstore.internalDTOs.FilterConditionDTO;
/**
* Dieses Daten-Transfer-Objekt stellt hält die Konfiguration einer
* AMS_FilterCond_TimeBasedItems.
*
* Das Create-Statement für die Datenbank hat folgendes Aussehen:
*
* <pre>
* create table AMS_FilterCond_TimeBased
*
* iFilterConditionRef INT NOT NULL,
* cStartKeyValue VARCHAR(16),
* sStartOperator SMALLINT,
* cStartCompValue VARCHAR(128),
* cConfirmKeyValue VARCHAR(16),
* sConfirmOperator SMALLINT,
* cConfirmCompValue VARCHAR(128),
* sTimePeriod SMALLINT,
* sTimeBehavior SMALLINT
* ;
* </pre>
*/
@Entity
@Table(name = "AMS_FilterCond_TimeBased")
@PrimaryKeyJoinColumn(name = "iFilterConditionRef")
public class TimeBasedFilterConditionDTO extends FilterConditionDTO {
@SuppressWarnings("unused")
protected void setFilterConditionTypeRef(int typeRef){
super.filterCondtionTypeRef = 2;
}
public int getFilterConditionTypeRef(){
return filterCondtionTypeRef;
}
public String getCStartKeyValue() {
return cStartKeyValue;
}
@SuppressWarnings("unused")
private void setCStartKeyValue(String startKeyValue) {
cStartKeyValue = startKeyValue;
}
public MessageKeyEnum getStartKeyValue(){
return MessageKeyEnum.valueOf(cStartKeyValue);
}
public String getCStartCompValue() {
return cStartCompValue;
}
public void setCStartCompValue(String startCompValue) {
cStartCompValue = startCompValue;
}
@SuppressWarnings("unused")
private String getCConfirmKeyValue() {
return cConfirmKeyValue;
}
public MessageKeyEnum getConfirmKeyValue(){
return MessageKeyEnum.valueOf(cConfirmKeyValue);
}
public void setCConfirmKeyValue(String confirmKeyValue) {
cConfirmKeyValue = confirmKeyValue;
}
public String getCConfirmCompValue() {
return cConfirmCompValue;
}
public void setCConfirmCompValue(String confirmCompValue) {
cConfirmCompValue = confirmCompValue;
}
public TimeBasedType getTimeBehavior() {
return TimeBasedType.valueOf(sTimeBehavior);
}
public void setTimeBehavior(TimeBasedType timeBasedType){
sTimeBehavior = timeBasedType.asShort();
}
@SuppressWarnings("unused")
private short getSTimeBehavior() {
return sTimeBehavior;
}
@SuppressWarnings("unused")
private void setSTimeBehavior(short timeBehavior) {
sTimeBehavior = timeBehavior;
}
public Millisekunden getTimePeriod() {
return Millisekunden.valueOf(sTimePeriod * 1000);
}
public void setTimePeriod(Millisekunden millisekunden) {
sTimePeriod = (short) (millisekunden.alsLongVonMillisekunden() / 1000);
}
public StringRegelOperator getTBStartOperator () {
return StringRegelOperator.valueOf(sStartOperator);
}
public void setTBStartOperator (Operator operator) {
sStartOperator = operator.asDatabaseId();
}
public StringRegelOperator getTBConfirmOperator () {
return StringRegelOperator.valueOf(sConfirmOperator);
}
public void setTBConfirmOperator (Operator operator) {
sConfirmOperator = operator.asDatabaseId();
}
@SuppressWarnings("unused")
private int getIFilterConditionRef() {
return iFilterConditionRef;
}
@SuppressWarnings("unused")
private void setIFilterConditionRef(int filterConditionRef) {
iFilterConditionRef = filterConditionRef;
}
@SuppressWarnings("unused")
private short getSStartOperator() {
return sStartOperator;
}
@SuppressWarnings("unused")
private void setSStartOperator(short startOperator) {
sStartOperator = startOperator;
}
@SuppressWarnings("unused")
private short getSConfirmOperator() {
return sConfirmOperator;
}
@SuppressWarnings("unused")
private void setSConfirmOperator(short confirmOperator) {
sConfirmOperator = confirmOperator;
}
@SuppressWarnings("unused")
private short getSTimePeriod() {
return sTimePeriod;
}
@SuppressWarnings("unused")
private void setSTimePeriod(short timePeriod) {
sTimePeriod = timePeriod;
}
@Column(name = "iFilterConditionRef", nullable = false, updatable = false, insertable = false)
private int iFilterConditionRef;
@Column(name = "cStartKeyValue")
private String cStartKeyValue;
@Column(name = "sStartOperator")
private short sStartOperator;
@Column(name = "cStartCompValue")
private String cStartCompValue;
@Column(name = "cConfirmKeyValue")
private String cConfirmKeyValue;
@Column(name = "sConfirmOperator")
private short sConfirmOperator;
@Column(name = "cConfirmCompValue")
private String cConfirmCompValue;
@Column(name="sTimePeriod")
private short sTimePeriod;
@Column(name="sTimeBehavior")
private short sTimeBehavior;
}
|
applications/plugins/org.csstudio.nams.service.configurationAccess.localStore/src/org/csstudio/nams/service/configurationaccess/localstore/internalDTOs/filterConditionSpecifics/TimeBasedFilterConditionDTO.java
|
package org.csstudio.nams.service.configurationaccess.localstore.internalDTOs.filterConditionSpecifics;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.csstudio.nams.common.fachwert.MessageKeyEnum;
import org.csstudio.nams.common.fachwert.Millisekunden;
import org.csstudio.nams.common.material.regelwerk.Operator;
import org.csstudio.nams.common.material.regelwerk.StringRegelOperator;
import org.csstudio.nams.service.configurationaccess.localstore.internalDTOs.FilterConditionDTO;
/**
* Dieses Daten-Transfer-Objekt stellt hält die Konfiguration einer
* AMS_FilterCond_TimeBasedItems.
*
* Das Create-Statement für die Datenbank hat folgendes Aussehen:
*
* <pre>
* create table AMS_FilterCond_TimeBased
*
* iFilterConditionRef INT NOT NULL,
* cStartKeyValue VARCHAR(16),
* sStartOperator SMALLINT,
* cStartCompValue VARCHAR(128),
* cConfirmKeyValue VARCHAR(16),
* sConfirmOperator SMALLINT,
* cConfirmCompValue VARCHAR(128),
* sTimePeriod SMALLINT,
* sTimeBehavior SMALLINT
* ;
* </pre>
*/
@Entity
@Table(name = "AMS_FilterCond_TimeBased")
@PrimaryKeyJoinColumn(name = "iFilterConditionRef")
public class TimeBasedFilterConditionDTO extends FilterConditionDTO {
@SuppressWarnings("unused")
protected void setFilterConditionTypeRef(int typeRef){
super.filterCondtionTypeRef = 2;
}
public int getFilterConditionTypeRef(){
return filterCondtionTypeRef;
}
public String getCStartKeyValue() {
return cStartKeyValue;
}
@SuppressWarnings("unused")
private void setCStartKeyValue(String startKeyValue) {
cStartKeyValue = startKeyValue;
}
public MessageKeyEnum getStartKeyValue(){
return MessageKeyEnum.valueOf(cStartKeyValue);
}
public String getCStartCompValue() {
return cStartCompValue;
}
public void setCStartCompValue(String startCompValue) {
cStartCompValue = startCompValue;
}
@SuppressWarnings("unused")
private String getCConfirmKeyValue() {
return cConfirmKeyValue;
}
public MessageKeyEnum getConfirmKeyValue(){
return MessageKeyEnum.valueOf(cConfirmKeyValue);
}
public void setCConfirmKeyValue(String confirmKeyValue) {
cConfirmKeyValue = confirmKeyValue;
}
public String getCConfirmCompValue() {
return cConfirmCompValue;
}
public void setCConfirmCompValue(String confirmCompValue) {
cConfirmCompValue = confirmCompValue;
}
public TimeBasedType getTimeBehavior() {
return TimeBasedType.valueOf(sTimeBehavior);
}
public void setTimeBehavior(TimeBasedType timeBasedType){
sTimeBehavior = timeBasedType.asShort();
}
@SuppressWarnings("unused")
private short getSTimeBehavior() {
return sTimeBehavior;
}
@SuppressWarnings("unused")
private void setSTimeBehavior(short timeBehavior) {
sTimeBehavior = timeBehavior;
}
public Millisekunden getTimePeriod() {
return Millisekunden.valueOf(sTimePeriod * 1000);
}
public void setTimePeriod(Millisekunden millisekunden) {
sTimePeriod = (short) (millisekunden.alsLongVonMillisekunden() / 1000);
}
public StringRegelOperator getTBStartOperator () {
return StringRegelOperator.valueOf(sStartOperator);
}
public void setTBStartOperator (Operator operator) {
sStartOperator = operator.asDatabaseId();
}
public StringRegelOperator getTBConfirmOperator () {
return StringRegelOperator.valueOf(sConfirmOperator);
}
public void setTBConfirmOperator (Operator operator) {
sConfirmOperator = operator.asDatabaseId();
}
@SuppressWarnings("unused")
private int getIFilterConditionRef() {
return iFilterConditionRef;
}
@SuppressWarnings("unused")
private void setIFilterConditionRef(int filterConditionRef) {
iFilterConditionRef = filterConditionRef;
}
@SuppressWarnings("unused")
private short getSStartOperator() {
return sStartOperator;
}
@SuppressWarnings("unused")
private void setSStartOperator(short startOperator) {
sStartOperator = startOperator;
}
@SuppressWarnings("unused")
private short getSConfirmOperator() {
return sConfirmOperator;
}
@SuppressWarnings("unused")
private void setSConfirmOperator(short confirmOperator) {
sConfirmOperator = confirmOperator;
}
@SuppressWarnings("unused")
private short getSTimePeriod() {
return sTimePeriod;
}
@SuppressWarnings("unused")
private void setSTimePeriod(short timePeriod) {
sTimePeriod = timePeriod;
}
@Column(name = "iFilterConditionRef", nullable = false, updatable = false, insertable = false)
private int iFilterConditionRef;
@Column(name = "cStartKeyValue")
private String cStartKeyValue;
@Column(name = "sStartOperator")
private short sStartOperator;
@Column(name = "cStartCompValue")
private String cStartCompValue;
@Column(name = "cConfirmKeyValue")
private String cConfirmKeyValue;
@Column(name = "sConfirmOperator")
private short sConfirmOperator;
@Column(name = "cConfirmCompValue")
private String cConfirmCompValue;
@Column(name="sTimePeriod")
private short sTimePeriod;
@Column(name="sTimeBehavior")
private short sTimeBehavior;
}
|
mw: organize imports
|
applications/plugins/org.csstudio.nams.service.configurationAccess.localStore/src/org/csstudio/nams/service/configurationaccess/localstore/internalDTOs/filterConditionSpecifics/TimeBasedFilterConditionDTO.java
|
mw: organize imports
|
|
Java
|
agpl-3.0
|
b7545cdb9d3f70ba1d4c65d93f2d931f696fcee4
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
18fd50f4-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
182d97c4-2e62-11e5-9284-b827eb9e62be
|
18fd50f4-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
18fd50f4-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
d9b68fc2778910448ec7e01f7c7731c99d7577dc
| 0
|
acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive@objectweb.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.config.PAProperties;
import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper;
import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* This class is a utility class to perform modifications and operations on urls.
*/
public class URIBuilder {
private static String[] LOCAL_URLS = {
"", "localhost.localdomain", "localhost", "127.0.0.1"
};
static Logger logger = ProActiveLogger.getLogger(Loggers.UTIL);
//
//-------------------Public methods-------------------------
//
/**
* Checks if the given url is well-formed
* @param url the url to check
* @return The url if well-formed
* @throws URISyntaxException if the url is not well-formed
*/
public static URI checkURI(String url) throws URISyntaxException {
URI u = new URI(url);
String hostname;
try {
hostname = fromLocalhostToHostname(u.getHost());
URI u2 = new URI(u.getScheme(), null, hostname, u.getPort(),
u.getPath(), u.getQuery(), u.getFragment());
return u2;
} catch (UnknownHostException e) {
throw new URISyntaxException(url, "host unknow");
}
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @throws UnknownProtocolException
* @returnan url under the form [protocol:][//host][[/]name]
*/
public static URI buildURI(String host, String name, String protocol)
throws UnknownProtocolException {
return buildURI(host, name, protocol,
RemoteObjectHelper.getDefaultPortForProtocol(protocol));
}
/**
* Returns an url compliant with RFC 2396[//host][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @throws UnknownProtocolException
* @returnan url under the form [//host][[/]name]
*/
public static URI buildURI(String host, String name)
throws UnknownProtocolException {
return buildURI(host, name, null);
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @param port Url's port
* @returnan url under the form [protocol:][//host[:port]][[/]name]
*/
public static URI buildURI(String host, String name, String protocol,
int port) {
return buildURI(host, name, protocol, port, true);
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]name]
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @param port Url's port
* @param replaceHost indicate if internal hooks regarding how to resolve the hostname have to be used
* @see #fromLocalhostToHostname(String localName)
* @see #getHostNameorIP(InetAddress address)
* @returnan url under the form [protocol:][//host[:port]][[/]name]
*/
public static URI buildURI(String host, String name, String protocol,
int port, boolean replaceHost) {
// if (protocol == null) {
// protocol = System.getProperty(Constants.PROPERTY_PA_COMMUNICATION_PROTOCOL);
// }
if (port == 0) {
port = -1;
}
try {
if (replaceHost) {
host = fromLocalhostToHostname(host);
}
if ((name != null) && (!name.startsWith("/"))) {
/* URI does not require a '/' at the beginning of the name like URLs. As we cannot use
* URL directly (because we do not want to register a URL handler), we do this ugly hook.
*/
name = "/" + name;
}
return new URI(protocol, null, host, port, name, null, null);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
public static URI setProtocol(URI uri, String protocol) {
try {
return new URI(protocol, uri.getUserInfo(), uri.getHost(),
uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
/**
* This method build an url in the form protocol://host:port/name where the port
* and protocol are retrieved from system properties
* @param host
* @param name
* @return an Url built from properties
*/
public static URI buildURIFromProperties(String host, String name) {
String port = null;
String protocol = PAProperties.PA_COMMUNICATION_PROTOCOL.getValue();
if (protocol.equals(Constants.RMI_PROTOCOL_IDENTIFIER) ||
protocol.equals(Constants.IBIS_PROTOCOL_IDENTIFIER)) {
port = PAProperties.PA_RMI_PORT.getValue();
}
if (protocol.equals(Constants.XMLHTTP_PROTOCOL_IDENTIFIER)) {
port = PAProperties.PA_XMLHTTP_PORT.getValue();
}
if (port == null) {
try {
return buildURI(host, name, protocol);
} catch (UnknownProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} else {
return buildURI(host, name, protocol, new Integer(port).intValue());
}
}
/**
* build a virtual node url from a given url
* @param url
* @return
* @throws java.net.UnknownHostException if no network interface was found
*/
public static URI buildVirtualNodeUrl(URI uri)
throws java.net.UnknownHostException {
String vnName = getNameFromURI(uri);
vnName = vnName.concat("_VN");
String host = getHostNameFromUrl(uri);
String protocol = uri.getScheme();
int port = uri.getPort();
return buildURI(host, vnName, protocol, port);
}
public static String appendVnSuffix(String name) {
return name.concat("_VN");
}
public static String removeVnSuffix(String url) {
int index = url.lastIndexOf("_VN");
if (index == -1) {
return url;
}
return url.substring(0, index);
}
/**
* Returns the name included in the url
* @param url
* @return the name included in the url
*/
public static String getNameFromURI(URI u) {
String path = u.getPath();
if ((path != null) && (path.startsWith("/"))) {
// remove the intial '/'
return path.substring(1);
}
return path;
}
/**
* Return the protocol specified in the string
* The same convention as in URL is used
*/
public static String getProtocol(URI uri) {
String protocol = uri.getScheme();
if (protocol == null) {
return Constants.DEFAULT_PROTOCOL_IDENTIFIER;
}
return protocol;
}
/**
* Returns the url without protocol
*/
public static URI removeProtocol(URI uri) {
return buildURI(getHostNameFromUrl(uri), uri.getPath(), null,
uri.getPort(), false);
}
public static String getHostNameFromUrl(URI uri) {
return uri.getHost();
}
public static String removePortFromHost(String hostname) {
try {
URI uri = new URI(hostname);
return uri.getHost();
} catch (URISyntaxException e) {
e.printStackTrace();
return hostname;
}
}
/**
* this method returns the hostname or the IP address associated to the InetAddress address parameter.
* It is possible to set {@code "proactive.runtime.ipaddress"} or
* {@code "proactive.hostname"} or the {@code "proactive.useIPaddress"} property (evaluated in that order) to override the default java behaviour
* of resolving InetAddress
* @param address any InetAddress
* @return a String matching the corresponding InetAddress
*/
public static String getHostNameorIP(InetAddress address) {
address = UrlBuilder.getNetworkInterfaces();
if (PAProperties.PA_RUNTIME_IPADDRESS.getValue() != null) {
return PAProperties.PA_RUNTIME_IPADDRESS.getValue();
}
if (PAProperties.PA_HOSTNAME.getValue() != null) {
return PAProperties.PA_HOSTNAME.getValue();
}
String temp = "";
if (PAProperties.PA_USE_IP_ADDRESS.isTrue()) {
temp = ((Inet6Address) address).getHostAddress();
} else {
temp = address.getCanonicalHostName();
}
return URIBuilder.ipv6withoutscope(temp);
}
/**
* evaluate if localName is a loopback entry, if yes calls {@link getHostNameorIP(InetAddress address)}
* @param localName
* @return a remotely accessible host name if exists
* @throws UnknownHostException if no network interface was found
* @see getHostNameorIP(InetAddress address)
*/
public static String fromLocalhostToHostname(String localName)
throws UnknownHostException {
if (localName == null) {
localName = "localhost";
}
java.net.InetAddress hostInetAddress = java.net.InetAddress.getLocalHost();
for (int i = 0; i < LOCAL_URLS.length; i++) {
if (LOCAL_URLS[i].startsWith(localName.toLowerCase())) {
return UrlBuilder.getHostNameorIP(hostInetAddress);
}
}
return localName;
}
/**
* This method extract the port from a string in the form host:port or host
* @param url
* @return port number or 0 if there is no port
*/
public static int getPortNumber(String url) {
try {
URI uri = new URI(url);
if (uri.getPort() != -1) {
return uri.getPort();
}
return 0;
} catch (URISyntaxException e) {
return 0;
}
}
/**
* change the port of a given url
* @param url the url to change the port
* @param port the new port number
* @return the url with the new port
*/
public static URI setPort(URI u, int port) {
URI u2;
try {
u2 = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), port,
u.getPath(), u.getQuery(), u.getFragment());
return u2;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return u;
}
public static String ipv6withoutscope(String address) {
String name = address;
int indexPercent = name.indexOf('%');
if (indexPercent != 0) {
return "[" + name.substring(0, indexPercent) + "]";
} else {
return address;
}
}
public static String ipv6withoutscope(InetAddress address) {
String name = address.getHostAddress();
int indexPercent = name.indexOf('%');
if (indexPercent != 0) {
return "[" + name.substring(0, indexPercent) + "]";
} else {
return name;
}
}
}
|
src/Core/org/objectweb/proactive/core/util/URIBuilder.java
|
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: proactive@objectweb.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.util;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.config.PAProperties;
import org.objectweb.proactive.core.remoteobject.RemoteObjectHelper;
import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* This class is a utility class to perform modifications and operations on urls.
*/
public class URIBuilder {
private static String[] LOCAL_URLS = {
"", "localhost.localdomain", "localhost", "127.0.0.1"
};
static Logger logger = ProActiveLogger.getLogger(Loggers.UTIL);
//
//-------------------Public methods-------------------------
//
/**
* Checks if the given url is well-formed
* @param url the url to check
* @return The url if well-formed
* @throws URISyntaxException if the url is not well-formed
*/
public static URI checkURI(String url) throws URISyntaxException {
URI u = new URI(url);
String hostname;
try {
hostname = fromLocalhostToHostname(u.getHost());
URI u2 = new URI(u.getScheme(), null, hostname, u.getPort(),
u.getPath(), u.getQuery(), u.getFragment());
return u2;
} catch (UnknownHostException e) {
throw new URISyntaxException(url, "host unknow");
}
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @throws UnknownProtocolException
* @returnan url under the form [protocol:][//host][[/]name]
*/
public static URI buildURI(String host, String name, String protocol)
throws UnknownProtocolException {
return buildURI(host, name, protocol,
RemoteObjectHelper.getDefaultPortForProtocol(protocol));
}
/**
* Returns an url compliant with RFC 2396[//host][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @throws UnknownProtocolException
* @returnan url under the form [//host][[/]name]
*/
public static URI buildURI(String host, String name)
throws UnknownProtocolException {
return buildURI(host, name, null);
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]path]
* loopback address is replaced by a non-loopback address localhost -> [DNS/IP] Address
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @param port Url's port
* @returnan url under the form [protocol:][//host[:port]][[/]name]
*/
public static URI buildURI(String host, String name, String protocol,
int port) {
return buildURI(host, name, protocol, port, true);
}
/**
* Returns an url compliant with RFC 2396 [protocol:][//host[:port]][[/]name]
* @param host Url's hostname
* @param name Url's Path
* @param protocol Url's protocol
* @param port Url's port
* @param replaceHost indicate if internal hooks regarding how to resolve the hostname have to be used
* @see #fromLocalhostToHostname(String localName)
* @see #getHostNameorIP(InetAddress address)
* @returnan url under the form [protocol:][//host[:port]][[/]name]
*/
public static URI buildURI(String host, String name, String protocol,
int port, boolean replaceHost) {
// if (protocol == null) {
// protocol = System.getProperty(Constants.PROPERTY_PA_COMMUNICATION_PROTOCOL);
// }
if (port == 0) {
port = -1;
}
try {
if (replaceHost) {
host = fromLocalhostToHostname(host);
}
if ((name != null) && (!name.startsWith("/"))) {
/* URI does not require a '/' at the beginning of the name like URLs. As we cannot use
* URL directly (because we do not want to register a URL handler), we do this ugly hook.
*/
name = "/" + name;
}
return new URI(protocol, null, host, port, name, null, null);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return null;
}
public static URI setProtocol(URI uri, String protocol) {
try {
return new URI(protocol, uri.getUserInfo(), uri.getHost(),
uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
/**
* This method build an url in the form protocol://host:port/name where the port
* and protocol are retrieved from system properties
* @param host
* @param name
* @return an Url built from properties
*/
public static URI buildURIFromProperties(String host, String name) {
String port = null;
String protocol = PAProperties.PA_COMMUNICATION_PROTOCOL.getValue();
if (protocol.equals(Constants.RMI_PROTOCOL_IDENTIFIER) ||
protocol.equals(Constants.IBIS_PROTOCOL_IDENTIFIER)) {
port = PAProperties.PA_RMI_PORT.getValue();
}
if (protocol.equals(Constants.XMLHTTP_PROTOCOL_IDENTIFIER)) {
port = PAProperties.PA_XMLHTTP_PORT.getValue();
}
if (port == null) {
try {
return buildURI(host, name, protocol);
} catch (UnknownProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} else {
return buildURI(host, name, protocol, new Integer(port).intValue());
}
}
/**
* build a virtual node url from a given url
* @param url
* @return
* @throws java.net.UnknownHostException if no network interface was found
*/
public static URI buildVirtualNodeUrl(URI uri)
throws java.net.UnknownHostException {
String vnName = getNameFromURI(uri);
vnName = vnName.concat("_VN");
String host = getHostNameFromUrl(uri);
String protocol = uri.getScheme();
int port = uri.getPort();
return buildURI(host, vnName, protocol, port);
}
public static String appendVnSuffix(String name) {
return name.concat("_VN");
}
public static String removeVnSuffix(String url) {
int index = url.lastIndexOf("_VN");
if (index == -1) {
return url;
}
return url.substring(0, index);
}
/**
* Returns the name included in the url
* @param url
* @return the name included in the url
*/
public static String getNameFromURI(URI u) {
String path = u.getPath();
if ((path != null) && (path.startsWith("/"))) {
// remove the intial '/'
return path.substring(1);
}
return path;
}
/**
* Return the protocol specified in the string
* The same convention as in URL is used
*/
public static String getProtocol(URI uri) {
String protocol = uri.getScheme();
if (protocol == null) {
return Constants.DEFAULT_PROTOCOL_IDENTIFIER;
}
return protocol;
}
/**
* Returns the url without protocol
*/
public static URI removeProtocol(URI uri) {
return buildURI(getHostNameFromUrl(uri), uri.getPath(), null,
uri.getPort(), false);
}
public static String getHostNameFromUrl(URI uri) {
return uri.getHost();
}
public static String removePortFromHost(String hostname) {
try {
URI uri = new URI(hostname);
return uri.getHost();
} catch (URISyntaxException e) {
e.printStackTrace();
return hostname;
}
}
/**
* this method returns the hostname or the IP address associated to the InetAddress address parameter.
* It is possible to set {@code "proactive.runtime.ipaddress"} or
* {@code "proactive.hostname"} or the {@code "proactive.useIPaddress"} property (evaluated in that order) to override the default java behaviour
* of resolving InetAddress
* @param address any InetAddress
* @return a String matching the corresponding InetAddress
*/
public static String getHostNameorIP(InetAddress address) {
if (PAProperties.PA_RUNTIME_IPADDRESS.getValue() != null) {
return PAProperties.PA_RUNTIME_IPADDRESS.getValue();
}
if (PAProperties.PA_HOSTNAME.getValue() != null) {
return PAProperties.PA_HOSTNAME.getValue();
}
if (PAProperties.PA_USE_IP_ADDRESS.isTrue()) {
return address.getHostAddress();
} else {
return address.getCanonicalHostName();
}
}
/**
* evaluate if localName is a loopback entry, if yes calls {@link getHostNameorIP(InetAddress address)}
* @param localName
* @return a remotely accessible host name if exists
* @throws UnknownHostException if no network interface was found
* @see getHostNameorIP(InetAddress address)
*/
public static String fromLocalhostToHostname(String localName)
throws UnknownHostException {
if (localName == null) {
localName = "localhost";
}
java.net.InetAddress hostInetAddress = java.net.InetAddress.getLocalHost();
for (int i = 0; i < LOCAL_URLS.length; i++) {
if (LOCAL_URLS[i].startsWith(localName.toLowerCase())) {
return UrlBuilder.getHostNameorIP(hostInetAddress);
}
}
return localName;
}
/**
* This method extract the port from a string in the form host:port or host
* @param url
* @return port number or 0 if there is no port
*/
public static int getPortNumber(String url) {
try {
URI uri = new URI(url);
if (uri.getPort() != -1) {
return uri.getPort();
}
return 0;
} catch (URISyntaxException e) {
return 0;
}
}
/**
* change the port of a given url
* @param url the url to change the port
* @param port the new port number
* @return the url with the new port
*/
public static URI setPort(URI u, int port) {
URI u2;
try {
u2 = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), port,
u.getPath(), u.getQuery(), u.getFragment());
return u2;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return u;
}
}
|
Javadocs for remote objects part2, the missing file
git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@6212 28e8926c-6b08-0410-baaa-805c5e19b8d6
|
src/Core/org/objectweb/proactive/core/util/URIBuilder.java
|
Javadocs for remote objects part2, the missing file
|
|
Java
|
lgpl-2.1
|
772d8e473d48cb81ecfd4f15c160b82eb51c38f7
| 0
|
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
|
package org.intermine.webservice.server.output;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.api.query.MainHelper;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.metadata.Model;
import org.intermine.model.testmodel.Company;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.objectstore.dummy.DummyResults;
import org.intermine.objectstore.dummy.ObjectStoreDummyImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.DynamicUtil;
import org.intermine.util.IteratorIterable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import junit.framework.TestCase;
/**
* Tests for the JSONResultsIterator class
*
* @author Alexis Kalderimis
*/
public class JSONResultsIteratorTest extends TestCase {
/**
* Compare two JSONObjects for equality
* @param left The reference JSONObject (this is referred to as "expected" in any messages)
* @param right The candidate object to check.
* @return a String with messages explaining the problems if there are any, otherwise null (equal)
* @throws JSONException
*/
private static String getProblemsComparing(JSONObject left, Object right) throws JSONException {
List<String> problems = new ArrayList<String>();
if (left == null ) {
if (right != null) {
return "Expected null, but got " + right;
} else {
return null;
}
}
if (! (right instanceof JSONObject)) {
if (right == null) {
return "Didn't expect null, but got null";
} else {
return "Expected a JSONObject, is got a " + right.getClass();
}
}
JSONObject rjo = (JSONObject) right;
Set<String> leftNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(left)));
Set<String> rightNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(rjo)));
if (! leftNames.equals(rightNames)) {
problems.add("Expected the keys " +
leftNames + ", but got these: " + rightNames);
}
for (String name : leftNames) {
Object leftValue = left.get(name);
String problem = null;
try {
if (leftValue == null) {
if ( rjo.get(name) != null ) {
problem = "Expected null, but got " + rjo.get(name);
}
} else if (leftValue instanceof JSONObject) {
problem = getProblemsComparing((JSONObject) leftValue, rjo.get(name));
} else if (leftValue instanceof JSONArray) {
problem = getProblemsComparing((JSONArray) leftValue, rjo.get(name));
} else {
if (! leftValue.toString().equals(rjo.get(name).toString())) {
problem = "Expected " + leftValue + " but got " + rjo.get(name);
}
}
} catch (Throwable e) {
problem = e.toString();
}
if (problem != null) {
problems.add("Problem with " + name + ": " + problem);
}
}
if (problems.isEmpty()) {
return null;
}
return problems.toString();
}
/**
* Compare two JSONArrays for equality
* @param left The reference array (referred to as "expected" in any messages)
* @param right The candidate object to check.
* @return a String with messages explaining the problems if there are any, otherwise null (equal)
* @throws JSONException
*/
private static String getProblemsComparing(JSONArray left, Object right) throws JSONException {
List<String> problems = new ArrayList<String>();
if (left == null ) {
if (right != null) {
return "Expected null, but got " + right;
} else {
return null;
}
}
if (! (right instanceof JSONArray)) {
return "Expected a JSONArray, but got a " + right.getClass();
}
JSONArray rja = (JSONArray) right;
if (left.length() != rja.length()) {
problems.add("Expected the size of this array to be " + left.length() +
" but got " + rja.length());
}
for (int index = 0; index < left.length(); index++) {
Object leftMember = left.get(index);
String problem = null;
try {
if (leftMember== null) {
if ( rja.get(index) != null ) {
problem = "Expected null, but got " + rja.get(index);
}
} else if (leftMember instanceof JSONObject) {
problem = getProblemsComparing((JSONObject) leftMember, rja.get(index));
} else if (leftMember instanceof JSONArray) {
problem = getProblemsComparing((JSONArray) leftMember, rja.get(index));
} else {
if (! leftMember.toString().equals(rja.get(index).toString())) {
problem = "Expected " + leftMember +
" but got " + rja.get(index);
}
}
} catch (Throwable e) {
problem = e.toString();
}
if (problem != null) {
problems.add("Problem with index " + index + ": " + problem);
}
}
if (problems.isEmpty()) {
return null;
}
return problems.toString();
}
private final Model model = Model.getInstanceByName("testmodel");
public JSONResultsIteratorTest(String arg) {
super(arg);
}
public void testNestedCollection() throws Exception {
ObjectStoreDummyImpl os = new ObjectStoreDummyImpl();
os.setResultsSize(1);
// Set up some known objects in the first 3 results rows
Company company1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
company1.setName("Company1");
company1.setVatNumber(101);
company1.setId(new Integer(1));
Department department1 = new Department();
department1.setName("Department1");
department1.setId(new Integer(2));
Department department2 = new Department();
department2.setName("Department2");
department2.setId(new Integer(3));
Employee employee1 = new Employee();
employee1.setName("Employee1");
employee1.setId(new Integer(4));
employee1.setAge(42);
Employee employee2 = new Employee();
employee2.setName("Employee2");
employee2.setId(new Integer(5));
employee2.setAge(43);
Employee employee3 = new Employee();
employee3.setName("Employee3");
employee3.setId(new Integer(6));
employee3.setAge(44);
Employee employee4 = new Employee();
employee4.setName("Employee4");
employee4.setId(new Integer(7));
employee4.setAge(45);
ResultsRow row = new ResultsRow();
row.add(company1);
List sub1 = new ArrayList();
ResultsRow subRow1 = new ResultsRow();
subRow1.add(department1);
List sub2 = new ArrayList();
ResultsRow subRow2 = new ResultsRow();
subRow2.add(employee1);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(employee2);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
subRow1 = new ResultsRow();
subRow1.add(department2);
sub2 = new ArrayList();
subRow2 = new ResultsRow();
subRow2.add(employee3);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(employee4);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
row.add(sub1);
os.addRow(row);
PathQuery pq = new PathQuery(model);
pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name");
pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER);
pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER);
Map pathToQueryNode = new HashMap();
Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
List resultList = os.execute(q, 0, 1, true, true, new HashMap());
Results results = new DummyResults(q, resultList);
ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode);
JsonResultsIterator jsonIter = new JsonResultsIterator(iter);
List<JSONObject> got = new ArrayList<JSONObject>();
for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) {
got.add(gotRow);
}
assertEquals(got.size(), 1);
String jsonString = "{" +
"\"objectId\" : 1," +
"\"name\" : \"Company1\"," +
"\"class\" : \"Company\"," +
"\"departments\" : [" +
"{" +
"\"objectId\" : 2," +
"\"name\":\"Department1\"," +
"\"class\":\"Department\"," +
"\"employees\" : [" +
"{" +
"\"objectId\" : 4," +
"\"name\" : \"Employee1\"," +
"\"class\" : \"Employee\"" +
"}," +
"{" +
" \"objectId\" : 5," +
" \"name\" : \"Employee2\"," +
" \"class\":\"Employee\"" +
"}" +
"]" +
"}," +
"{" +
" \"objectId\" : 3," +
" \"name\" : \"Department2\", " +
" \"class\" : \"Department\"," +
" \"employees\" : [" +
" {" +
" \"objectId\" : 6," +
" \"name\" : \"Employee3\"," +
" \"class\" : \"Employee\"" +
" }," +
" {" +
" \"objectId\" : 7," +
" \"name\" : \"Employee4\"," +
" \"class\" : \"Employee\"" +
" }" +
" ]" +
"}" +
"]," +
"\"vatNumber\" : \"101\"" +
"}";
JSONObject expected = new JSONObject(jsonString);
assertEquals(null, getProblemsComparing(expected, got.get(0)));
}
}
|
intermine/web/test/src/org/intermine/webservice/server/output/JSONResultsIteratorTest.java
|
package org.intermine.webservice.server.output;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.intermine.api.query.MainHelper;
import org.intermine.api.results.ExportResultsIterator;
import org.intermine.api.results.ResultElement;
import org.intermine.metadata.Model;
import org.intermine.model.testmodel.Company;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.objectstore.dummy.DummyResults;
import org.intermine.objectstore.dummy.ObjectStoreDummyImpl;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.DynamicUtil;
import org.intermine.util.IteratorIterable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import junit.framework.TestCase;
/**
* Tests for the JSONResultsIterator class
*
* @author Alexis Kalderimis
*/
public class JSONResultsIteratorTest extends TestCase {
/**
* Compare two JSONObjects for equality
* @param left
* @param right
* @return a String with messages explaining the problems if there are any, otherwise null (equal)
* @throws JSONException
*/
private static String getProblemsComparing(JSONObject left, Object right) throws JSONException {
List<String> problems = new ArrayList<String>();
if (left == null ) {
if (right != null) {
return "Expected null, but got " + right;
} else {
return null;
}
}
if (! (right instanceof JSONObject)) {
if (right == null) {
return "Didn't expect null, but got null";
} else {
return "Expected a JSONObject, is got a " + right.getClass();
}
}
JSONObject rjo = (JSONObject) right;
Set<String> leftNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(left)));
Set<String> rightNames = new HashSet<String>(Arrays.asList(JSONObject.getNames(rjo)));
if (! leftNames.equals(rightNames)) {
problems.add("Expected the keys " +
leftNames + ", but got these: " + rightNames);
}
for (String name : leftNames) {
Object leftValue = left.get(name);
String problem = null;
if (leftValue == null) {
if ( rjo.get(name) != null ) {
problem = "Expected null, but got " + rjo.get(name);
}
} else if (leftValue instanceof JSONObject) {
problem = getProblemsComparing((JSONObject) leftValue, rjo.get(name));
} else if (leftValue instanceof JSONArray) {
problem = getProblemsComparing((JSONArray) leftValue, rjo.get(name));
} else {
if (! leftValue.toString().equals(rjo.get(name).toString())) {
problem = "Expected " + leftValue + " but got " + rjo.get(name);
}
}
if (problem != null) {
problems.add("Problem with " + name + ": " + problem);
}
}
if (problems.isEmpty()) {
return null;
}
return problems.toString();
}
/**
* Compare two JSONArrays for equality
* @param left
* @param right
* @return a String with messages explaining the problems if there are any, otherwise null (equal)
* @throws JSONException
*/
private static String getProblemsComparing(JSONArray left, Object right) throws JSONException {
List<String> problems = new ArrayList<String>();
if (left == null ) {
if (right != null) {
return "Expected null, but got " + right;
} else {
return null;
}
}
if (! (right instanceof JSONArray)) {
return "Expected a JSONArray, but got a " + right.getClass();
}
JSONArray rja = (JSONArray) right;
if (left.length() != rja.length()) {
problems.add("Expected the size of this array to be " + left.length() +
" but got " + rja.length());
}
for (int index = 0; index < left.length(); index++) {
Object leftMember = left.get(index);
String problem = null;
if (leftMember== null) {
if ( rja.get(index) != null ) {
problem = "Expected null, but got " + rja.get(index);
}
} else if (leftMember instanceof JSONObject) {
problem = getProblemsComparing((JSONObject) leftMember, rja.get(index));
} else if (leftMember instanceof JSONArray) {
problem = getProblemsComparing((JSONArray) leftMember, rja.get(index));
} else {
if (! leftMember.toString().equals(rja.get(index).toString())) {
problem = "Expected " + leftMember +
" but got " + rja.get(index);
}
}
if (problem != null) {
problems.add("Problem with index " + index + ": " + problem);
}
}
if (problems.isEmpty()) {
return null;
}
return problems.toString();
}
private final Model model = Model.getInstanceByName("testmodel");
public JSONResultsIteratorTest(String arg) {
super(arg);
}
public void testNestedCollection() throws Exception {
ObjectStoreDummyImpl os = new ObjectStoreDummyImpl();
os.setResultsSize(1);
// Set up some known objects in the first 3 results rows
Company company1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
company1.setName("Company1");
company1.setVatNumber(101);
company1.setId(new Integer(1));
Department department1 = new Department();
department1.setName("Department1");
department1.setId(new Integer(2));
Department department2 = new Department();
department2.setName("Department2");
department2.setId(new Integer(3));
Employee employee1 = new Employee();
employee1.setName("Employee1");
employee1.setId(new Integer(4));
employee1.setAge(42);
Employee employee2 = new Employee();
employee2.setName("Employee2");
employee2.setId(new Integer(5));
employee2.setAge(43);
Employee employee3 = new Employee();
employee3.setName("Employee3");
employee3.setId(new Integer(6));
employee3.setAge(44);
Employee employee4 = new Employee();
employee4.setName("Employee4");
employee4.setId(new Integer(7));
employee4.setAge(45);
ResultsRow row = new ResultsRow();
row.add(company1);
List sub1 = new ArrayList();
ResultsRow subRow1 = new ResultsRow();
subRow1.add(department1);
List sub2 = new ArrayList();
ResultsRow subRow2 = new ResultsRow();
subRow2.add(employee1);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(employee2);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
subRow1 = new ResultsRow();
subRow1.add(department2);
sub2 = new ArrayList();
subRow2 = new ResultsRow();
subRow2.add(employee3);
sub2.add(subRow2);
subRow2 = new ResultsRow();
subRow2.add(employee4);
sub2.add(subRow2);
subRow1.add(sub2);
sub1.add(subRow1);
row.add(sub1);
os.addRow(row);
PathQuery pq = new PathQuery(model);
pq.addViews("Company.name", "Company.vatNumber", "Company.departments.name", "Company.departments.employees.name");
pq.setOuterJoinStatus("Company.departments", OuterJoinStatus.OUTER);
pq.setOuterJoinStatus("Company.departments.employees", OuterJoinStatus.OUTER);
Map pathToQueryNode = new HashMap();
Query q = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
List resultList = os.execute(q, 0, 1, true, true, new HashMap());
Results results = new DummyResults(q, resultList);
ExportResultsIterator iter = new ExportResultsIterator(pq, results, pathToQueryNode);
JsonResultsIterator jsonIter = new JsonResultsIterator(iter);
List<JSONObject> got = new ArrayList<JSONObject>();
for (JSONObject gotRow : new IteratorIterable<JSONObject>(jsonIter)) {
got.add(gotRow);
}
assertEquals(got.size(), 1);
String jsonString = "{" +
"\"objectId\" : 1," +
"\"name\" : \"Company1\"," +
"\"class\" : \"Company\"," +
"\"departments\" : [" +
"{" +
"\"objectId\" : 2," +
"\"name\":\"Department1\"," +
"\"class\":\"Department\"," +
"\"employees\" : [" +
"{" +
"\"objectId\" : 4," +
"\"name\" : \"Employee1\"," +
"\"class\" : \"Employee\"" +
"}," +
"{" +
" \"objectId\" : 5," +
" \"name\" : \"Employee2\"," +
" \"class\":\"Employee\"" +
"}" +
"]" +
"}," +
"{" +
" \"objectId\" : 3," +
" \"name\" : \"Department2\", " +
" \"class\" : \"Department\"," +
" \"employees\" : [" +
" {" +
" \"objectId\" : 6," +
" \"name\" : \"Employee3\"," +
" \"class\" : \"Employee\"" +
" }," +
" {" +
" \"objectId\" : 7," +
" \"name\" : \"Employee4\"," +
" \"class\" : \"Employee\"" +
" }" +
" ]" +
"}" +
"]," +
"\"vatNumber\" : \"101\"" +
"}";
JSONObject expected = new JSONObject(jsonString);
assertEquals(null, getProblemsComparing(expected, got.get(0)));
}
}
|
Now with better error messages and catches missing fields/array elements
Former-commit-id: adae391bdd3f1f55576339c9b0ef89f1c66f4778
|
intermine/web/test/src/org/intermine/webservice/server/output/JSONResultsIteratorTest.java
|
Now with better error messages and catches missing fields/array elements
|
|
Java
|
apache-2.0
|
dca1a020b64f5c3f1b7a8213bfdefb4ddd0bfd79
| 0
|
rawbenny/BroadleafCommerce,alextiannus/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,lgscofield/BroadleafCommerce,lgscofield/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,cengizhanozcan/BroadleafCommerce,zhaorui1/BroadleafCommerce,macielbombonato/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,sitexa/BroadleafCommerce,lgscofield/BroadleafCommerce,cogitoboy/BroadleafCommerce,udayinfy/BroadleafCommerce,macielbombonato/BroadleafCommerce,sanlingdd/broadleaf,liqianggao/BroadleafCommerce,caosg/BroadleafCommerce,shopizer/BroadleafCommerce,liqianggao/BroadleafCommerce,daniellavoie/BroadleafCommerce,daniellavoie/BroadleafCommerce,cogitoboy/BroadleafCommerce,daniellavoie/BroadleafCommerce,sitexa/BroadleafCommerce,cloudbearings/BroadleafCommerce,bijukunjummen/BroadleafCommerce,passion1014/metaworks_framework,shopizer/BroadleafCommerce,zhaorui1/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,wenmangbo/BroadleafCommerce,udayinfy/BroadleafCommerce,alextiannus/BroadleafCommerce,shopizer/BroadleafCommerce,ljshj/BroadleafCommerce,caosg/BroadleafCommerce,bijukunjummen/BroadleafCommerce,bijukunjummen/BroadleafCommerce,rawbenny/BroadleafCommerce,caosg/BroadleafCommerce,macielbombonato/BroadleafCommerce,trombka/blc-tmp,gengzhengtao/BroadleafCommerce,cloudbearings/BroadleafCommerce,udayinfy/BroadleafCommerce,gengzhengtao/BroadleafCommerce,ljshj/BroadleafCommerce,zhaorui1/BroadleafCommerce,alextiannus/BroadleafCommerce,trombka/blc-tmp,passion1014/metaworks_framework,liqianggao/BroadleafCommerce,cogitoboy/BroadleafCommerce,trombka/blc-tmp,passion1014/metaworks_framework,wenmangbo/BroadleafCommerce,sanlingdd/broadleaf,sitexa/BroadleafCommerce,TouK/BroadleafCommerce,TouK/BroadleafCommerce,rawbenny/BroadleafCommerce,TouK/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cloudbearings/BroadleafCommerce,ljshj/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,gengzhengtao/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,wenmangbo/BroadleafCommerce,arshadalisoomro/BroadleafCommerce
|
/*
* #%L
* BroadleafCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.openadmin.web.form.component;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.broadleafcommerce.common.presentation.client.AddMethodType;
import org.broadleafcommerce.common.util.TypedPredicate;
import org.broadleafcommerce.openadmin.dto.SectionCrumb;
import org.broadleafcommerce.openadmin.web.form.entity.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class ListGrid {
protected String className;
protected String friendlyName = null;
protected String idProperty;
protected int order;
protected Set<Field> headerFields = new TreeSet<Field>(new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
return new CompareToBuilder()
.append(o1.getOrder(), o2.getOrder())
.append(o1.getFriendlyName(), o2.getFriendlyName())
.append(o1.getName(), o2.getName())
.toComparison();
}
});
protected List<ListGridRecord> records = new ArrayList<ListGridRecord>();
protected List<ListGridAction> toolbarActions = new ArrayList<ListGridAction>();
// These actions will start greyed out and unable to be clicked until a specific row has been selected
protected List<ListGridAction> rowActions = new ArrayList<ListGridAction>();
protected int totalRecords;
protected int startIndex;
protected int pageSize;
protected Boolean canFilterAndSort;
protected Boolean isReadOnly;
protected Boolean hideIdColumn;
protected AddMethodType addMethodType;
protected String listGridType;
// The section url that maps to this particular list grid
protected String sectionKey;
// The list of all section keys that have been traversed to arrive at this ListGrid (including the current one), in order
// of occurrence
protected List<SectionCrumb> sectionCrumbs = new ArrayList<SectionCrumb>();
// If this list grid is a sublistgrid, meaning it is rendered as part of a different entity, these properties
// help identify the parent entity.
protected String externalEntitySectionKey;
protected String containingEntityId;
protected String subCollectionFieldName;
protected String pathOverride;
public enum Type {
MAIN,
INLINE,
INLINEMULTI,
TO_ONE,
BASIC,
ADORNED,
ADORNED_WITH_FORM,
MAP,
TRANSLATION,
ASSET
}
/* ************** */
/* CUSTOM METHODS */
/* ************** */
public String getPath() {
if (StringUtils.isNotBlank(pathOverride)) {
return pathOverride;
}
StringBuilder sb = new StringBuilder();
if (!getSectionKey().startsWith("/")) {
sb.append("/");
}
sb.append(getSectionKey());
if (getContainingEntityId() != null) {
sb.append("/").append(getContainingEntityId());
}
if (StringUtils.isNotBlank(getSubCollectionFieldName())) {
sb.append("/").append(getSubCollectionFieldName());
}
//to-one grids need a slightly different grid URL; these need to be appended with 'select'
//TODO: surely there's a better way to do this besides just hardcoding the 'select'?
if (Type.TO_ONE.toString().toLowerCase().equals(listGridType)) {
sb.append("/select");
}
return sb.toString();
}
public String getSectionCrumbRepresentation() {
StringBuilder sb = new StringBuilder();
if (!sectionCrumbs.isEmpty()) {
sb.append("?sectionCrumbs=");
}
int index = 0;
for (SectionCrumb section : sectionCrumbs) {
sb.append(section.getSectionIdentifier());
sb.append("--");
sb.append(section.getSectionId());
if (index < sectionCrumbs.size()-1) {
sb.append(",");
}
index++;
}
return sb.toString();
}
/**
* Grabs a filtered list of toolbar actions filtered by whether or not they match the same readonly state as the listgrid
* and are thus shown on the screen
*/
@SuppressWarnings("unchecked")
public List<ListGridAction> getActiveToolbarActions() {
return (List<ListGridAction>) CollectionUtils.select(getToolbarActions(), new TypedPredicate<ListGridAction>() {
@Override
public boolean eval(ListGridAction action) {
return action.getForListGridReadOnly().equals(getReadOnly());
}
});
}
/**
* Grabs a filtered list of row actions filtered by whether or not they match the same readonly state as the listgrid
* and are thus shown on the screen
*/
@SuppressWarnings("unchecked")
public List<ListGridAction> getActiveRowActions() {
return (List<ListGridAction>) CollectionUtils.select(getRowActions(), new TypedPredicate<ListGridAction>() {
@Override
public boolean eval(ListGridAction action) {
return action.getForListGridReadOnly().equals(getReadOnly());
}
});
}
public void addRowAction(ListGridAction action) {
getRowActions().add(action);
}
public void addToolbarAction(ListGridAction action) {
getToolbarActions().add(action);
}
public void removeAllToolbarActions() {
getToolbarActions().clear();
}
public void removeAllRowActions() {
getRowActions().clear();
}
public ListGridAction findToolbarAction(String actionId) {
for (ListGridAction action : getToolbarActions()) {
if (action.getActionId().equals(actionId)) {
return action;
}
}
return null;
}
public ListGridAction findRowAction(String actionId) {
for (ListGridAction action : getRowActions()) {
if (action.getActionId().equals(actionId)) {
return action;
}
}
return null;
}
/**
* This grid is sortable if there is a reorder action defined in the toolbar. If records can be reordered, then the
* sort functionality doesn't make any sense.
*
* Also, map structures are currently unsortable.
*
* @return
*/
public boolean isSortable() {
return getToolbarActions().contains(DefaultListGridActions.REORDER) ||
Type.MAP.toString().toLowerCase().equals(getListGridType());
}
/* ************************ */
/* CUSTOM GETTERS / SETTERS */
/* ************************ */
public void setListGridType(Type listGridType) {
this.listGridType = listGridType.toString().toLowerCase();
}
/**
* Allows for completely custom types other than the ones defined {@link Type} to assign unique handlers to on the JS
* side
* @param listGridType
*/
public void setListGridTypeString(String listGridType) {
this.listGridType = listGridType;
}
public Boolean getCanFilterAndSort() {
return (canFilterAndSort == null ? true : canFilterAndSort);
}
public Boolean getReadOnly() {
return isReadOnly == null ? false : isReadOnly;
}
public Boolean getClickable() {
return !"main".equals(listGridType);
}
public Boolean getHideIdColumn() {
return hideIdColumn == null ? false : hideIdColumn;
}
/* ************************** */
/* STANDARD GETTERS / SETTERS */
/* ************************** */
public String getIdProperty() {
return idProperty;
}
public void setIdProperty(String idProperty) {
this.idProperty = idProperty;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Set<Field> getHeaderFields() {
return headerFields;
}
public void setHeaderFields(Set<Field> headerFields) {
this.headerFields = headerFields;
}
public List<ListGridRecord> getRecords() {
return records;
}
public void setRecords(List<ListGridRecord> records) {
this.records = records;
}
public List<ListGridAction> getToolbarActions() {
return toolbarActions;
}
public void setToolbarActions(List<ListGridAction> toolbarActions) {
this.toolbarActions = toolbarActions;
}
public List<ListGridAction> getRowActions() {
return rowActions;
}
public void setRowActions(List<ListGridAction> rowActions) {
this.rowActions = rowActions;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setCanFilterAndSort(Boolean canFilterAndSort) {
this.canFilterAndSort = canFilterAndSort;
}
public AddMethodType getAddMethodType() {
return addMethodType;
}
public void setAddMethodType(AddMethodType addMethodType) {
this.addMethodType = addMethodType;
}
public String getListGridType() {
return listGridType;
}
public String getContainingEntityId() {
return containingEntityId;
}
public void setContainingEntityId(String containingEntityId) {
this.containingEntityId = containingEntityId;
}
public String getSubCollectionFieldName() {
return subCollectionFieldName;
}
public void setSubCollectionFieldName(String subCollectionFieldName) {
this.subCollectionFieldName = subCollectionFieldName;
}
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getSectionKey() {
return sectionKey;
}
public void setSectionKey(String sectionKey) {
this.sectionKey = sectionKey;
}
public String getExternalEntitySectionKey() {
return externalEntitySectionKey;
}
public void setExternalEntitySectionKey(String externalEntitySectionKey) {
this.externalEntitySectionKey = externalEntitySectionKey;
}
public String getPathOverride() {
return pathOverride;
}
public void setPathOverride(String pathOverride) {
this.pathOverride = pathOverride;
}
public void setReadOnly(Boolean readOnly) {
this.isReadOnly = readOnly;
}
public void setHideIdColumn(Boolean hideIdColumn) {
this.hideIdColumn = hideIdColumn;
}
public List<SectionCrumb> getSectionCrumbs() {
return sectionCrumbs;
}
public void setSectionCrumbs(List<SectionCrumb> sectionCrumbs) {
if (sectionCrumbs == null) {
this.sectionCrumbs.clear();
return;
}
this.sectionCrumbs = sectionCrumbs;
}
}
|
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/form/component/ListGrid.java
|
/*
* #%L
* BroadleafCommerce Open Admin Platform
* %%
* Copyright (C) 2009 - 2013 Broadleaf Commerce
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.broadleafcommerce.openadmin.web.form.component;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.CompareToBuilder;
import org.broadleafcommerce.common.presentation.client.AddMethodType;
import org.broadleafcommerce.common.util.TypedPredicate;
import org.broadleafcommerce.openadmin.dto.SectionCrumb;
import org.broadleafcommerce.openadmin.web.form.entity.Field;
public class ListGrid {
protected String className;
protected String friendlyName = null;
protected String idProperty;
protected int order;
protected Set<Field> headerFields = new TreeSet<Field>(new Comparator<Field>() {
@Override
public int compare(Field o1, Field o2) {
return new CompareToBuilder()
.append(o1.getOrder(), o2.getOrder())
.append(o1.getFriendlyName(), o2.getFriendlyName())
.append(o1.getName(), o2.getName())
.toComparison();
}
});
protected List<ListGridRecord> records = new ArrayList<ListGridRecord>();
protected List<ListGridAction> toolbarActions = new ArrayList<ListGridAction>();
// These actions will start greyed out and unable to be clicked until a specific row has been selected
protected List<ListGridAction> rowActions = new ArrayList<ListGridAction>();
protected int totalRecords;
protected int startIndex;
protected int pageSize;
protected Boolean canFilterAndSort;
protected Boolean isReadOnly;
protected Boolean hideIdColumn;
protected AddMethodType addMethodType;
protected String listGridType;
// The section url that maps to this particular list grid
protected String sectionKey;
// The list of all section keys that have been traversed to arrive at this ListGrid (including the current one), in order
// of occurrence
protected List<SectionCrumb> sectionCrumbs = new ArrayList<SectionCrumb>();
// If this list grid is a sublistgrid, meaning it is rendered as part of a different entity, these properties
// help identify the parent entity.
protected String externalEntitySectionKey;
protected String containingEntityId;
protected String subCollectionFieldName;
protected String pathOverride;
public enum Type {
MAIN,
INLINE,
INLINEMULTI,
TO_ONE,
BASIC,
ADORNED,
ADORNED_WITH_FORM,
MAP,
TRANSLATION,
ASSET
}
/* ************** */
/* CUSTOM METHODS */
/* ************** */
public String getPath() {
if (StringUtils.isNotBlank(pathOverride)) {
return pathOverride;
}
StringBuilder sb = new StringBuilder();
if (!getSectionKey().startsWith("/")) {
sb.append("/");
}
sb.append(getSectionKey());
if (getContainingEntityId() != null) {
sb.append("/").append(getContainingEntityId());
}
if (StringUtils.isNotBlank(getSubCollectionFieldName())) {
sb.append("/").append(getSubCollectionFieldName());
}
//to-one grids need a slightly different grid URL; these need to be appended with 'select'
//TODO: surely there's a better way to do this besides just hardcoding the 'select'?
if (Type.TO_ONE.toString().toLowerCase().equals(listGridType)) {
sb.append("/select");
}
return sb.toString();
}
public String getSectionCrumbRepresentation() {
StringBuilder sb = new StringBuilder();
if (!sectionCrumbs.isEmpty()) {
sb.append("?sectionCrumbs=");
}
int index = 0;
for (SectionCrumb section : sectionCrumbs) {
sb.append(section.getSectionIdentifier());
sb.append("--");
sb.append(section.getSectionId());
if (index < sectionCrumbs.size()-1) {
sb.append(",");
}
index++;
}
return sb.toString();
}
/**
* Grabs a filtered list of toolbar actions filtered by whether or not they match the same readonly state as the listgrid
* and are thus shown on the screen
*/
@SuppressWarnings("unchecked")
public List<ListGridAction> getActiveToolbarActions() {
return (List<ListGridAction>) CollectionUtils.select(getToolbarActions(), new TypedPredicate<ListGridAction>() {
@Override
public boolean eval(ListGridAction action) {
return action.getForListGridReadOnly().equals(getReadOnly());
}
});
}
/**
* Grabs a filtered list of row actions filtered by whether or not they match the same readonly state as the listgrid
* and are thus shown on the screen
*/
@SuppressWarnings("unchecked")
public List<ListGridAction> getActiveRowActions() {
return (List<ListGridAction>) CollectionUtils.select(getRowActions(), new TypedPredicate<ListGridAction>() {
@Override
public boolean eval(ListGridAction action) {
return action.getForListGridReadOnly().equals(getReadOnly());
}
});
}
public void addRowAction(ListGridAction action) {
getRowActions().add(action);
}
public void addToolbarAction(ListGridAction action) {
getToolbarActions().add(action);
}
public void removeAllToolbarActions() {
getToolbarActions().clear();
}
public void removeAllRowActions() {
getRowActions().clear();
}
public ListGridAction findToolbarAction(String actionId) {
for (ListGridAction action : getToolbarActions()) {
if (action.getActionId().equals(actionId)) {
return action;
}
}
return null;
}
public ListGridAction findRowAction(String actionId) {
for (ListGridAction action : getRowActions()) {
if (action.getActionId().equals(actionId)) {
return action;
}
}
return null;
}
/**
* This grid is sortable if there is a reorder action defined in the toolbar. If records can be reordered, then the
* sort functionality doesn't make any sense.
*
* Also, map structures are currently unsortable.
*
* @return
*/
public boolean isSortable() {
return getToolbarActions().contains(DefaultListGridActions.REORDER) ||
Type.MAP.toString().toLowerCase().equals(getListGridType());
}
/* ************************ */
/* CUSTOM GETTERS / SETTERS */
/* ************************ */
public void setListGridType(Type listGridType) {
this.listGridType = listGridType.toString().toLowerCase();
}
public Boolean getCanFilterAndSort() {
return (canFilterAndSort == null ? true : canFilterAndSort);
}
public Boolean getReadOnly() {
return isReadOnly == null ? false : isReadOnly;
}
public Boolean getClickable() {
return !"main".equals(listGridType);
}
public Boolean getHideIdColumn() {
return hideIdColumn == null ? false : hideIdColumn;
}
/* ************************** */
/* STANDARD GETTERS / SETTERS */
/* ************************** */
public String getIdProperty() {
return idProperty;
}
public void setIdProperty(String idProperty) {
this.idProperty = idProperty;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Set<Field> getHeaderFields() {
return headerFields;
}
public void setHeaderFields(Set<Field> headerFields) {
this.headerFields = headerFields;
}
public List<ListGridRecord> getRecords() {
return records;
}
public void setRecords(List<ListGridRecord> records) {
this.records = records;
}
public List<ListGridAction> getToolbarActions() {
return toolbarActions;
}
public void setToolbarActions(List<ListGridAction> toolbarActions) {
this.toolbarActions = toolbarActions;
}
public List<ListGridAction> getRowActions() {
return rowActions;
}
public void setRowActions(List<ListGridAction> rowActions) {
this.rowActions = rowActions;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getTotalRecords() {
return totalRecords;
}
public void setTotalRecords(int totalRecords) {
this.totalRecords = totalRecords;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setCanFilterAndSort(Boolean canFilterAndSort) {
this.canFilterAndSort = canFilterAndSort;
}
public AddMethodType getAddMethodType() {
return addMethodType;
}
public void setAddMethodType(AddMethodType addMethodType) {
this.addMethodType = addMethodType;
}
public String getListGridType() {
return listGridType;
}
public String getContainingEntityId() {
return containingEntityId;
}
public void setContainingEntityId(String containingEntityId) {
this.containingEntityId = containingEntityId;
}
public String getSubCollectionFieldName() {
return subCollectionFieldName;
}
public void setSubCollectionFieldName(String subCollectionFieldName) {
this.subCollectionFieldName = subCollectionFieldName;
}
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getSectionKey() {
return sectionKey;
}
public void setSectionKey(String sectionKey) {
this.sectionKey = sectionKey;
}
public String getExternalEntitySectionKey() {
return externalEntitySectionKey;
}
public void setExternalEntitySectionKey(String externalEntitySectionKey) {
this.externalEntitySectionKey = externalEntitySectionKey;
}
public String getPathOverride() {
return pathOverride;
}
public void setPathOverride(String pathOverride) {
this.pathOverride = pathOverride;
}
public void setReadOnly(Boolean readOnly) {
this.isReadOnly = readOnly;
}
public void setHideIdColumn(Boolean hideIdColumn) {
this.hideIdColumn = hideIdColumn;
}
public List<SectionCrumb> getSectionCrumbs() {
return sectionCrumbs;
}
public void setSectionCrumbs(List<SectionCrumb> sectionCrumbs) {
if (sectionCrumbs == null) {
this.sectionCrumbs.clear();
return;
}
this.sectionCrumbs = sectionCrumbs;
}
}
|
#801 - Allow a complete list grid type override
|
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/form/component/ListGrid.java
|
#801 - Allow a complete list grid type override
|
|
Java
|
apache-2.0
|
c77ba072065654f055c190975b8dc3046006375a
| 0
|
opensingular/singular-server,opensingular/singular-server,opensingular/singular-server
|
/*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.server.p.commons.admin.healthsystem.stypes;
import org.opensingular.form.SIComposite;
import org.opensingular.form.SInfoType;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.STypeList;
import org.opensingular.form.TypeBuilder;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.view.SViewListByTable;
import org.opensingular.server.p.commons.admin.healthsystem.validation.webchecker.IProtocolChecker;
import org.opensingular.server.p.commons.admin.healthsystem.validation.webchecker.ProtocolCheckerFactory;
import java.util.Arrays;
@SInfoType(spackage = SSystemHealthPackage.class, newable = true, name = SWebHealth.TYPE_NAME)
public class SWebHealth extends STypeComposite<SIComposite> {
public static final String TYPE_NAME = "webhealth";
public static final String TYPE_FULL_NAME = SSystemHealthPackage.PACKAGE_NAME+"."+TYPE_NAME;
@Override
protected void onLoadType(TypeBuilder tb) {
STypeList<STypeComposite<SIComposite>, SIComposite> urlsList = this.addFieldListOfComposite("urls", "urlsList");
urlsList.setView(()->new SViewListByTable());
this
.asAtr()
.label("Url (Protocolos suportados: " +
Arrays.asList(ProtocolCheckerFactory.values()).toString().replace("[", "").replace("]", "")
+ ")");
STypeComposite<SIComposite> tabela = urlsList.getElementsType();
STypeString urlField = tabela.addFieldString("url");
urlField
.asAtr()
.maxLength(100)
.asAtrBootstrap()
.colPreference(3);
urlField.addInstanceValidator(validatable->{
try {
IProtocolChecker protocolChecker = ProtocolCheckerFactory.getProtocolChecker(validatable.getInstance().getValue());
protocolChecker.protocolCheck(validatable);
} catch (Exception e) {
getLogger().error(e.getMessage(), e);
validatable.error(e.getMessage());
}
});
}
}
|
server-libs/server-commons/src/main/java/org/opensingular/server/p/commons/admin/healthsystem/stypes/SWebHealth.java
|
/*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.server.p.commons.admin.healthsystem.stypes;
import org.opensingular.form.SIComposite;
import org.opensingular.form.SInfoType;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.STypeList;
import org.opensingular.form.TypeBuilder;
import org.opensingular.form.type.core.STypeString;
import org.opensingular.form.view.SViewListByTable;
import org.opensingular.server.p.commons.admin.healthsystem.validation.webchecker.IProtocolChecker;
import org.opensingular.server.p.commons.admin.healthsystem.validation.webchecker.ProtocolCheckerFactory;
import java.util.Arrays;
@SInfoType(spackage = SSystemHealthPackage.class, newable = true, name = SWebHealth.TYPE_NAME)
public class SWebHealth extends STypeComposite<SIComposite> {
public static final String TYPE_NAME = "webhealth";
public static final String TYPE_FULL_NAME = SSystemHealthPackage.PACKAGE_NAME+"."+TYPE_NAME;
@Override
protected void onLoadType(TypeBuilder tb) {
STypeList<STypeComposite<SIComposite>, SIComposite> urlsList = this.addFieldListOfComposite("urls", "urlsList");
urlsList.setView(()->new SViewListByTable());
this
.asAtr()
.label("Url (Protocolos suportados: " +
Arrays.asList(ProtocolCheckerFactory.values()).toString().replace("[", "").replace("]", "")
+ ")");
STypeComposite<SIComposite> tabela = urlsList.getElementsType();
STypeString urlField = tabela.addFieldString("url");
urlField
.asAtr()
.maxLength(100)
.asAtrBootstrap()
.colPreference(3);
urlField.addInstanceValidator(validatable->{
try {
IProtocolChecker protocolChecker = ProtocolCheckerFactory.getProtocolChecker(validatable.getInstance().getValue());
protocolChecker.protocolCheck(validatable);
} catch (Exception e) {
validatable.error(e.getMessage());
}
});
}
}
|
correção do log da exceção
|
server-libs/server-commons/src/main/java/org/opensingular/server/p/commons/admin/healthsystem/stypes/SWebHealth.java
|
correção do log da exceção
|
|
Java
|
apache-2.0
|
b0670c3abf7c6dcc3830137e110f89cad4718cfc
| 0
|
jvalkeal/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,markpollack/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,mminella/spring-cloud-data,jvalkeal/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,spring-cloud/spring-cloud-data,jvalkeal/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,mminella/spring-cloud-data,ilayaperumalg/spring-cloud-dataflow,ilayaperumalg/spring-cloud-dataflow,cppwfs/spring-cloud-dataflow,ghillert/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,markfisher/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,markpollack/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,ghillert/spring-cloud-dataflow,markfisher/spring-cloud-data,ilayaperumalg/spring-cloud-dataflow,markfisher/spring-cloud-data,spring-cloud/spring-cloud-dataflow,jvalkeal/spring-cloud-dataflow,jvalkeal/spring-cloud-data,jvalkeal/spring-cloud-data,markpollack/spring-cloud-dataflow,cppwfs/spring-cloud-dataflow,markfisher/spring-cloud-data,cppwfs/spring-cloud-dataflow,trisberg/spring-cloud-dataflow,spring-cloud/spring-cloud-data,trisberg/spring-cloud-dataflow,spring-cloud/spring-cloud-data,jvalkeal/spring-cloud-data,spring-cloud/spring-cloud-dataflow,spring-cloud/spring-cloud-dataflow
|
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.server.local;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.springframework.analytics.metrics.FieldValueCounterRepository;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.dataflow.registry.AppRegistry;
import org.springframework.cloud.dataflow.server.config.features.FeaturesProperties;
import org.springframework.cloud.dataflow.server.local.dataflowapp.LocalTestDataFlowServer;
import org.springframework.cloud.dataflow.server.local.nodataflowapp.LocalTestNoDataFlowServer;
import org.springframework.cloud.dataflow.server.repository.DeploymentIdRepository;
import org.springframework.cloud.dataflow.server.repository.StreamDefinitionRepository;
import org.springframework.cloud.dataflow.server.repository.TaskDefinitionRepository;
import org.springframework.cloud.deployer.resource.support.DelegatingResourceLoader;
import org.springframework.cloud.deployer.resource.support.LRUCleaningResourceLoader;
import org.springframework.cloud.deployer.spi.local.LocalAppDeployer;
import org.springframework.cloud.deployer.spi.local.LocalTaskLauncher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.SocketUtils;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Tests for {@link LocalTestDataFlowServer}.
*
* @author Janne Valkealahti
* @author Eric Bottard
* @author Mark Fisher
* @author Ilayaperumal Gopinathan
*/
public class LocalConfigurationTests {
private static final String APP_DEPLOYER_BEAN_NAME = "appDeployer";
private static final String TASK_LAUNCHER_BEAN_NAME = "taskLauncher";
private ConfigurableApplicationContext context;
@After
public void tearDown() {
context.close();
}
@Test
public void testConfig() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
int randomPort = SocketUtils.findAvailableTcpPort();
String dataSourceUrl = String.format("jdbc:h2:tcp://localhost:%s/mem:dataflow", randomPort);
context = app.run(new String[] { "--server.port=0", "--spring.datasource.url=" + dataSourceUrl });
assertThat(context.containsBean(APP_DEPLOYER_BEAN_NAME), is(true));
assertThat(context.getBean(APP_DEPLOYER_BEAN_NAME), instanceOf(LocalAppDeployer.class));
assertThat(context.containsBean(TASK_LAUNCHER_BEAN_NAME), is(true));
assertThat(context.getBean(TASK_LAUNCHER_BEAN_NAME), instanceOf(LocalTaskLauncher.class));
assertNotNull(context.getBean(AppRegistry.class));
}
@Test
public void testLocalAutoConfigApplied() throws Exception {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0" });
// default on DataFlowControllerAutoConfiguration only adds maven,
// LocalDataFlowServerAutoConfiguration also adds docker so test on those.
LRUCleaningResourceLoader lruCleaningResourceLoader = context.getBean(LRUCleaningResourceLoader.class);
DelegatingResourceLoader delegatingResourceLoader =
(DelegatingResourceLoader)TestUtils.readField("delegate", lruCleaningResourceLoader);
Map<String, ResourceLoader> loaders = TestUtils.readField("loaders", delegatingResourceLoader);
assertThat(loaders.size(), is(2));
assertThat(loaders.get("maven"), notNullValue());
assertThat(loaders.get("docker"), notNullValue());
}
@Test
public void testConfigWithStreamsDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.STREAMS_ENABLED + "=false" });
assertNotNull(context.getBean(TaskDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
assertNotNull(context.getBean(FieldValueCounterRepository.class));
try {
context.getBean(StreamDefinitionRepository.class);
fail("Stream features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testConfigWithTasksDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.TASKS_ENABLED + "=false" });
assertNotNull(context.getBean(StreamDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
assertNotNull(context.getBean(FieldValueCounterRepository.class));
try {
context.getBean(TaskDefinitionRepository.class);
fail("Task features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testConfigWithAnalyticsDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.ANALYTICS_ENABLED + "=false" });
;
assertNotNull(context.getBean(StreamDefinitionRepository.class));
assertNotNull(context.getBean(TaskDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
try {
context.getBean(FieldValueCounterRepository.class);
fail("Task features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testNoDataflowConfig() {
SpringApplication app = new SpringApplication(LocalTestNoDataFlowServer.class);
context = app.run(new String[] { "--server.port=0" });
// we still have deployer beans
assertThat(context.containsBean(APP_DEPLOYER_BEAN_NAME), is(true));
assertThat(context.containsBean(TASK_LAUNCHER_BEAN_NAME), is(true));
assertThat(context.containsBean("appRegistry"), is(false));
}
}
|
spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/LocalConfigurationTests.java
|
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.dataflow.server.local;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
import org.springframework.analytics.metrics.FieldValueCounterRepository;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.dataflow.registry.AppRegistry;
import org.springframework.cloud.dataflow.server.config.features.FeaturesProperties;
import org.springframework.cloud.dataflow.server.local.dataflowapp.LocalTestDataFlowServer;
import org.springframework.cloud.dataflow.server.local.nodataflowapp.LocalTestNoDataFlowServer;
import org.springframework.cloud.dataflow.server.repository.DeploymentIdRepository;
import org.springframework.cloud.dataflow.server.repository.StreamDefinitionRepository;
import org.springframework.cloud.dataflow.server.repository.TaskDefinitionRepository;
import org.springframework.cloud.deployer.resource.support.DelegatingResourceLoader;
import org.springframework.cloud.deployer.spi.local.LocalAppDeployer;
import org.springframework.cloud.deployer.spi.local.LocalTaskLauncher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.SocketUtils;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Tests for {@link LocalTestDataFlowServer}.
*
* @author Janne Valkealahti
* @author Eric Bottard
* @author Mark Fisher
* @author Ilayaperumal Gopinathan
*/
public class LocalConfigurationTests {
private static final String APP_DEPLOYER_BEAN_NAME = "appDeployer";
private static final String TASK_LAUNCHER_BEAN_NAME = "taskLauncher";
private ConfigurableApplicationContext context;
@After
public void tearDown() {
context.close();
}
@Test
public void testConfig() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
int randomPort = SocketUtils.findAvailableTcpPort();
String dataSourceUrl = String.format("jdbc:h2:tcp://localhost:%s/mem:dataflow", randomPort);
context = app.run(new String[] { "--server.port=0", "--spring.datasource.url=" + dataSourceUrl });
assertThat(context.containsBean(APP_DEPLOYER_BEAN_NAME), is(true));
assertThat(context.getBean(APP_DEPLOYER_BEAN_NAME), instanceOf(LocalAppDeployer.class));
assertThat(context.containsBean(TASK_LAUNCHER_BEAN_NAME), is(true));
assertThat(context.getBean(TASK_LAUNCHER_BEAN_NAME), instanceOf(LocalTaskLauncher.class));
assertNotNull(context.getBean(AppRegistry.class));
}
@Test
public void testLocalAutoConfigApplied() throws Exception {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0" });
// default on DataFlowControllerAutoConfiguration only adds maven,
// LocalDataFlowServerAutoConfiguration also adds docker so test on those.
DelegatingResourceLoader delegatingResourceLoader = context.getBean(DelegatingResourceLoader.class);
Map<String, ResourceLoader> loaders = TestUtils.readField("loaders", delegatingResourceLoader);
assertThat(loaders.size(), is(2));
assertThat(loaders.get("maven"), notNullValue());
assertThat(loaders.get("docker"), notNullValue());
}
@Test
public void testConfigWithStreamsDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.STREAMS_ENABLED + "=false" });
assertNotNull(context.getBean(TaskDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
assertNotNull(context.getBean(FieldValueCounterRepository.class));
try {
context.getBean(StreamDefinitionRepository.class);
fail("Stream features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testConfigWithTasksDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.TASKS_ENABLED + "=false" });
assertNotNull(context.getBean(StreamDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
assertNotNull(context.getBean(FieldValueCounterRepository.class));
try {
context.getBean(TaskDefinitionRepository.class);
fail("Task features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testConfigWithAnalyticsDisabled() {
SpringApplication app = new SpringApplication(LocalTestDataFlowServer.class);
context = app.run(new String[] { "--server.port=0",
"--" + FeaturesProperties.FEATURES_PREFIX + "." + FeaturesProperties.ANALYTICS_ENABLED + "=false" });
;
assertNotNull(context.getBean(StreamDefinitionRepository.class));
assertNotNull(context.getBean(TaskDefinitionRepository.class));
assertNotNull(context.getBean(DeploymentIdRepository.class));
try {
context.getBean(FieldValueCounterRepository.class);
fail("Task features should have been disabled.");
}
catch (NoSuchBeanDefinitionException e) {
}
}
@Test
public void testNoDataflowConfig() {
SpringApplication app = new SpringApplication(LocalTestNoDataFlowServer.class);
context = app.run(new String[] { "--server.port=0" });
// we still have deployer beans
assertThat(context.containsBean(APP_DEPLOYER_BEAN_NAME), is(true));
assertThat(context.containsBean(TASK_LAUNCHER_BEAN_NAME), is(true));
assertThat(context.containsBean("appRegistry"), is(false));
}
}
|
Fix test
|
spring-cloud-starter-dataflow-server-local/src/test/java/org/springframework/cloud/dataflow/server/local/LocalConfigurationTests.java
|
Fix test
|
|
Java
|
apache-2.0
|
fe1ebb0978e0242c3b78ff1f165d3bb291787b6d
| 0
|
osgi/osgi.iot.contest.sdk,osgi/osgi.iot.contest.sdk,osgi/osgi.iot.contest.sdk,osgi/osgi.iot.contest.sdk
|
package osgi.enroute.trains.train.manager.example.provider;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import osgi.enroute.scheduler.api.Scheduler;
import osgi.enroute.trains.cloud.api.Observation;
import osgi.enroute.trains.cloud.api.TrackForTrain;
import osgi.enroute.trains.track.util.Tracks;
import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
import osgi.enroute.trains.train.api.TrainController;
import osgi.enroute.trains.train.manager.example.provider.ExampleTrainManagerImpl.Config;
/**
* Train manager.
*/
@Designate(ocd = Config.class, factory = true)
@Component(name = Config.TRAIN_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE,
immediate = true, service = Object.class)
public class ExampleTrainManagerImpl {
@ObjectClassDefinition
@interface Config {
final static public String TRAIN_CONFIG_PID = "osgi.enroute.trains.train.manager";
String name();
String rfid();
int speed() default 50;
String TrainController_target();
}
static Logger logger = LoggerFactory.getLogger(ExampleTrainManagerImpl.class);
List<TrainController> trainControllers = new ArrayList<>();
// TrainController.target is set in config
@Reference(name = "TrainController",
cardinality = ReferenceCardinality.AT_LEAST_ONE,
policy = ReferencePolicy.DYNAMIC)
void addTrainController(TrainController trainCtrl) {
trainControllers.add(trainCtrl);
}
void removeTrainController(TrainController trainCtrl) {
trainControllers.remove(trainCtrl);
}
@Reference
private TrackForTrain trackManager;
@Reference
private Scheduler scheduler;
private Tracks<Object> tracks;
private String name;
private String rfid;
private int speed;
private int lastMove = 0;
private Thread mgmtThread;
@Activate
public void activate(Config config) throws Exception {
name = config.name();
rfid = config.rfid();
speed = config.speed();
info("activate: speed<{}> rfid<{}>", speed, rfid);
// register train with Track Manager
trackManager.registerTrain(name, rfid);
// create Track
tracks = new Tracks<Object>(trackManager.getSegments().values(), new TrainManagerFactory());
mgmtThread = new Thread(new TrainMgmtLoop());
mgmtThread.start();
}
@Deactivate
public void deactivate() {
info("deactivate");
try {
mgmtThread.interrupt();
mgmtThread.join(5000);
} catch (InterruptedException e) {
}
// stop when deactivated
stop();
}
private void move(int moveSpeed) {
if (lastMove != moveSpeed || moveSpeed == 0) {
info("move({})", moveSpeed);
lastMove = moveSpeed;
trainControllers.forEach(c -> c.move(moveSpeed));
}
}
private void stop() {
move(0);
light(false);
}
private void light(boolean on) {
trainControllers.forEach(c -> c.light(on));
}
private class TrainMgmtLoop implements Runnable {
private String currentAssignment = null;
private String currentLocation = null;
private String currentAccess = null;
private LinkedList<SegmentHandler<Object>> route = null;
private void abort() {
stop();
currentAssignment = null;
route = null;
}
@Override
public void run() {
// get observations, without blocking, to find lastObservation
// and to avoid re-processing same observations on restart
List<Observation> observations = trackManager.getRecentObservations(-2);
long lastObsId = -1;
boolean blocked = false;
if (!observations.isEmpty()) {
Observation lastObs = observations.get(observations.size() - 1);
lastObsId = lastObs.id;
info("disgard old observations: last: {}", lastObs);
}
stop();
while (isActive()) {
observations = trackManager
.getRecentObservations(lastObsId - (blocked ? 1 : 0));
if (blocked && observations.size() > 1) {
// remove the observation that caused block and process next
// otherwise re-process previous observation, which should
// drop back to followRoute()
observations.remove(0);
blocked = false;
}
for (Observation o : observations) {
lastObsId = o.id;
tracks.event(o);
if (name == null || !name.equals(o.train)) {
continue;
}
switch (o.type) {
case ASSIGNMENT:
// new assignment, plan and follow the route
info("New Assignment<{}>", o.assignment);
currentAssignment = o.assignment;
if (currentLocation == null) {
info("start moving to find location");
move(speed);
} else {
planRoute();
blocked = followRoute();
}
break;
case LOCATED:
info("Located @ {}", o.segment);
if (currentLocation == null && currentAssignment != null) {
currentLocation = o.segment;
move(0);
planRoute();
} else {
currentLocation = o.segment;
}
// stop when assignment reached
if (currentAssignment == null) {
info("Waiting for an assignment");
stop();
} else if (currentAssignment.equals(currentLocation)) {
info("Reached assignment<{}>", currentAssignment);
currentAssignment = null;
stop();
blink(3);
} else {
blocked = followRoute();
}
break;
case BLOCKED:
case CHANGE:
case SIGNAL:
case SWITCH:
case TIMEOUT:
default:
break;
}
}
}
info("management loop terminated.");
}
private void blink(int n) {
light(false);
if (n > 0) {
scheduler.after(() -> {
light(true);
scheduler.after(() -> blink(n - 1), 500);
}, 500);
}
}
private void planRoute() {
if (currentLocation == null)
return;
if (currentAssignment == null)
return;
// plan the route
SegmentHandler<Object> src = tracks.getHandler(currentLocation);
SegmentHandler<Object> dest = tracks.getHandler(currentAssignment);
route = src.findForward(dest);
}
private boolean followRoute() {
if (route == null || route.isEmpty())
return false;
light(true);
Optional<SegmentHandler<Object>> mySegment = route.stream()
.filter(sh -> sh.segment.id.equals(currentLocation))
.findFirst();
if (!mySegment.isPresent()) {
error("location<{}> is not on route. stop.", currentLocation);
abort();
return false;
}
Optional<SegmentHandler<Object>> nextLocator;
String fromTrack;
String toTrack;
// update the remaining part of the current route
while (route.size() > 0 && !route.getFirst().segment.id.equals(currentLocation)) {
SegmentHandler<Object> removed = route.removeFirst();
if (removed.isLocator()) {
info("eek! missed locator <{}>", removed.segment.id);
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (nextLocator.isPresent()) {
fromTrack = removed.getTrack();
toTrack = nextLocator.get().getTrack();
if (!fromTrack.equals(toTrack)) {
info("retrospectively request access to <{}> from <{}>", toTrack, fromTrack);
move(0);
requestAccess(fromTrack, toTrack);
}
}
}
}
// figure out where to go to next
fromTrack = route.removeFirst().getTrack();
// check if we have to go to a new track before we have a new
// Locator
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (!nextLocator.isPresent()) {
error("no locator to go to, stop now");
abort();
return false;
}
toTrack = nextLocator.get().getTrack();
// if we have to go to other track, request access
if (!fromTrack.equals(toTrack) && !toTrack.equals(currentAccess)) {
info("stop and request access to track<{}> from <{}>", toTrack, currentLocation);
move(0);
boolean granted = false;
// simply keep on trying until access is given
while (!granted && isActive()) {
granted = requestAccess(fromTrack, toTrack);
if (!granted) {
// allow mgmt loop to process other events
// return true;
}
}
}
// just go forward
move(speed);
return false;
}
private boolean requestAccess(String fromTrack, String toTrack) {
boolean granted = false;
try {
granted = trackManager.requestAccessTo(name, fromTrack, toTrack);
} catch (Exception e) {
error("request access failed: " + e);
abort();
}
info("access is {}", granted ? "granted" : "blocked");
currentAccess = (granted ? toTrack : null);
return granted;
}
private boolean isActive() {
return !Thread.currentThread().isInterrupted();
}
}
private void info(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.out.printf(ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
}
private void error(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.err.printf("ERROR: " + ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
logger.error(ident + fmt, args);
}
}
|
osgi.enroute.trains.train.manager.example.provider/src/osgi/enroute/trains/train/manager/example/provider/ExampleTrainManagerImpl.java
|
package osgi.enroute.trains.train.manager.example.provider;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import osgi.enroute.scheduler.api.Scheduler;
import osgi.enroute.trains.cloud.api.Observation;
import osgi.enroute.trains.cloud.api.TrackForTrain;
import osgi.enroute.trains.track.util.Tracks;
import osgi.enroute.trains.track.util.Tracks.SegmentHandler;
import osgi.enroute.trains.train.api.TrainController;
import osgi.enroute.trains.train.manager.example.provider.ExampleTrainManagerImpl.Config;
/**
* Train manager.
*/
@Designate(ocd = Config.class, factory = true)
@Component(name = Config.TRAIN_CONFIG_PID, configurationPolicy = ConfigurationPolicy.REQUIRE,
immediate = true, service = Object.class)
public class ExampleTrainManagerImpl {
@ObjectClassDefinition
@interface Config {
final static public String TRAIN_CONFIG_PID = "osgi.enroute.trains.train.manager";
String name();
String rfid();
int speed() default 50;
String TrainController_target();
}
static Logger logger = LoggerFactory.getLogger(ExampleTrainManagerImpl.class);
// TrainController.target is set in config
@Reference(name = "TrainController")
private TrainController trainCtrl;
@Reference
private TrackForTrain trackManager;
@Reference
private Scheduler scheduler;
private Tracks<Object> tracks;
private String name;
private String rfid;
private int speed;
private int lastMove = 0;
private Thread mgmtThread;
@Activate
public void activate(Config config) throws Exception {
name = config.name();
rfid = config.rfid();
speed = config.speed();
info("activate: speed<{}> rfid<{}>", speed, rfid);
// register train with Track Manager
trackManager.registerTrain(name, rfid);
// create Track
tracks = new Tracks<Object>(trackManager.getSegments().values(), new TrainManagerFactory());
mgmtThread = new Thread(new TrainMgmtLoop());
mgmtThread.start();
}
@Deactivate
public void deactivate() {
info("deactivate");
try {
mgmtThread.interrupt();
mgmtThread.join(5000);
} catch (InterruptedException e) {
}
// stop when deactivated
stop();
}
private void move(int moveSpeed) {
if (lastMove != moveSpeed || moveSpeed == 0) {
info("move({})", moveSpeed);
lastMove = moveSpeed;
trainCtrl.move(moveSpeed);
}
}
private void stop() {
move(0);
trainCtrl.light(false);
}
private class TrainMgmtLoop implements Runnable {
private String currentAssignment = null;
private String currentLocation = null;
private String currentAccess = null;
private LinkedList<SegmentHandler<Object>> route = null;
private void abort() {
trainCtrl.move(0);
trainCtrl.light(false);
currentAssignment = null;
route = null;
}
@Override
public void run() {
// get observations, without blocking, to find lastObservation
// and to avoid re-processing same observations on restart
List<Observation> observations = trackManager.getRecentObservations(-2);
long lastObsId = -1;
boolean blocked = false;
if (!observations.isEmpty()) {
Observation lastObs = observations.get(observations.size() - 1);
lastObsId = lastObs.id;
info("disgard old observations: last: {}", lastObs);
}
stop();
while (isActive()) {
observations = trackManager
.getRecentObservations(lastObsId - (blocked ? 1 : 0));
if (blocked && observations.size() > 1) {
// remove the observation that caused block and process next
// otherwise re-process previous observation, which should
// drop back to followRoute()
observations.remove(0);
blocked = false;
}
for (Observation o : observations) {
lastObsId = o.id;
tracks.event(o);
if (name == null || !name.equals(o.train)) {
continue;
}
switch (o.type) {
case ASSIGNMENT:
// new assignment, plan and follow the route
info("New Assignment<{}>", o.assignment);
currentAssignment = o.assignment;
if (currentLocation == null) {
info("start moving to find location");
move(speed);
} else {
planRoute();
blocked = followRoute();
}
break;
case LOCATED:
info("Located @ {}", o.segment);
if (currentLocation == null && currentAssignment != null) {
currentLocation = o.segment;
move(0);
planRoute();
} else {
currentLocation = o.segment;
}
// stop when assignment reached
if (currentAssignment == null) {
info("Waiting for an assignment");
stop();
} else if (currentAssignment.equals(currentLocation)) {
info("Reached assignment<{}>", currentAssignment);
currentAssignment = null;
stop();
blink(3);
} else {
blocked = followRoute();
}
break;
case BLOCKED:
case CHANGE:
case SIGNAL:
case SWITCH:
case TIMEOUT:
default:
break;
}
}
}
info("management loop terminated.");
}
private void blink(int n) {
trainCtrl.light(false);
if (n > 0) {
scheduler.after(() -> {
trainCtrl.light(true);
scheduler.after(() -> blink(n - 1), 500);
}, 500);
}
}
private void planRoute() {
if (currentLocation == null)
return;
if (currentAssignment == null)
return;
// plan the route
SegmentHandler<Object> src = tracks.getHandler(currentLocation);
SegmentHandler<Object> dest = tracks.getHandler(currentAssignment);
route = src.findForward(dest);
}
private boolean followRoute() {
if (route == null || route.isEmpty())
return false;
trainCtrl.light(true);
Optional<SegmentHandler<Object>> mySegment = route.stream()
.filter(sh -> sh.segment.id.equals(currentLocation))
.findFirst();
if (!mySegment.isPresent()) {
error("location<{}> is not on route. stop.", currentLocation);
abort();
return false;
}
Optional<SegmentHandler<Object>> nextLocator;
String fromTrack;
String toTrack;
// update the remaining part of the current route
while (route.size() > 0 && !route.getFirst().segment.id.equals(currentLocation)) {
SegmentHandler<Object> removed = route.removeFirst();
if (removed.isLocator()) {
info("eek! missed locator <{}>", removed.segment.id);
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (nextLocator.isPresent()) {
fromTrack = removed.getTrack();
toTrack = nextLocator.get().getTrack();
if (!fromTrack.equals(toTrack)) {
info("retrospectively request access to <{}> from <{}>", toTrack, fromTrack);
move(0);
requestAccess(fromTrack, toTrack);
}
}
}
}
// figure out where to go to next
fromTrack = route.removeFirst().getTrack();
// check if we have to go to a new track before we have a new
// Locator
nextLocator = route.stream().filter(sh -> sh.isLocator()).findFirst();
if (!nextLocator.isPresent()) {
error("no locator to go to, stop now");
abort();
return false;
}
toTrack = nextLocator.get().getTrack();
// if we have to go to other track, request access
if (!fromTrack.equals(toTrack) && !toTrack.equals(currentAccess)) {
info("stop and request access to track<{}> from <{}>", toTrack, currentLocation);
move(0);
boolean granted = false;
// simply keep on trying until access is given
while (!granted && isActive()) {
granted = requestAccess(fromTrack, toTrack);
if (!granted) {
// allow mgmt loop to process other events
// return true;
}
}
}
// just go forward
move(speed);
return false;
}
private boolean requestAccess(String fromTrack, String toTrack) {
boolean granted = false;
try {
granted = trackManager.requestAccessTo(name, fromTrack, toTrack);
} catch (Exception e) {
error("request access failed: " + e);
abort();
}
info("access is {}", granted ? "granted" : "blocked");
currentAccess = (granted ? toTrack : null);
return granted;
}
private boolean isActive() {
return !Thread.currentThread().isInterrupted();
}
}
private void info(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.out.printf(ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
}
private void error(String fmt, Object... args) {
String ident = String.format("Train<%s>: ", name);
System.err.printf("ERROR: " + ident + fmt.replaceAll("\\{}", "%s") + "\n", args);
logger.error(ident + fmt, args);
}
}
|
use multiple IR senders
|
osgi.enroute.trains.train.manager.example.provider/src/osgi/enroute/trains/train/manager/example/provider/ExampleTrainManagerImpl.java
|
use multiple IR senders
|
|
Java
|
apache-2.0
|
230fd67b549a457d7f0d490333cfd566712f351a
| 0
|
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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.
*/
package com.sandwell.JavaSimulation3D;
import java.awt.FileDialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JOptionPane;
import com.sandwell.JavaSimulation.*;
import com.sandwell.JavaSimulation.Package;
public class InputAgent {
private static final String addedRecordMarker = "\" *** Added Records ***";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static String configFileName;
private static boolean batchRun;
private static boolean sessionEdited;
private static boolean addedRecordFound;
private static boolean endOfFileReached; // notes end of cfg files
// ConfigurationFile load and save variables
final protected static int SAVE_ONLY = 2;
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static String reportDirectory;
static {
addedRecordFound = false;
sessionEdited = false;
endOfFileReached = false;
batchRun = false;
configFileName = "Simulation1.cfg";
reportDirectory = "";
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
addedRecordFound = false;
sessionEdited = false;
configFileName = "Simulation1.cfg";
reportDirectory = "";
}
public static String getReportDirectory() {
return reportDirectory;
}
public static void setReportDirectory(String dir) {
reportDirectory = Util.getAbsoluteFilePath(dir);
if (reportDirectory.substring(reportDirectory.length() - 1) != "\\")
reportDirectory = reportDirectory + "\\";
// Create the report directory if it does not already exist
// This code should probably be added to FileEntity someday to
// create necessary folders on demand.
File f = new File(reportDirectory);
f.mkdirs();
}
public static void setConfigFileName(String name) {
configFileName = name;
}
public static String getConfigFileName() {
return configFileName;
}
public static String getRunName() {
int index = Util.fileShortName( InputAgent.getConfigFileName() ).indexOf( "." );
String runName;
if( index > -1 ) {
runName = Util.fileShortName( InputAgent.getConfigFileName() ).substring( 0, index );
}
else {
runName = Util.fileShortName( InputAgent.getConfigFileName() );
}
return runName;
}
public static boolean hasAddedRecords() {
return addedRecordFound;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
/**
* Break the record into individual tokens and append it to the token list
*/
public static void tokenizeString(ArrayList<String> tokens, String record) {
// Split the record into two pieces, the contents portion and possibly
// a commented portion
String[] contents = record.split("\"", 2);
// Split the contents along single-quoted substring boundaries to allow
// us to parse quoted and unquoted sections separately
String[] substring = contents[0].split("'", -1);
for (int i = 0; i < substring.length; i++) {
// Odd indices were single-quoted strings in the original record
// restore the quotes and append the whole string as a single token
// even if there was nothing between the quotes (an empty string)
if (i % 2 != 0) {
tokens.add(String.format("'%s'", substring[i]));
continue;
}
// The even-index strings need tokenizing, we allow spaces, tabs and
// commas to delimit token boundaries, we also want all braces {} to
// appear as a single token
// Ensure { or } has tabs separating if from adjacent characters
String temp = substring[i].replaceAll("([\\{\\}])", "\t$1\t");
// Split along space, comma and tab characters, treat consecutive
// characters as one delimiter
String[] delimTokens = temp.split("[ ,\t]+", 0);
// Append the new tokens that have greater than zero length
for (String each : delimTokens) {
if (each.length() > 0)
tokens.add(each);
}
}
// add any comments if they exist with a leading " prepended to denote it
// as commented
if (contents.length == 2)
tokens.add(String.format("\"%s", contents[1]));
}
/**
* returns true if the first and last tokens are matched braces
**/
public static boolean enclosedByBraces(ArrayList<String> tokens) {
if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces
return false;
int level =1;
int i = 1;
for(String each: tokens.subList(1, tokens.size())) {
if(each.equals("{")) {
level++;
}
if(each.equals("}")) {
level--;
// Matching close brace found
if(level == 0)
break;
}
i++;
}
if(level == 0 && i == tokens.size()-1) {
return true;
}
return false;
}
private static boolean isRecordComplete(ArrayList<String> tokens) {
int braceDepth = 0;
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth--;
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
return false;
}
if (braceDepth > 2) {
InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded");
tokens.clear();
return false;
}
}
if (braceDepth == 0)
return true;
else
return false;
}
public static void readURL(URL url) {
if (url == null)
return;
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logWarning("Could not read from %s", url.toString());
return;
}
try {
ArrayList<String> record = new ArrayList<String>();
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
// Set flag if found " *** Added Records ***
if ( line.trim().equalsIgnoreCase( addedRecordMarker ) ) {
addedRecordFound = true;
}
InputAgent.tokenizeString(record, line);
if (!InputAgent.isRecordComplete(record))
continue;
InputAgent.processRecord(url, record);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
}
private static void removeComments(ArrayList<String> record) {
for (int i = record.size() - 1; i >= 0; i--) {
// remove parts of the input that were commented out
if (record.get(i).startsWith("\"")) {
record.remove(i);
continue;
}
// strip single-quoted strings when passing through to the parsers
if (record.get(i).startsWith("'")) {
String noQuotes = record.get(i).substring(1, record.get(i).length() - 1);
record.set(i, noQuotes);
}
}
}
private static void processRecord(URL url, ArrayList<String> record) {
//InputAgent.echoInputRecord(record);
InputAgent.removeComments(record);
if (record.size() == 0)
return;
if (record.get(0).equalsIgnoreCase("INCLUDE")) {
InputAgent.processIncludeRecord(url, record);
return;
}
if (record.get(0).equalsIgnoreCase("DEFINE")) {
InputAgent.processDefineRecord(record);
return;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record);
}
private static void processIncludeRecord(URL baseURL, ArrayList<String> record) {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
// Ensure the include filename is well formed
URL finalURL = null;
try {
URI incFile = new URI(record.get(1).replaceAll("\\\\", "/"));
// Construct a base file in case this URI is relative and split at ! to
// account for a jar:file:<jarfilename>!<internalfilename> URL
int bangIndex = baseURL.toString().lastIndexOf("!") + 1;
String prefix = baseURL.toString().substring(0, bangIndex);
String folder = baseURL.toString().substring(bangIndex);
URI folderURI = new URI(folder).resolve(incFile);
// Remove all remaining relative path directives ../
String noRelative = folderURI.toString().replaceAll("\\.\\./", "");
finalURL = new URL(prefix + noRelative);
}
catch (NullPointerException e) {}
catch (URISyntaxException e) {}
catch (MalformedURLException e) {}
finally {
if (finalURL == null) {
InputAgent.logError("Unable to parse filename: %s", record.get(1));
return;
}
}
InputAgent.readURL(finalURL);
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "Package" ) ) {
proto = Package.class;
}
else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), false);
}
}
/**
* if userDefined is true then this is an entity defined by user interaction;
* otherwise, it is from an input file define statement
* @param proto
* @param key
* @param userDefined
*/
public static Entity defineEntity(Class<? extends Entity> proto, String key, boolean userDefined) {
Region region = null;
String name = key;
Entity ent = Input.tryParseEntity(key, Entity.class);
if (ent != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, name, ent.getClass().getSimpleName());
return null;
}
if (key.contains("/")) {
String regionName = key.substring(0, key.indexOf("/"));
name = key.substring(key.indexOf("/") + 1);
Entity check = Input.tryParseEntity(regionName, Entity.class);
if (check == null) {
InputAgent.logError("%s not found, could not define: %s", regionName, name);
return null;
}
if (check instanceof Region)
region = (Region)check;
else
name = key;
}
ent = null;
try {
ent = proto.newInstance();
if (hasAddedRecords() || userDefined) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setName(name);
ent.setInputName(key);
if (region != null)
ent.setRegion( region );
ent.defineNewEntity();
return ent;
}
private static void processKeywordRecord(ArrayList<String> record) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
ArrayList<ArrayList<String>> keywords = InputAgent.splitKeywords(record);
for (ArrayList<String> keyword : keywords) {
if (keyword.size() < 3 ||
!keyword.get(1).equals("{") ||
!keyword.get(keyword.size() - 1).equals("}")) {
InputAgent.logError("Keyword not valid, should be <keyword> { <args> }");
continue;
}
String key = keyword.get(0);
StringVector args = new StringVector(keyword.size() - 3);
for (int i = 2; i < keyword.size() - 1; i++) {
args.add(keyword.get(i));
}
try {
InputAgent.processKeyword(ent, args, key);
}
catch (Throwable e) {
InputAgent.logError("Exception thrown from Entity: %s for keyword:%s - %s", ent.getInputName(), key, e.getMessage());
}
}
}
private static ArrayList<ArrayList<String>> splitKeywords(ArrayList<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 1; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<String>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth--;
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
System.out.println("An error occurred in the simulation environment. Please check inputs for an error:");
System.out.println(e);
System.exit(1);
}
public static void loadConfigFile(String fileName) {
try {
DisplayEntity.simulation.getGUIFrame().updateForSimulationState();
InputAgent.loadConfigurationFile(fileName);
GraphicsUpdateBehavior.forceUpdate = true;
}
catch( InputErrorException iee ) {
if (!batchRun) {
javax.swing.JOptionPane.showMessageDialog( null, iee.getMessage(), "Input Error", javax.swing.JOptionPane.ERROR_MESSAGE );
}
else {
System.out.println( iee.getMessage() );
}
return;
}
}
// Load the run file
public static void loadConfigurationFile( String fileName) {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
// Set and open the input trace file name
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
catch( Exception e ) {
throw new ErrorException( "Could not create trace file" );
}
InputAgent.loadConfigurationFile(fileName, true);
// At this point configuration file is loaded
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors found, check log file", InputAgent.numErrors);
// print inputKeywordfile
if( DisplayEntity.simulation.getPrintInputReport() ) {
InputAgent.printInputFileKeywords();
}
}
/**
*
* @param fileName
* @param firstTime ( true => this is the main config file (run file); false => this is an included file within main config file or another included file )
*/
public static void loadConfigurationFile( String fileName, boolean firstTime ) {
//System.out.println( "load configuration file " + fileName );
FileEntity file;
Vector record;
// If the file does not exist, write an error and exit
if( !FileEntity.fileExists( fileName ) ) {
System.out.println( (("Error -- The input file " + fileName) + " was not found ") );
System.exit( 0 );
}
// Open the file
file = new FileEntity( fileName, FileEntity.FILE_READ, false );
String mainRootDirectory = null;
String originalJarFileRootDirectory = null;
if( firstTime ) {
// Store the directory of the first input file
file.setRootDirectory();
}
else {
// Save the directory of the first file
mainRootDirectory = FileEntity.getRootDirectory();
// Switch to the directory of the current input file
file.setRootDirectory();
// Save the directory of the first file within the jar file
originalJarFileRootDirectory = FileEntity.getJarFileRootDirectory();
try {
// Determine the url of the file from the jar file com/sandwell/JavaSimulation directory
String relativeURL = FileEntity.getRelativeURL( fileName );
// Is the file is inside the jar file?
if (Simulation.class.getResource(relativeURL) != null) {
// Set the directory of the file inside the jar file relative to com/sandwell/JavaSimulation directory
int lastIndex = relativeURL.lastIndexOf( '/' );
String jarFileRootDirectory = relativeURL.substring( 0, lastIndex ).replace( "/", "\\" );
FileEntity.setJarFileRootDirectory( jarFileRootDirectory );
}
}
catch( Exception e ) {
throw new ErrorException( "Could not open " + fileName );
}
}
// Initialize the input file
file.toStart();
DisplayEntity.simulation.setProgressText( file.getFileName() );
// For each line in the file
while( true ) {
// Read the next line to record
record = getNextParsedRecord( file );
// System.out.println( record.toString() );
// Determine the amount of file read and update the progress gauge
int per = (int)(((double)file.getNumRead()) / ((double)file.getLength()) * 100.0);
DisplayEntity.simulation.setProgress( per );
// When end-of-file is reached, record.size() == 0
if( endOfFileReached ) {
break;
}
// Process this line if it is not empty
if ( record.size() > 0 ) {
// If there is an included file, LoadConfigurationFile is run for that (This is recursive)
InputAgent.readRecord(record, file);
}
}
// Reset the progress bar to zero and remove its label
DisplayEntity.simulation.setProgressText( null );
DisplayEntity.simulation.setProgress( 0 );
// Close the file
file.close();
// Restore to the directory of the first input file
if ( ! firstTime ) {
FileEntity.setRootDirectory( mainRootDirectory );
FileEntity.setJarFileRootDirectory( originalJarFileRootDirectory );
}
}
/**
* Reads record, either as a default, define statement, include, or keyword
* @param record
* @param file
*/
private static void readRecord(Vector record, FileEntity file) {
if(record.size() < 2){
InputAgent.logError("Invalid input line - missing keyword or parameter");
return;
}
try {
if( "DEFINE".equalsIgnoreCase( (String)record.get( 0 ) ) ) {
ArrayList<String> tempCopy = new ArrayList<String>(record.size());
for (int i = 0; i < record.size(); i++)
tempCopy.add((String)record.get(i));
InputAgent.processDefineRecord(tempCopy);
}
// Process other files
else if( "INCLUDE".equalsIgnoreCase( (String)record.get( 0 ) ) ) {
if( record.size() == 2 ) {
if( FileEntity.fileExists( (String)record.get( 1 ) ) ) {
// Load the included file and process its records first
InputAgent.loadConfigurationFile( (String)record.get( 1 ), false );
DisplayEntity.simulation.setProgressText( file.getFileName() );
}
else {
InputAgent.logError("File not found: %s", (String)record.get(1));
}
}
else {
InputAgent.logError("There must be exactly two entries in an Include record");
}
}
// is a keyword
else {
InputAgent.processData(record);
}
}
catch( InputErrorException iee ) {
}
}
// Read the next line of the file
protected static Vector getNextParsedRecord(FileEntity file) {
Vector record = new Vector( 1 , 1 );
int noOfUnclosedBraces = 0;
do {
Vector nextLine = file.readAndParseRecord();
InputAgent.echoInput(nextLine);
if (nextLine.size() == 0) {
endOfFileReached = true;
}
else {
endOfFileReached = false;
}
// Set flag if input records added through the EditBox interface are found
if ( !(endOfFileReached) && ( ((String) nextLine.get( 0 )).equalsIgnoreCase( addedRecordMarker ) ) ) {
addedRecordFound = true;
}
Util.discardComment( nextLine );
// Count braces and allow input with a missing space following an opening brace and/or a missing space preceding a closing brace
for (int i = 0; i < nextLine.size(); i++) {
String checkRecord = (String)nextLine.get( i );
Vector parsedString = new Vector( 1 , 1 );
// Check for braces
for (int j=0; j<checkRecord.length(); j++) {
// '(' & ')' are not allowed in the input file
if( checkRecord.charAt(j) == '(' || checkRecord.charAt(j) == ')' ) {
throw new ErrorException( "\n\"" + checkRecord.charAt(j) + "\"" + " is not allowed in the input file: \n" + nextLine + "\n" + FileEntity.getRootDirectory() + file.getFileName() );
}
if (checkRecord.charAt(j) == '{') {
noOfUnclosedBraces++;
parsedString.add("{");
}
else if (checkRecord.charAt(j) == '}') {
noOfUnclosedBraces--;
parsedString.add("}");
} else {
// no brace is found, assume it is a whole word until the next brace
String stringDump = "";
// iterate through
for ( int k = j; k<checkRecord.length(); k++ ) {
// if a brace is found, end checking this word
if ( checkRecord.charAt(k) == '{' || checkRecord.charAt(k) == '}' ) {
k = checkRecord.length();
}
// otherwise, make the word
else {
stringDump += checkRecord.charAt(k);
}
}
j += stringDump.length() - 1;
parsedString.add(stringDump);
}
}
// Add brackets as separate entries
if (parsedString.size() > 0 ) {
nextLine.remove( i );
nextLine.addAll( i , parsedString );
i = i + parsedString.size() - 1;
}
}
record.addAll(nextLine);
} while ( ( noOfUnclosedBraces != 0 ) && ( !endOfFileReached ) );
if( noOfUnclosedBraces != 0 ) {
InputAgent.logError("Missing closing brace");
}
return record;
}
private static void processKeyword( Entity entity, StringVector recordCmd, String keyword) {
if (keyword == null)
throw new InputErrorException("The keyword is null.");
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
try {
Input<?> input = entity.getInput( keyword );
if( input != null && input.isAppendable() ) {
ArrayList<StringVector> splitData = Util.splitStringVectorByBraces(recordCmd);
for ( int i = 0; i < splitData.size(); i++ ) {
entity.readInput(splitData.get(i), keyword, false, false);
}
}
else {
entity.readInput(recordCmd, keyword, false, false);
}
// Create a list of entities to update in the edit table
Vector entityList = new Vector( 1, 1 );
if( entity instanceof Group ) {
// Is the keyword a Group keyword?
if( entity.getInput( keyword ) != null ) {
entityList.addElement( entity );
}
else {
entityList = ((Group)entity).getList();
}
}
else {
entityList.addElement( entity );
}
// Store the keyword data for use in the edit table
for( int i = 0; i < entityList.size(); i++ ) {
Entity ent = (Entity)entityList.get( i );
Input<?> in = ent.getInput(keyword);
if (in != null) {
InputAgent.updateInput(ent, in, recordCmd);
}
// The keyword is not on the editable keyword list
else {
InputAgent.logWarning("Keyword %s is obsolete. Please replace the Keyword. Refer to the manual for more detail.", keyword);
}
}
}
catch ( InputErrorException e ) {
InputAgent.logError("Entity: %s Keyword: %s - %s", entity.getName(), keyword, e.getMessage());
throw e;
}
}
public static void processData(Entity ent, Vector rec) {
if( rec.get( 1 ).toString().trim().equals( "{" ) ) {
InputAgent.logError("A keyword expected after: %s", ent.getName());
}
Vector multiCmds = InputAgent.splitMultipleCommands(rec);
// Process each command
for( int i = 0; i < multiCmds.size(); i++ ) {
Vector cmd = (Vector)multiCmds.get(i);
StringVector recordCmd = new StringVector(cmd.size() - 1);
// Omit the object name (first entry) as it is already determined
for (int j = 1; j < cmd.size(); j++) {
recordCmd.add((String)cmd.get(j));
}
// Allow old-style input to prepend the keyword if necessary
String keyword = recordCmd.remove(0);
// Process the record
InputAgent.processKeyword(ent, recordCmd, keyword);
}
return;
}
/**
* process's input data from record for use as a keyword.
* format of record: <obj-name> <keyword> <data> <keyword> <data>
* braces are included
*/
public static void processData( Vector record ) {
String item1 = ((String)record.get( 0 )).trim();
// Checks on Entity:
Entity obj = Input.tryParseEntity(item1, Entity.class);
if (obj == null) {
InputAgent.logError("Object not found: %s", item1);
return;
}
// Entity exists with name <entityName> or name <region>/<entityName>
InputAgent.processData(obj, record);
}
/**
* returns a vector of vectors
* each vector will be of form <obj-name> <kwd> <data> <data>
* no braces are returned
*/
private static Vector splitMultipleCommands( Vector record ) {
// SUPPORTED SYNTAX:
//
// <obj-name> <kwd> { <par> }
// <obj-name> <kwd> { <par> <par> ... }
// <obj-name> <kwd> { <par> <par> ... } <kwd> { <par> <par> ... } ...
// <obj-name> <kwd> <par> <kwd> { <par> <par> ... } ...
Vector multiCmds = new Vector();
int noOfUnclosedBraces = 0;
String itemObject = (String)record.remove(0);
// Loop through the keywords and assemble new commands
while( record.size() > 0 ) {
// Enter the class, object, and keyword in the new command
Vector cmd = new Vector();
// Class and object are constant
//cmd.add( itemClass );
cmd.add( itemObject );
// Keyword changes as loop proceeds
cmd.add( record.remove( 0 ) );
// For a command of the new form "<obj-name> <file-name>", record
// will be empty here.
if( !record.isEmpty() ) {
// If there is an opening brace, then the keyword has a list of
// parameters
String openingBrace = (String)record.get( 0 );
if( openingBrace.equals("{") ) {
noOfUnclosedBraces ++ ;
record.remove( 0 ); // throw out opening brace {
// Iterate through record
while( (record.size() > 0) && ( noOfUnclosedBraces > 0 ) ) {
if ( record.get(0).equals("{") )
noOfUnclosedBraces ++ ;
else if (record.get(0).equals("}"))
noOfUnclosedBraces -- ;
cmd.add( record.remove( 0 ) );
}
if( ( record.size() == 0 ) && ( noOfUnclosedBraces != 0) ) { // corresponding "}" is missing
InputAgent.logError("Closing brace } is missing.");
return multiCmds;
}
// Last item added was the corresponding closing brace
else {
cmd.remove(cmd.size()-1); // throw out the closing brace }
multiCmds.add( cmd );
}
}
// If there is no brace, then the keyword must have a single
// parameter.
else {
cmd.add( record.remove( 0 ) );
multiCmds.add( cmd );
}
}
// Record contains no other items
else {
multiCmds.add( cmd );
}
}
return multiCmds;
}
private static class ConfigFileFilter implements FilenameFilter {
public boolean accept(File inFile, String fileName) {
return fileName.endsWith("[cC][fF][gG]");
}
}
public static void load() {
System.out.println("Loading...");
FileDialog chooser = new FileDialog( DisplayEntity.simulation.getGUIFrame() , "Load Configuration File", FileDialog.LOAD );
chooser.setFilenameFilter(new ConfigFileFilter());
String chosenFileName = chooseFile(chooser, FileDialog.LOAD);
if (chosenFileName != null) {
//dispose();
setLoadFile(chosenFileName);
} else {
//dispose();
}
}
public static void save() {
System.out.println("Saving...");
setSaveFile( FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName(), SAVE_ONLY );
}
public static void saveAs() {
System.out.println("Save As...");
FileDialog chooser = new FileDialog( DisplayEntity.simulation.getGUIFrame(), "Save Configuration File As", FileDialog.SAVE );
chooser.setFilenameFilter(new ConfigFileFilter());
String chosenFileName = chooseFile(chooser, FileDialog.SAVE);
if ( chosenFileName != null ) {
//dispose();
setSaveFile( chosenFileName, FileDialog.SAVE );
} else {
//dispose();
}
}
/**
* Opens browser to choose file. returns a boolean if a file was picked, false if canceled or closed.
*/
private static String chooseFile(FileDialog chooser, int saveOrLoadType) {
// filter
if (saveOrLoadType == FileDialog.SAVE) {
chooser.setFile( InputAgent.getConfigFileName() );
} else {
chooser.setFile( "*.cfg" );
}
// display browser
//this.show();
chooser.setVisible( true );
// if a file was picked, set entryarea to be this file
if( chooser.getFile() != null ) {
//chooser should not set root directory
//FileEntity.setRootDirectory( chooser.getDirectory() );
String chosenFileName = chooser.getDirectory() + chooser.getFile();
return chosenFileName.trim();
} else {
return null;
}
}
/**
* Loads configuration file , calls GraphicSimulation.configure() method
*/
private static void setLoadFile(String fileName) {
final String chosenFileName = fileName;
new Thread(new Runnable() {
public void run() {
File temp = new File(chosenFileName);
if( temp.isAbsolute() ) {
FileEntity.setRootDirectory( temp.getParentFile() );
DisplayEntity.simulation.configure(temp.getName());
}
else {
DisplayEntity.simulation.configure(chosenFileName);
}
FrameBox.valueUpdate();
}
}).start();
}
/**
* saves the cfg/pos file. checks for 'save' and 'save as', recursively goes to 'save as' if 'save' is not possible.
* updates runname and filename of file.
* if editbox is open and unaccepted, accepts changes.
*/
private static void setSaveFile(String fileName, int saveOrLoadType) {
String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName();
// check ending string of filename, force cfg onto end if needed
if (!(fileName.endsWith(".cfg"))) {
fileName = fileName.concat(".cfg");
}
File temp = new File(fileName);
//System.out.println("fileName is " + fileName);
// If the original configuration file is the same as the file to save, and there were no added records,
// then do not save the file because it would be recursive, i.e. contain "include <fileName>"
if( configFilePath.equalsIgnoreCase( fileName ) ) {
if( !InputAgent.hasAddedRecords() ) {
if( saveOrLoadType == FileDialog.SAVE) {
// recursive -- if can't overwrite base file, 'save as'
// Ask if appending to base configuration is ok
int appendOption = JOptionPane.showConfirmDialog( null,
"Cannot overwrite base configuration file. Do you wish to append changes?",
"Confirm Append",
JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE );
// Perform append only if yes
if (appendOption == JOptionPane.YES_OPTION) {
FileEntity configFile = new FileEntity( fileName, FileEntity.FILE_WRITE, true );
configFile.write( "\n" + addedRecordMarker );
addedRecordFound = true;
}
else {
InputAgent.saveAs();
return;
}
}
else {
InputAgent.saveAs();
return;
}
} else if ( saveOrLoadType == SAVE_ONLY) {
System.out.println("Saving...");
}
}
// set root directory
FileEntity.setRootDirectory( temp.getParentFile() );
//saveFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
//simulation.printNewConfigurationFileOn( saveFile );
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
//TODOalan set directory of model.. ?
InputAgent.setConfigFileName(Util.fileShortName(fileName));
// Set the title bar to match the new run name
DisplayEntity.simulation.getGUIFrame().setTitle( DisplayEntity.simulation.getModelName() + " - " + InputAgent.getRunName() );
// close the window
//dispose();
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
Entity ent;
// Create report file for the inputs
FileEntity inputReportFile;
String inputReportFileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + ".inp";
if( FileEntity.fileExists( inputReportFileName ) ) {
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
inputReportFile.flush();
}
else
{
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
}
// Loop through the entity classes
boolean hasinput = false; // for formating output
int count = 0; // for formating output
String entityName = null; // to take out Region name
// print Define statements
for( ObjectType type : ObjectType.getAll() ) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
ArrayList<? extends Entity> cloneList = Simulation.getInstancesOf(each);
count = 0;
for( int j=0; j < cloneList.size(); j++ ) {
hasinput = false;
ent = cloneList.get(j);
for( Input<?> in : ent.getEditableInputs() ){
// If the keyword has been used, then add a record to the report
if ( in.getValueString().length() != 0 ){
hasinput = true;
count++;
break;
}
}
if ( each.getSimpleName().equalsIgnoreCase("Region") && hasinput == false )
{
count++;
hasinput = true;
}
if( hasinput ){
entityName = cloneList.get(j).getInputName();
if ( (count-1)%5 == 0) {
inputReportFile.putString( "Define" );
inputReportFile.putTab();
inputReportFile.putString(each.getSimpleName());
inputReportFile.putTab();
inputReportFile.putString( "{ " + entityName );
inputReportFile.putTab();
}
else if ( (count-1)%5 == 4 ){
inputReportFile.putString( entityName + " }" );
inputReportFile.newLine();
}
else {
inputReportFile.putString( entityName );
inputReportFile.putTab();
}
}
}
if ( cloneList.size() > 0 ){
if ( count%5 != 0 ){
inputReportFile.putString( " }" );
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for( ObjectType type : ObjectType.getAll() ) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Simulation.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if( cloneList.size() > 0 ) {
inputReportFile.putString( "\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
public int compare(Entity a, Entity b) {
return a.getInputName().compareTo(b.getInputName());
}
});
// Loop through the instances for this entity class
for( int j=0; j < cloneList.size(); j++ ) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
ent = cloneList.get(j);
entityName = cloneList.get(j).getInputName();
hasinput = false;
// Loop through the editable keywords for this instance
for( Input<?> in : ent.getEditableInputs() ) {
// If the keyword has been used, then add a record to the report
if ( in.getValueString().length() != 0 ) {
if ( ! in.getCategory().contains("Graphics") ) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString( entityName );
inputReportFile.putTab();
inputReportFile.putString( in.getKeyword() );
inputReportFile.putTab();
if( in.getValueString().lastIndexOf( "{" ) > 10 ) {
String[] item1Array;
item1Array = in.getValueString().trim().split( " }" );
inputReportFile.putString( "{ " + item1Array[0] + " }" );
for (int l = 1; l < (item1Array.length); l++ ){
inputReportFile.newLine();
inputReportFile.putTabs( 5 );
inputReportFile.putString( item1Array[l] + " } " );
}
inputReportFile.putString( " }" );
}
else {
inputReportFile.putString( "{ " + in.getValueString() + " }" );
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if ( hasinput ) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
logFile = null;
}
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
line.append(" ").append(tokens.get(i));
if (tokens.get(i).startsWith("\"")) {
InputAgent.logMessage("%s", line.toString());
line.setLength(0);
}
}
// Leftover input
if (line.length() > 0)
InputAgent.logMessage("%s", line.toString());
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
System.out.println(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
/*
* Log the input to a file, but don't echo it out as well.
*/
public static void echoInput(Vector line) {
// if there is no log file currently, output nothing
if (logFile == null)
return;
StringBuilder msg = new StringBuilder();
for (Object each : line) {
msg.append(" ");
msg.append(each);
}
logFile.write(msg.toString());
logFile.newLine();
logFile.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){
ArrayList<String> tokens = new ArrayList<String>();
InputAgent.tokenizeString(tokens, value);
if(! InputAgent.enclosedByBraces(tokens) ) {
tokens.add(0, "{");
tokens.add("}");
}
tokens.add(0, ent.getInputName());
tokens.add(1, in.getKeyword());
Vector data = new Vector(tokens.size());
data.addAll(tokens);
InputAgent.processData(ent, data);
}
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
Input<?> in = ent.getInput( keyword );
processEntity_Keyword_Value(ent, in, value);
}
public static void updateInput(Entity ent, Input<?> in, StringVector data) {
if(ent.testFlag(Entity.FLAG_GENERATED))
return;
String str = data.toString();
// reformat input string to be added to keyword
// strip out "{}" from data to find value
if( data.size() > 0 ) {
if (!(data.get(0).equals("{"))) {
str = str.replaceAll("[{}]", "");
} else {
int strLength = str.length();
str = String.format("{%s}", str.substring(3,strLength-3));
}
str = str.replaceAll( "[,]", " " );
str = str.trim();
}
// Takes care of old format, displaying as new format -- appending onto end of record.
if( in.isAppendable() && ! data.get(0).equals("{") ) {
str = String.format("%s { %s }", in.getValueString(), str );
}
if(in.isEdited()) {
in.setEditedValueString(str);
ent.setFlag(Entity.FLAG_EDITED);
sessionEdited = true;
}
else {
in.setValueString(str);
}
}
/**
* Print out a configuration file with all the edited changes attached
*/
public static void printNewConfigurationFileWithName( String fileName ) {
StringVector preAddedRecordLines = new StringVector();
String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName();
if( InputAgent.hasAddedRecords() && FileEntity.fileExists( configFilePath ) ) {
// Store the original configuration file lines up to added records
try {
BufferedReader in = new BufferedReader( new FileReader( configFilePath ) );
String line;
while ( ( line = in.readLine() ) != null ) {
if ( line.startsWith( addedRecordMarker ) ) {
break;
}
else {
preAddedRecordLines.addElement( line );
}
}
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
FileEntity file = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
// include the original configuration file
if (!InputAgent.hasAddedRecords()) {
file.format( "\" File: %s\n\n", file.getFileName() );
file.format( "include %s\n\n", InputAgent.getConfigFileName() );
}
else {
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
String line = preAddedRecordLines.get( i );
if( line.startsWith( "\" File: " ) ) {
file.format( "\" File: %s\n", file.getFileName() );
}
else {
file.format("%s\n", line);
}
}
}
file.format("%s\n\n", addedRecordMarker);
addedRecordFound = true;
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>();
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Print the define statements for each new class
for( Class<? extends Entity> newClass : newClasses ) {
file.putString( "Define " + newClass.getSimpleName()+" {" );
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.toString());
}
file.format("}\n");
}
// List all the changes that were saved for each edited entity
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_EDITED))
continue;
file.format("\n");
// Write new configuration file for non-appendable keywords
//for( int j=0; j < ent.getKeywordChangedList().size(); j++ ) {
// currentKeywordFlag = ent.getKeywordChangedList().get( j );
for( int j=0; j < ent.getEditableInputs().size(); j++ ) {
Input<?> in = ent.getEditableInputs().get( j );
if( in.isEdited() ) {
// Each line starts with the entity name followed by changed keyword
file.format("%s %s ", ent.getInputName(), in.getKeyword());
String value = in.getValueString();
ArrayList<String> tokens = new ArrayList<String>();
InputAgent.tokenizeString(tokens, value);
if(! InputAgent.enclosedByBraces(tokens) ) {
value = String.format("{ %s }", value);
}
file.format("%s\n", value);
}
}
}
file.flush();
file.close();
}
static void loadDefault() {
// Read the default configuration file
InputAgent.readURL(InputAgent.class.getResource("/resources/inputs/default.cfg"));
DisplayEntity.simulation.setSkyImage();
sessionEdited = false;
}
}
|
com/sandwell/JavaSimulation3D/InputAgent.java
|
/*
* JaamSim Discrete Event Simulation
* Copyright (C) 2009-2011 Ausenco Engineering Canada Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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.
*/
package com.sandwell.JavaSimulation3D;
import java.awt.FileDialog;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.swing.JOptionPane;
import com.sandwell.JavaSimulation.*;
import com.sandwell.JavaSimulation.Package;
public class InputAgent {
private static final String addedRecordMarker = "\" *** Added Records ***";
private static int numErrors = 0;
private static int numWarnings = 0;
private static FileEntity logFile;
private static String configFileName;
private static boolean batchRun;
private static boolean sessionEdited;
private static boolean addedRecordFound;
private static boolean endOfFileReached; // notes end of cfg files
// ConfigurationFile load and save variables
final protected static int SAVE_ONLY = 2;
private static final String INP_ERR_DEFINEUSED = "The name: %s has already been used and is a %s";
private static String reportDirectory;
static {
addedRecordFound = false;
sessionEdited = false;
endOfFileReached = false;
batchRun = false;
configFileName = "Simulation1.cfg";
reportDirectory = "";
}
public static void clear() {
logFile = null;
numErrors = 0;
numWarnings = 0;
addedRecordFound = false;
sessionEdited = false;
configFileName = "Simulation1.cfg";
reportDirectory = "";
}
public static String getReportDirectory() {
return reportDirectory;
}
public static void setReportDirectory(String dir) {
reportDirectory = Util.getAbsoluteFilePath(dir);
if (reportDirectory.substring(reportDirectory.length() - 1) != "\\")
reportDirectory = reportDirectory + "\\";
// Create the report directory if it does not already exist
// This code should probably be added to FileEntity someday to
// create necessary folders on demand.
File f = new File(reportDirectory);
f.mkdirs();
}
public static void setConfigFileName(String name) {
configFileName = name;
}
public static String getConfigFileName() {
return configFileName;
}
public static String getRunName() {
int index = Util.fileShortName( InputAgent.getConfigFileName() ).indexOf( "." );
String runName;
if( index > -1 ) {
runName = Util.fileShortName( InputAgent.getConfigFileName() ).substring( 0, index );
}
else {
runName = Util.fileShortName( InputAgent.getConfigFileName() );
}
return runName;
}
public static boolean hasAddedRecords() {
return addedRecordFound;
}
public static boolean isSessionEdited() {
return sessionEdited;
}
public static void setBatch(boolean batch) {
batchRun = batch;
}
/**
* Break the record into individual tokens and append it to the token list
*/
public static void tokenizeString(ArrayList<String> tokens, String record) {
// Split the record into two pieces, the contents portion and possibly
// a commented portion
String[] contents = record.split("\"", 2);
// Split the contents along single-quoted substring boundaries to allow
// us to parse quoted and unquoted sections separately
String[] substring = contents[0].split("'", -1);
for (int i = 0; i < substring.length; i++) {
// Odd indices were single-quoted strings in the original record
// restore the quotes and append the whole string as a single token
// even if there was nothing between the quotes (an empty string)
if (i % 2 != 0) {
tokens.add(String.format("'%s'", substring[i]));
continue;
}
// The even-index strings need tokenizing, we allow spaces, tabs and
// commas to delimit token boundaries, we also want all braces {} to
// appear as a single token
// Ensure { or } has tabs separating if from adjacent characters
String temp = substring[i].replaceAll("([\\{\\}])", "\t$1\t");
// Split along space, comma and tab characters, treat consecutive
// characters as one delimiter
String[] delimTokens = temp.split("[ ,\t]+", 0);
// Append the new tokens that have greater than zero length
for (String each : delimTokens) {
if (each.length() > 0)
tokens.add(each);
}
}
// add any comments if they exist with a leading " prepended to denote it
// as commented
if (contents.length == 2)
tokens.add(String.format("\"%s", contents[1]));
}
/**
* returns true if the first and last tokens are matched braces
**/
public static boolean enclosedByBraces(ArrayList<String> tokens) {
if(tokens.size() < 2 || tokens.indexOf("{") < 0) // no braces
return false;
int level =1;
int i = 1;
for(String each: tokens.subList(1, tokens.size())) {
if(each.equals("{")) {
level++;
}
if(each.equals("}")) {
level--;
// Matching close brace found
if(level == 0)
break;
}
i++;
}
if(level == 0 && i == tokens.size()-1) {
return true;
}
return false;
}
private static boolean isRecordComplete(ArrayList<String> tokens) {
int braceDepth = 0;
for (int i = 0; i < tokens.size(); i++) {
String token = tokens.get(i);
if (token.equals("{"))
braceDepth++;
if (token.equals("}"))
braceDepth--;
if (braceDepth < 0) {
InputAgent.logBadInput(tokens, "Extra closing braces found");
tokens.clear();
return false;
}
if (braceDepth > 2) {
InputAgent.logBadInput(tokens, "Maximum brace depth (2) exceeded");
tokens.clear();
return false;
}
}
if (braceDepth == 0)
return true;
else
return false;
}
public static void readURL(URL url) {
if (url == null)
return;
BufferedReader buf = null;
try {
InputStream in = url.openStream();
buf = new BufferedReader(new InputStreamReader(in));
} catch (IOException e) {
InputAgent.logWarning("Could not read from %s", url.toString());
return;
}
try {
ArrayList<String> record = new ArrayList<String>();
while (true) {
String line = buf.readLine();
// end of file, stop reading
if (line == null)
break;
// Set flag if found " *** Added Records ***
if ( line.trim().equalsIgnoreCase( addedRecordMarker ) ) {
addedRecordFound = true;
}
InputAgent.tokenizeString(record, line);
if (!InputAgent.isRecordComplete(record))
continue;
InputAgent.processRecord(url, record);
record.clear();
}
// Leftover Input at end of file
if (record.size() > 0)
InputAgent.logBadInput(record, "Leftover input at end of file");
buf.close();
}
catch (IOException e) {
// Make best effort to ensure it closes
try { buf.close(); } catch (IOException e2) {}
}
}
private static void removeComments(ArrayList<String> record) {
for (int i = record.size() - 1; i >= 0; i--) {
// remove parts of the input that were commented out
if (record.get(i).startsWith("\"")) {
record.remove(i);
continue;
}
// strip single-quoted strings when passing through to the parsers
if (record.get(i).startsWith("'")) {
String noQuotes = record.get(i).substring(1, record.get(i).length() - 1);
record.set(i, noQuotes);
}
}
}
private static void processRecord(URL url, ArrayList<String> record) {
//InputAgent.echoInputRecord(record);
InputAgent.removeComments(record);
if (record.size() == 0)
return;
if (record.get(0).equalsIgnoreCase("INCLUDE")) {
InputAgent.processIncludeRecord(url, record);
return;
}
if (record.get(0).equalsIgnoreCase("DEFINE")) {
InputAgent.processDefineRecord(record);
return;
}
// Otherwise assume it is a Keyword record
InputAgent.processKeywordRecord(record);
}
private static void processIncludeRecord(URL baseURL, ArrayList<String> record) {
if (record.size() != 2) {
InputAgent.logError("Bad Include record, should be: Include <File>");
return;
}
// Ensure the include filename is well formed
URL finalURL = null;
try {
URI incFile = new URI(record.get(1).replaceAll("\\\\", "/"));
// Construct a base file in case this URI is relative and split at ! to
// account for a jar:file:<jarfilename>!<internalfilename> URL
int bangIndex = baseURL.toString().lastIndexOf("!") + 1;
String prefix = baseURL.toString().substring(0, bangIndex);
String folder = baseURL.toString().substring(bangIndex);
URI folderURI = new URI(folder).resolve(incFile);
// Remove all remaining relative path directives ../
String noRelative = folderURI.toString().replaceAll("\\.\\./", "");
finalURL = new URL(prefix + noRelative);
}
catch (NullPointerException e) {}
catch (URISyntaxException e) {}
catch (MalformedURLException e) {}
finally {
if (finalURL == null) {
InputAgent.logError("Unable to parse filename: %s", record.get(1));
return;
}
}
InputAgent.readURL(finalURL);
}
private static void processDefineRecord(ArrayList<String> record) {
if (record.size() < 5 ||
!record.get(2).equals("{") ||
!record.get(record.size() - 1).equals("}")) {
InputAgent.logError("Bad Define record, should be: Define <Type> { <names>... }");
return;
}
Class<? extends Entity> proto = null;
try {
if( record.get( 1 ).equalsIgnoreCase( "Package" ) ) {
proto = Package.class;
}
else if( record.get( 1 ).equalsIgnoreCase( "ObjectType" ) ) {
proto = ObjectType.class;
}
else {
proto = Input.parseEntityType(record.get(1));
}
}
catch (InputErrorException e) {
InputAgent.logError("%s", e.getMessage());
return;
}
// Loop over all the new Entity names
for (int i = 3; i < record.size() - 1; i++) {
InputAgent.defineEntity(proto, record.get(i), false);
}
}
/**
* if userDefined is true then this is an entity defined by user interaction;
* otherwise, it is from an input file define statement
* @param proto
* @param key
* @param userDefined
*/
public static Entity defineEntity(Class<? extends Entity> proto, String key, boolean userDefined) {
Region region = null;
String name = key;
Entity ent = Input.tryParseEntity(key, Entity.class);
if (ent != null) {
InputAgent.logError(INP_ERR_DEFINEUSED, name, ent.getClass().getSimpleName());
return null;
}
if (key.contains("/")) {
String regionName = key.substring(0, key.indexOf("/"));
name = key.substring(key.indexOf("/") + 1);
Entity check = Input.tryParseEntity(regionName, Entity.class);
if (check == null) {
InputAgent.logError("%s not found, could not define: %s", regionName, name);
return null;
}
if (check instanceof Region)
region = (Region)check;
else
name = key;
}
ent = null;
try {
ent = proto.newInstance();
if (hasAddedRecords() || userDefined) {
ent.setFlag(Entity.FLAG_ADDED);
sessionEdited = true;
}
}
catch (InstantiationException e) {}
catch (IllegalAccessException e) {}
finally {
if (ent == null) {
InputAgent.logError("Could not create new Entity: %s", key);
return null;
}
}
ent.setName(name);
ent.setInputName(key);
if (region != null)
ent.setRegion( region );
ent.defineNewEntity();
return ent;
}
private static void processKeywordRecord(ArrayList<String> record) {
Entity ent = Input.tryParseEntity(record.get(0), Entity.class);
if (ent == null) {
InputAgent.logError("Could not find Entity: %s", record.get(0));
return;
}
ArrayList<ArrayList<String>> keywords = InputAgent.splitKeywords(record);
for (ArrayList<String> keyword : keywords) {
if (keyword.size() < 3 ||
!keyword.get(1).equals("{") ||
!keyword.get(keyword.size() - 1).equals("}")) {
InputAgent.logError("Keyword not valid, should be <keyword> { <args> }");
continue;
}
String key = keyword.get(0);
StringVector args = new StringVector(keyword.size() - 3);
for (int i = 2; i < keyword.size() - 1; i++) {
args.add(keyword.get(i));
}
try {
InputAgent.processKeyword(ent, args, key);
}
catch (Throwable e) {
InputAgent.logError("Exception thrown from Entity: %s for keyword:%s - %s", ent.getInputName(), key, e.getMessage());
}
}
}
private static ArrayList<ArrayList<String>> splitKeywords(ArrayList<String> input) {
ArrayList<ArrayList<String>> inputs = new ArrayList<ArrayList<String>>();
int braceDepth = 0;
ArrayList<String> currentLine = null;
for (int i = 1; i < input.size(); i++) {
if (currentLine == null)
currentLine = new ArrayList<String>();
currentLine.add(input.get(i));
if (input.get(i).equals("{")) {
braceDepth++;
continue;
}
if (input.get(i).equals("}")) {
braceDepth--;
if (braceDepth == 0) {
inputs.add(currentLine);
currentLine = null;
continue;
}
}
}
return inputs;
}
public static void doError(Throwable e) {
if (!batchRun)
return;
System.out.println("An error occurred in the simulation environment. Please check inputs for an error:");
System.out.println(e);
System.exit(1);
}
public static void loadConfigFile(String fileName) {
try {
DisplayEntity.simulation.getGUIFrame().updateForSimulationState();
InputAgent.loadConfigurationFile(fileName);
GraphicsUpdateBehavior.forceUpdate = true;
}
catch( InputErrorException iee ) {
if (!batchRun) {
javax.swing.JOptionPane.showMessageDialog( null, iee.getMessage(), "Input Error", javax.swing.JOptionPane.ERROR_MESSAGE );
}
else {
System.out.println( iee.getMessage() );
}
return;
}
}
// Load the run file
public static void loadConfigurationFile( String fileName) {
String inputTraceFileName = InputAgent.getRunName() + ".log";
// Initializing the tracing for the model
try {
System.out.println( "Creating trace file" );
// Set and open the input trace file name
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
catch( Exception e ) {
throw new ErrorException( "Could not create trace file" );
}
InputAgent.loadConfigurationFile(fileName, true);
// At this point configuration file is loaded
// Save and close the input trace file
if (logFile != null) {
if (InputAgent.numWarnings == 0 && InputAgent.numErrors == 0) {
logFile.close();
logFile.delete();
logFile = new FileEntity( inputTraceFileName, FileEntity.FILE_WRITE, false );
}
}
// Check for found errors
if( InputAgent.numErrors > 0 )
throw new InputErrorException("%d input errors found, check log file", InputAgent.numErrors);
// print inputKeywordfile
if( DisplayEntity.simulation.getPrintInputReport() ) {
InputAgent.printInputFileKeywords();
}
}
/**
*
* @param fileName
* @param firstTime ( true => this is the main config file (run file); false => this is an included file within main config file or another included file )
*/
public static void loadConfigurationFile( String fileName, boolean firstTime ) {
//System.out.println( "load configuration file " + fileName );
FileEntity file;
Vector record;
// If the file does not exist, write an error and exit
if( !FileEntity.fileExists( fileName ) ) {
System.out.println( (("Error -- The input file " + fileName) + " was not found ") );
System.exit( 0 );
}
// Open the file
file = new FileEntity( fileName, FileEntity.FILE_READ, false );
String mainRootDirectory = null;
String originalJarFileRootDirectory = null;
if( firstTime ) {
// Store the directory of the first input file
file.setRootDirectory();
}
else {
// Save the directory of the first file
mainRootDirectory = FileEntity.getRootDirectory();
// Switch to the directory of the current input file
file.setRootDirectory();
// Save the directory of the first file within the jar file
originalJarFileRootDirectory = FileEntity.getJarFileRootDirectory();
try {
// Determine the url of the file from the jar file com/sandwell/JavaSimulation directory
String relativeURL = FileEntity.getRelativeURL( fileName );
// Is the file is inside the jar file?
if (Simulation.class.getResource(relativeURL) != null) {
// Set the directory of the file inside the jar file relative to com/sandwell/JavaSimulation directory
int lastIndex = relativeURL.lastIndexOf( '/' );
String jarFileRootDirectory = relativeURL.substring( 0, lastIndex ).replace( "/", "\\" );
FileEntity.setJarFileRootDirectory( jarFileRootDirectory );
}
}
catch( Exception e ) {
throw new ErrorException( "Could not open " + fileName );
}
}
// Initialize the input file
file.toStart();
DisplayEntity.simulation.setProgressText( file.getFileName() );
// For each line in the file
while( true ) {
// Read the next line to record
record = getNextParsedRecord( file );
// System.out.println( record.toString() );
// Determine the amount of file read and update the progress gauge
int per = (int)(((double)file.getNumRead()) / ((double)file.getLength()) * 100.0);
DisplayEntity.simulation.setProgress( per );
// When end-of-file is reached, record.size() == 0
if( endOfFileReached ) {
break;
}
// Process this line if it is not empty
if ( record.size() > 0 ) {
// If there is an included file, LoadConfigurationFile is run for that (This is recursive)
InputAgent.readRecord(record, file);
}
}
// Reset the progress bar to zero and remove its label
DisplayEntity.simulation.setProgressText( null );
DisplayEntity.simulation.setProgress( 0 );
// Close the file
file.close();
// Restore to the directory of the first input file
if ( ! firstTime ) {
FileEntity.setRootDirectory( mainRootDirectory );
FileEntity.setJarFileRootDirectory( originalJarFileRootDirectory );
}
}
/**
* Reads record, either as a default, define statement, include, or keyword
* @param record
* @param file
*/
private static void readRecord(Vector record, FileEntity file) {
if(record.size() < 2){
InputAgent.logError("Invalid input line - missing keyword or parameter");
return;
}
try {
if( "DEFINE".equalsIgnoreCase( (String)record.get( 0 ) ) ) {
ArrayList<String> tempCopy = new ArrayList<String>(record.size());
for (int i = 0; i < record.size(); i++)
tempCopy.add((String)record.get(i));
InputAgent.processDefineRecord(tempCopy);
}
// Process other files
else if( "INCLUDE".equalsIgnoreCase( (String)record.get( 0 ) ) ) {
if( record.size() == 2 ) {
if( FileEntity.fileExists( (String)record.get( 1 ) ) ) {
// Load the included file and process its records first
InputAgent.loadConfigurationFile( (String)record.get( 1 ), false );
DisplayEntity.simulation.setProgressText( file.getFileName() );
}
else {
InputAgent.logError("File not found: %s", (String)record.get(1));
}
}
else {
InputAgent.logError("There must be exactly two entries in an Include record");
}
}
// is a keyword
else {
InputAgent.processData(record);
}
}
catch( InputErrorException iee ) {
}
}
// Read the next line of the file
protected static Vector getNextParsedRecord(FileEntity file) {
Vector record = new Vector( 1 , 1 );
int noOfUnclosedBraces = 0;
do {
Vector nextLine = file.readAndParseRecord();
InputAgent.echoInput(nextLine);
if (nextLine.size() == 0) {
endOfFileReached = true;
}
else {
endOfFileReached = false;
}
// Set flag if input records added through the EditBox interface are found
if ( !(endOfFileReached) && ( ((String) nextLine.get( 0 )).equalsIgnoreCase( addedRecordMarker ) ) ) {
addedRecordFound = true;
}
Util.discardComment( nextLine );
// Count braces and allow input with a missing space following an opening brace and/or a missing space preceding a closing brace
for (int i = 0; i < nextLine.size(); i++) {
String checkRecord = (String)nextLine.get( i );
Vector parsedString = new Vector( 1 , 1 );
// Check for braces
for (int j=0; j<checkRecord.length(); j++) {
// '(' & ')' are not allowed in the input file
if( checkRecord.charAt(j) == '(' || checkRecord.charAt(j) == ')' ) {
throw new ErrorException( "\n\"" + checkRecord.charAt(j) + "\"" + " is not allowed in the input file: \n" + nextLine + "\n" + FileEntity.getRootDirectory() + file.getFileName() );
}
if (checkRecord.charAt(j) == '{') {
noOfUnclosedBraces++;
parsedString.add("{");
}
else if (checkRecord.charAt(j) == '}') {
noOfUnclosedBraces--;
parsedString.add("}");
} else {
// no brace is found, assume it is a whole word until the next brace
String stringDump = "";
// iterate through
for ( int k = j; k<checkRecord.length(); k++ ) {
// if a brace is found, end checking this word
if ( checkRecord.charAt(k) == '{' || checkRecord.charAt(k) == '}' ) {
k = checkRecord.length();
}
// otherwise, make the word
else {
stringDump += checkRecord.charAt(k);
}
}
j += stringDump.length() - 1;
parsedString.add(stringDump);
}
}
// Add brackets as separate entries
if (parsedString.size() > 0 ) {
nextLine.remove( i );
nextLine.addAll( i , parsedString );
i = i + parsedString.size() - 1;
}
}
record.addAll(nextLine);
} while ( ( noOfUnclosedBraces != 0 ) && ( !endOfFileReached ) );
if( noOfUnclosedBraces != 0 ) {
InputAgent.logError("Missing closing brace");
}
return record;
}
private static void processKeyword( Entity entity, StringVector recordCmd, String keyword) {
if (keyword == null)
throw new InputErrorException("The keyword is null.");
if (entity.testFlag(Entity.FLAG_LOCKED))
throw new InputErrorException("Entity: %s is locked and cannot be modified", entity.getName());
try {
Input<?> input = entity.getInput( keyword );
if( input != null && input.isAppendable() ) {
ArrayList<StringVector> splitData = Util.splitStringVectorByBraces(recordCmd);
for ( int i = 0; i < splitData.size(); i++ ) {
entity.readInput(splitData.get(i), keyword, false, false);
}
}
else {
entity.readInput(recordCmd, keyword, false, false);
}
// Create a list of entities to update in the edit table
Vector entityList = new Vector( 1, 1 );
if( entity instanceof Group ) {
// Is the keyword a Group keyword?
if( entity.getInput( keyword ) != null ) {
entityList.addElement( entity );
}
else {
entityList = ((Group)entity).getList();
}
}
else {
entityList.addElement( entity );
}
// Store the keyword data for use in the edit table
for( int i = 0; i < entityList.size(); i++ ) {
Entity ent = (Entity)entityList.get( i );
Input<?> in = ent.getInput(keyword);
if (in != null) {
InputAgent.updateInput(ent, in, recordCmd);
}
// The keyword is not on the editable keyword list
else {
InputAgent.logWarning("Keyword %s is obsolete. Please replace the Keyword. Refer to the manual for more detail.", keyword);
}
}
}
catch ( InputErrorException e ) {
InputAgent.logError("Entity: %s Keyword: %s - %s", entity.getName(), keyword, e.getMessage());
throw e;
}
}
public static void processData(Entity ent, Vector rec) {
if( rec.get( 1 ).toString().trim().equals( "{" ) ) {
InputAgent.logError("A keyword expected after: %s", ent.getName());
}
Vector multiCmds = InputAgent.splitMultipleCommands(rec);
// Process each command
for( int i = 0; i < multiCmds.size(); i++ ) {
Vector cmd = (Vector)multiCmds.get(i);
StringVector recordCmd = new StringVector(cmd.size() - 1);
// Omit the object name (first entry) as it is already determined
for (int j = 1; j < cmd.size(); j++) {
recordCmd.add((String)cmd.get(j));
}
// Allow old-style input to prepend the keyword if necessary
String keyword = recordCmd.remove(0);
// Process the record
InputAgent.processKeyword(ent, recordCmd, keyword);
}
return;
}
/**
* process's input data from record for use as a keyword.
* format of record: <obj-name> <keyword> <data> <keyword> <data>
* braces are included
*/
public static void processData( Vector record ) {
String item1 = ((String)record.get( 0 )).trim();
// Checks on Entity:
Entity obj = Input.tryParseEntity(item1, Entity.class);
if (obj == null) {
InputAgent.logError("Object not found: %s", item1);
return;
}
// Entity exists with name <entityName> or name <region>/<entityName>
InputAgent.processData(obj, record);
}
/**
* returns a vector of vectors
* each vector will be of form <obj-name> <kwd> <data> <data>
* no braces are returned
*/
private static Vector splitMultipleCommands( Vector record ) {
// SUPPORTED SYNTAX:
//
// <obj-name> <kwd> { <par> }
// <obj-name> <kwd> { <par> <par> ... }
// <obj-name> <kwd> { <par> <par> ... } <kwd> { <par> <par> ... } ...
// <obj-name> <kwd> <par> <kwd> { <par> <par> ... } ...
Vector multiCmds = new Vector();
int noOfUnclosedBraces = 0;
String itemObject = (String)record.remove(0);
// Loop through the keywords and assemble new commands
while( record.size() > 0 ) {
// Enter the class, object, and keyword in the new command
Vector cmd = new Vector();
// Class and object are constant
//cmd.add( itemClass );
cmd.add( itemObject );
// Keyword changes as loop proceeds
cmd.add( record.remove( 0 ) );
// For a command of the new form "<obj-name> <file-name>", record
// will be empty here.
if( !record.isEmpty() ) {
// If there is an opening brace, then the keyword has a list of
// parameters
String openingBrace = (String)record.get( 0 );
if( openingBrace.equals("{") ) {
noOfUnclosedBraces ++ ;
record.remove( 0 ); // throw out opening brace {
// Iterate through record
while( (record.size() > 0) && ( noOfUnclosedBraces > 0 ) ) {
if ( record.get(0).equals("{") )
noOfUnclosedBraces ++ ;
else if (record.get(0).equals("}"))
noOfUnclosedBraces -- ;
cmd.add( record.remove( 0 ) );
}
if( ( record.size() == 0 ) && ( noOfUnclosedBraces != 0) ) { // corresponding "}" is missing
InputAgent.logError("Closing brace } is missing.");
return multiCmds;
}
// Last item added was the corresponding closing brace
else {
cmd.remove(cmd.size()-1); // throw out the closing brace }
multiCmds.add( cmd );
}
}
// If there is no brace, then the keyword must have a single
// parameter.
else {
cmd.add( record.remove( 0 ) );
multiCmds.add( cmd );
}
}
// Record contains no other items
else {
multiCmds.add( cmd );
}
}
return multiCmds;
}
private static class ConfigFileFilter implements FilenameFilter {
public boolean accept(File inFile, String fileName) {
return fileName.endsWith("[cC][fF][gG]");
}
}
public static void load() {
System.out.println("Loading...");
FileDialog chooser = new FileDialog( DisplayEntity.simulation.getGUIFrame() , "Load Configuration File", FileDialog.LOAD );
chooser.setFilenameFilter(new ConfigFileFilter());
String chosenFileName = chooseFile(chooser, FileDialog.LOAD);
if (chosenFileName != null) {
//dispose();
setLoadFile(chosenFileName);
} else {
//dispose();
}
}
public static void save() {
System.out.println("Saving...");
setSaveFile( FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName(), SAVE_ONLY );
}
public static void saveAs() {
System.out.println("Save As...");
FileDialog chooser = new FileDialog( DisplayEntity.simulation.getGUIFrame(), "Save Configuration File As", FileDialog.SAVE );
chooser.setFilenameFilter(new ConfigFileFilter());
String chosenFileName = chooseFile(chooser, FileDialog.SAVE);
if ( chosenFileName != null ) {
//dispose();
setSaveFile( chosenFileName, FileDialog.SAVE );
} else {
//dispose();
}
}
/**
* Opens browser to choose file. returns a boolean if a file was picked, false if canceled or closed.
*/
private static String chooseFile(FileDialog chooser, int saveOrLoadType) {
// filter
if (saveOrLoadType == FileDialog.SAVE) {
chooser.setFile( InputAgent.getConfigFileName() );
} else {
chooser.setFile( "*.cfg" );
}
// display browser
//this.show();
chooser.setVisible( true );
// if a file was picked, set entryarea to be this file
if( chooser.getFile() != null ) {
//chooser should not set root directory
//FileEntity.setRootDirectory( chooser.getDirectory() );
String chosenFileName = chooser.getDirectory() + chooser.getFile();
return chosenFileName.trim();
} else {
return null;
}
}
/**
* Loads configuration file , calls GraphicSimulation.configure() method
*/
private static void setLoadFile(String fileName) {
final String chosenFileName = fileName;
new Thread(new Runnable() {
public void run() {
File temp = new File(chosenFileName);
if( temp.isAbsolute() ) {
FileEntity.setRootDirectory( temp.getParentFile() );
DisplayEntity.simulation.configure(temp.getName());
}
else {
DisplayEntity.simulation.configure(chosenFileName);
}
FrameBox.valueUpdate();
}
}).start();
}
/**
* saves the cfg/pos file. checks for 'save' and 'save as', recursively goes to 'save as' if 'save' is not possible.
* updates runname and filename of file.
* if editbox is open and unaccepted, accepts changes.
*/
private static void setSaveFile(String fileName, int saveOrLoadType) {
String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName();
// check ending string of filename, force cfg onto end if needed
if (!(fileName.endsWith(".cfg"))) {
fileName = fileName.concat(".cfg");
}
File temp = new File(fileName);
//System.out.println("fileName is " + fileName);
// If the original configuration file is the same as the file to save, and there were no added records,
// then do not save the file because it would be recursive, i.e. contain "include <fileName>"
if( configFilePath.equalsIgnoreCase( fileName ) ) {
if( !InputAgent.hasAddedRecords() ) {
if( saveOrLoadType == FileDialog.SAVE) {
// recursive -- if can't overwrite base file, 'save as'
// Ask if appending to base configuration is ok
int appendOption = JOptionPane.showConfirmDialog( null,
"Cannot overwrite base configuration file. Do you wish to append changes?",
"Confirm Append",
JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE );
// Perform append only if yes
if (appendOption == JOptionPane.YES_OPTION) {
FileEntity configFile = new FileEntity( fileName, FileEntity.FILE_WRITE, true );
configFile.write( "\n" + addedRecordMarker );
addedRecordFound = true;
}
else {
InputAgent.saveAs();
return;
}
}
else {
InputAgent.saveAs();
return;
}
} else if ( saveOrLoadType == SAVE_ONLY) {
System.out.println("Saving...");
}
}
// set root directory
FileEntity.setRootDirectory( temp.getParentFile() );
//saveFile = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
//simulation.printNewConfigurationFileOn( saveFile );
InputAgent.printNewConfigurationFileWithName( fileName );
sessionEdited = false;
//TODOalan set directory of model.. ?
InputAgent.setConfigFileName(Util.fileShortName(fileName));
// Set the title bar to match the new run name
DisplayEntity.simulation.getGUIFrame().setTitle( DisplayEntity.simulation.getModelName() + " - " + InputAgent.getRunName() );
// close the window
//dispose();
}
/*
* write input file keywords and values
*
* input file format:
* Define Group { <Group names> }
* Define <Object> { <Object names> }
*
* <Object name> <Keyword> { < values > }
*
*/
public static void printInputFileKeywords() {
Entity ent;
// Create report file for the inputs
FileEntity inputReportFile;
String inputReportFileName = InputAgent.getReportDirectory() + InputAgent.getRunName() + ".inp";
if( FileEntity.fileExists( inputReportFileName ) ) {
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
inputReportFile.flush();
}
else
{
inputReportFile = new FileEntity( inputReportFileName, FileEntity.FILE_WRITE, false );
}
// Loop through the entity classes
boolean hasinput = false; // for formating output
int count = 0; // for formating output
String entityName = null; // to take out Region name
// print Define statements
for( ObjectType type : ObjectType.getAll() ) {
Class<? extends Entity> each = type.getJavaClass();
// Loop through the instances for this entity class
ArrayList<? extends Entity> cloneList = Simulation.getInstancesOf(each);
count = 0;
for( int j=0; j < cloneList.size(); j++ ) {
hasinput = false;
ent = cloneList.get(j);
for( Input<?> in : ent.getEditableInputs() ){
// If the keyword has been used, then add a record to the report
if ( in.getValueString().length() != 0 ){
hasinput = true;
count++;
break;
}
}
if ( each.getSimpleName().equalsIgnoreCase("Region") && hasinput == false )
{
count++;
hasinput = true;
}
if( hasinput ){
entityName = cloneList.get(j).getInputName();
if ( (count-1)%5 == 0) {
inputReportFile.putString( "Define" );
inputReportFile.putTab();
inputReportFile.putString(each.getSimpleName());
inputReportFile.putTab();
inputReportFile.putString( "{ " + entityName );
inputReportFile.putTab();
}
else if ( (count-1)%5 == 4 ){
inputReportFile.putString( entityName + " }" );
inputReportFile.newLine();
}
else {
inputReportFile.putString( entityName );
inputReportFile.putTab();
}
}
}
if ( cloneList.size() > 0 ){
if ( count%5 != 0 ){
inputReportFile.putString( " }" );
inputReportFile.newLine();
}
inputReportFile.newLine();
}
}
for( ObjectType type : ObjectType.getAll() ) {
Class<? extends Entity> each = type.getJavaClass();
// Get the list of instances for this entity class
// sort the list alphabetically
ArrayList<? extends Entity> cloneList = Simulation.getInstancesOf(each);
// Print the entity class name to the report (in the form of a comment)
if( cloneList.size() > 0 ) {
inputReportFile.putString( "\" " + each.getSimpleName() + " \"");
inputReportFile.newLine();
inputReportFile.newLine(); // blank line below the class name heading
}
Collections.sort(cloneList, new Comparator<Entity>() {
public int compare(Entity a, Entity b) {
return a.getInputName().compareTo(b.getInputName());
}
});
// Loop through the instances for this entity class
for( int j=0; j < cloneList.size(); j++ ) {
// Make sure the clone is an instance of the class (and not an instance of a subclass)
if (cloneList.get(j).getClass() == each) {
ent = cloneList.get(j);
entityName = cloneList.get(j).getInputName();
hasinput = false;
// Loop through the editable keywords for this instance
for( Input<?> in : ent.getEditableInputs() ) {
// If the keyword has been used, then add a record to the report
if ( in.getValueString().length() != 0 ) {
if ( ! in.getCategory().contains("Graphics") ) {
hasinput = true;
inputReportFile.putTab();
inputReportFile.putString( entityName );
inputReportFile.putTab();
inputReportFile.putString( in.getKeyword() );
inputReportFile.putTab();
if( in.getValueString().lastIndexOf( "{" ) > 10 ) {
String[] item1Array;
item1Array = in.getValueString().trim().split( " }" );
inputReportFile.putString( "{ " + item1Array[0] + " }" );
for (int l = 1; l < (item1Array.length); l++ ){
inputReportFile.newLine();
inputReportFile.putTabs( 5 );
inputReportFile.putString( item1Array[l] + " } " );
}
inputReportFile.putString( " }" );
}
else {
inputReportFile.putString( "{ " + in.getValueString() + " }" );
}
inputReportFile.newLine();
}
}
}
// Put a blank line after each instance
if ( hasinput ) {
inputReportFile.newLine();
}
}
}
}
// Close out the report
inputReportFile.flush();
inputReportFile.close();
}
public static void closeLogFile() {
if (logFile == null)
return;
logFile.flush();
logFile.close();
if (numErrors ==0 && numWarnings == 0) {
logFile.delete();
logFile = null;
}
}
private static final String errPrefix = "*** ERROR *** %s%n";
private static final String wrnPrefix = "***WARNING*** %s%n";
public static int numErrors() {
return numErrors;
}
public static int numWarnings() {
return numWarnings;
}
private static void echoInputRecord(ArrayList<String> tokens) {
StringBuilder line = new StringBuilder();
for (int i = 0; i < tokens.size(); i++) {
line.append(" ").append(tokens.get(i));
if (tokens.get(i).startsWith("\"")) {
InputAgent.logMessage("%s", line.toString());
line.setLength(0);
}
}
// Leftover input
if (line.length() > 0)
InputAgent.logMessage("%s", line.toString());
}
private static void logBadInput(ArrayList<String> tokens, String msg) {
InputAgent.echoInputRecord(tokens);
InputAgent.logError("%s", msg);
}
public static void logMessage(String fmt, Object... args) {
String msg = String.format(fmt, args);
System.out.println(msg);
if (logFile == null)
return;
logFile.write(msg);
logFile.newLine();
logFile.flush();
}
/*
* Log the input to a file, but don't echo it out as well.
*/
public static void echoInput(Vector line) {
// if there is no log file currently, output nothing
if (logFile == null)
return;
StringBuilder msg = new StringBuilder();
for (Object each : line) {
msg.append(" ");
msg.append(each);
}
logFile.write(msg.toString());
logFile.newLine();
logFile.flush();
}
public static void logWarning(String fmt, Object... args) {
numWarnings++;
String msg = String.format(fmt, args);
InputAgent.logMessage(wrnPrefix, msg);
}
public static void logError(String fmt, Object... args) {
numErrors++;
String msg = String.format(fmt, args);
InputAgent.logMessage(errPrefix, msg);
}
public static void processEntity_Keyword_Value(Entity ent, Input<?> in, String value){
ArrayList<String> tokens = new ArrayList<String>();
InputAgent.tokenizeString(tokens, value);
if(! InputAgent.enclosedByBraces(tokens) ) {
tokens.add(0, "{");
tokens.add("}");
}
tokens.add(0, ent.getInputName());
tokens.add(1, in.getKeyword());
Vector data = new Vector(tokens.size());
data.addAll(tokens);
InputAgent.processData(ent, data);
}
public static void processEntity_Keyword_Value(Entity ent, String keyword, String value){
Input<?> in = ent.getInput( keyword );
processEntity_Keyword_Value(ent, in, value);
}
public static void updateInput(Entity ent, Input<?> in, StringVector data) {
String str = data.toString();
// reformat input string to be added to keyword
// strip out "{}" from data to find value
if( data.size() > 0 ) {
if (!(data.get(0).equals("{"))) {
str = str.replaceAll("[{}]", "");
} else {
int strLength = str.length();
str = String.format("{%s}", str.substring(3,strLength-3));
}
str = str.replaceAll( "[,]", " " );
str = str.trim();
}
// Takes care of old format, displaying as new format -- appending onto end of record.
if( in.isAppendable() && ! data.get(0).equals("{") ) {
str = String.format("%s { %s }", in.getValueString(), str );
}
if(in.isEdited()) {
in.setEditedValueString(str);
ent.setFlag(Entity.FLAG_EDITED);
sessionEdited = true;
}
else {
in.setValueString(str);
}
}
/**
* Print out a configuration file with all the edited changes attached
*/
public static void printNewConfigurationFileWithName( String fileName ) {
StringVector preAddedRecordLines = new StringVector();
String configFilePath = FileEntity.getRootDirectory() + System.getProperty( "file.separator" ) + InputAgent.getConfigFileName();
if( InputAgent.hasAddedRecords() && FileEntity.fileExists( configFilePath ) ) {
// Store the original configuration file lines up to added records
try {
BufferedReader in = new BufferedReader( new FileReader( configFilePath ) );
String line;
while ( ( line = in.readLine() ) != null ) {
if ( line.startsWith( addedRecordMarker ) ) {
break;
}
else {
preAddedRecordLines.addElement( line );
}
}
}
catch ( Exception e ) {
throw new ErrorException( e );
}
}
FileEntity file = new FileEntity( fileName, FileEntity.FILE_WRITE, false );
// include the original configuration file
if (!InputAgent.hasAddedRecords()) {
file.format( "\" File: %s\n\n", file.getFileName() );
file.format( "include %s\n\n", InputAgent.getConfigFileName() );
}
else {
for( int i=0; i < preAddedRecordLines.size(); i++ ) {
String line = preAddedRecordLines.get( i );
if( line.startsWith( "\" File: " ) ) {
file.format( "\" File: %s\n", file.getFileName() );
}
else {
file.format("%s\n", line);
}
}
}
file.format("%s\n\n", addedRecordMarker);
addedRecordFound = true;
// Determine all the new classes that were created
ArrayList<Class<? extends Entity>> newClasses = new ArrayList<Class<? extends Entity>>();
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (!newClasses.contains(ent.getClass()))
newClasses.add(ent.getClass());
}
// Print the define statements for each new class
for( Class<? extends Entity> newClass : newClasses ) {
file.putString( "Define " + newClass.getSimpleName()+" {" );
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_ADDED))
continue;
if (ent.getClass() == newClass)
file.format(" %s ", ent.toString());
}
file.format("}\n");
}
// List all the changes that were saved for each edited entity
for (int i = 0; i < Entity.getAll().size(); i++) {
Entity ent = Entity.getAll().get(i);
if (!ent.testFlag(Entity.FLAG_EDITED))
continue;
file.format("\n");
// Write new configuration file for non-appendable keywords
//for( int j=0; j < ent.getKeywordChangedList().size(); j++ ) {
// currentKeywordFlag = ent.getKeywordChangedList().get( j );
for( int j=0; j < ent.getEditableInputs().size(); j++ ) {
Input<?> in = ent.getEditableInputs().get( j );
if( in.isEdited() ) {
// Each line starts with the entity name followed by changed keyword
file.format("%s %s ", ent.getInputName(), in.getKeyword());
String value = in.getValueString();
ArrayList<String> tokens = new ArrayList<String>();
InputAgent.tokenizeString(tokens, value);
if(! InputAgent.enclosedByBraces(tokens) ) {
value = String.format("{ %s }", value);
}
file.format("%s\n", value);
}
}
}
file.flush();
file.close();
}
static void loadDefault() {
// Read the default configuration file
InputAgent.readURL(InputAgent.class.getResource("/resources/inputs/default.cfg"));
DisplayEntity.simulation.setSkyImage();
sessionEdited = false;
}
}
|
JS3D: do not show generated entities in the saved input file
Signed-off-by: Ali Marandi <c1f5ba98b5f658269cb60d2683b8b1af37717b03@ausencosandwell.com>
Signed-off-by: Harvey Harrison <eadbd6b462bf3c97df0300a934c12bc2e5d1fe51@ausencosandwell.com>
|
com/sandwell/JavaSimulation3D/InputAgent.java
|
JS3D: do not show generated entities in the saved input file
|
|
Java
|
apache-2.0
|
46b3541bb97fdd62e4c40fed1d6f8c75b5e47c20
| 0
|
LMAX-Exchange/disruptor,LMAX-Exchange/disruptor
|
/*
* Copyright 2011 LMAX Ltd.
*
* 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.lmax.disruptor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Convenience class for handling the batching semantics of consuming entries from a {@link RingBuffer}
* and delegating the available events to an {@link EventHandler}.
* <p>
* If the {@link EventHandler} also implements {@link LifecycleAware} it will be notified just after the thread
* is started and just before the thread is shutdown.
*
* @param <T> event implementation storing the data for sharing during exchange or parallel coordination of an event.
*/
public final class BatchEventProcessor<T>
implements EventProcessor
{
private static final int IDLE = 0;
private static final int HALTED = IDLE + 1;
private static final int RUNNING = HALTED + 1;
private final AtomicInteger running = new AtomicInteger(IDLE);
private ExceptionHandler<? super T> exceptionHandler = new FatalExceptionHandler();
private final DataProvider<T> dataProvider;
private final SequenceBarrier sequenceBarrier;
private final EventHandler<? super T> eventHandler;
private final Sequence sequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE);
private final TimeoutHandler timeoutHandler;
private final BatchStartAware batchStartAware;
/**
* Construct a {@link EventProcessor} that will automatically track the progress by updating its sequence when
* the {@link EventHandler#onEvent(Object, long, boolean)} method returns.
*
* @param dataProvider to which events are published.
* @param sequenceBarrier on which it is waiting.
* @param eventHandler is the delegate to which events are dispatched.
*/
public BatchEventProcessor(
final DataProvider<T> dataProvider,
final SequenceBarrier sequenceBarrier,
final EventHandler<? super T> eventHandler)
{
this.dataProvider = dataProvider;
this.sequenceBarrier = sequenceBarrier;
this.eventHandler = eventHandler;
if (eventHandler instanceof SequenceReportingEventHandler)
{
((SequenceReportingEventHandler<?>) eventHandler).setSequenceCallback(sequence);
}
batchStartAware =
(eventHandler instanceof BatchStartAware) ? (BatchStartAware) eventHandler : null;
timeoutHandler =
(eventHandler instanceof TimeoutHandler) ? (TimeoutHandler) eventHandler : null;
}
@Override
public Sequence getSequence()
{
return sequence;
}
@Override
public void halt()
{
running.set(HALTED);
sequenceBarrier.alert();
}
@Override
public boolean isRunning()
{
return running.get() != IDLE;
}
/**
* Set a new {@link ExceptionHandler} for handling exceptions propagated out of the {@link BatchEventProcessor}
*
* @param exceptionHandler to replace the existing exceptionHandler.
*/
public void setExceptionHandler(final ExceptionHandler<? super T> exceptionHandler)
{
if (null == exceptionHandler)
{
throw new NullPointerException();
}
this.exceptionHandler = exceptionHandler;
}
/**
* It is ok to have another thread rerun this method after a halt().
*
* @throws IllegalStateException if this object instance is already running in a thread
*/
@Override
public void run()
{
if (running.compareAndSet(IDLE, RUNNING))
{
sequenceBarrier.clearAlert();
notifyStart();
try
{
if (running.get() == RUNNING)
{
processEvents();
}
}
finally
{
notifyShutdown();
running.set(IDLE);
}
}
else
{
// This is a little bit of guess work. The running state could of changed to HALTED by
// this point. However, Java does not have compareAndExchange which is the only way
// to get it exactly correct.
if (running.get() == RUNNING)
{
throw new IllegalStateException("Thread is already running");
}
else
{
earlyExit();
}
}
}
private void processEvents()
{
T event = null;
long nextSequence = sequence.get() + 1L;
while (true)
{
try
{
final long availableSequence = sequenceBarrier.waitFor(nextSequence);
if (batchStartAware != null)
{
batchStartAware.onBatchStart(availableSequence - nextSequence + 1);
}
while (nextSequence <= availableSequence)
{
event = dataProvider.get(nextSequence);
eventHandler.onEvent(event, nextSequence, nextSequence == availableSequence);
nextSequence++;
}
sequence.set(availableSequence);
}
catch (final TimeoutException e)
{
notifyTimeout(sequence.get());
}
catch (final AlertException ex)
{
if (running.get() != RUNNING)
{
break;
}
}
catch (final Throwable ex)
{
exceptionHandler.handleEventException(ex, nextSequence, event);
sequence.set(nextSequence);
nextSequence++;
}
}
}
private void earlyExit()
{
notifyStart();
notifyShutdown();
}
private void notifyTimeout(final long availableSequence)
{
try
{
if (timeoutHandler != null)
{
timeoutHandler.onTimeout(availableSequence);
}
}
catch (Throwable e)
{
exceptionHandler.handleEventException(e, availableSequence, null);
}
}
/**
* Notifies the EventHandler when this processor is starting up
*/
private void notifyStart()
{
if (eventHandler instanceof LifecycleAware)
{
try
{
((LifecycleAware) eventHandler).onStart();
}
catch (final Throwable ex)
{
exceptionHandler.handleOnStartException(ex);
}
}
}
/**
* Notifies the EventHandler immediately prior to this processor shutting down
*/
private void notifyShutdown()
{
if (eventHandler instanceof LifecycleAware)
{
try
{
((LifecycleAware) eventHandler).onShutdown();
}
catch (final Throwable ex)
{
exceptionHandler.handleOnShutdownException(ex);
}
}
}
}
|
src/main/java/com/lmax/disruptor/BatchEventProcessor.java
|
/*
* Copyright 2011 LMAX Ltd.
*
* 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.lmax.disruptor;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Convenience class for handling the batching semantics of consuming entries from a {@link RingBuffer}
* and delegating the available events to an {@link EventHandler}.
* <p>
* If the {@link EventHandler} also implements {@link LifecycleAware} it will be notified just after the thread
* is started and just before the thread is shutdown.
*
* @param <T> event implementation storing the data for sharing during exchange or parallel coordination of an event.
*/
public final class BatchEventProcessor<T>
implements EventProcessor
{
private static final int IDLE = 0;
private static final int HALTED = IDLE + 1;
private static final int RUNNING = HALTED + 1;
private final AtomicInteger running = new AtomicInteger(IDLE);
private ExceptionHandler<? super T> exceptionHandler = new FatalExceptionHandler();
private final DataProvider<T> dataProvider;
private final SequenceBarrier sequenceBarrier;
private final EventHandler<? super T> eventHandler;
private final Sequence sequence = new Sequence(Sequencer.INITIAL_CURSOR_VALUE);
private final TimeoutHandler timeoutHandler;
private final BatchStartAware batchStartAware;
/**
* Construct a {@link EventProcessor} that will automatically track the progress by updating its sequence when
* the {@link EventHandler#onEvent(Object, long, boolean)} method returns.
*
* @param dataProvider to which events are published.
* @param sequenceBarrier on which it is waiting.
* @param eventHandler is the delegate to which events are dispatched.
*/
public BatchEventProcessor(
final DataProvider<T> dataProvider,
final SequenceBarrier sequenceBarrier,
final EventHandler<? super T> eventHandler)
{
this.dataProvider = dataProvider;
this.sequenceBarrier = sequenceBarrier;
this.eventHandler = eventHandler;
if (eventHandler instanceof SequenceReportingEventHandler)
{
((SequenceReportingEventHandler<?>) eventHandler).setSequenceCallback(sequence);
}
batchStartAware =
(eventHandler instanceof BatchStartAware) ? (BatchStartAware) eventHandler : null;
timeoutHandler =
(eventHandler instanceof TimeoutHandler) ? (TimeoutHandler) eventHandler : null;
}
@Override
public Sequence getSequence()
{
return sequence;
}
@Override
public void halt()
{
running.set(HALTED);
sequenceBarrier.alert();
}
@Override
public boolean isRunning()
{
return running.get() != IDLE;
}
/**
* Set a new {@link ExceptionHandler} for handling exceptions propagated out of the {@link BatchEventProcessor}
*
* @param exceptionHandler to replace the existing exceptionHandler.
*/
public void setExceptionHandler(final ExceptionHandler<? super T> exceptionHandler)
{
if (null == exceptionHandler)
{
throw new NullPointerException();
}
this.exceptionHandler = exceptionHandler;
}
/**
* It is ok to have another thread rerun this method after a halt().
*
* @throws IllegalStateException if this object instance is already running in a thread
*/
@Override
public void run()
{
if (running.compareAndSet(IDLE, RUNNING))
{
sequenceBarrier.clearAlert();
notifyStart();
try
{
if (running.get() == RUNNING)
{
processEvents();
}
}
finally
{
notifyShutdown();
running.set(IDLE);
}
}
else
{
// This is a little bit of guess work. The running state could of changed to HALTED by
// this point. However, Java does not have compareAndExchange which is the only way
// to get it exactly correct.
if (running.get() == RUNNING)
{
throw new IllegalStateException("Thread is already running");
}
else
{
earlyExit();
}
}
}
private void processEvents()
{
T event = null;
long nextSequence = sequence.get() + 1L;
while (true)
{
try
{
final long availableSequence = sequenceBarrier.waitFor(nextSequence);
if (batchStartAware != null)
{
batchStartAware.onBatchStart(availableSequence - nextSequence + 1);
}
while (nextSequence <= availableSequence)
{
event = dataProvider.get(nextSequence);
eventHandler.onEvent(event, nextSequence, nextSequence == availableSequence);
nextSequence++;
}
sequence.set(availableSequence);
}
catch (final TimeoutException e)
{
notifyTimeout(sequence.get());
}
catch (final AlertException ex)
{
if (running.get() != RUNNING)
{
break;
}
}
catch (final Throwable ex)
{
exceptionHandler.handleEventException(ex, nextSequence, event);
sequence.set(nextSequence);
nextSequence++;
}
}
}
private void earlyExit()
{
notifyStart();
notifyShutdown();
}
private void notifyTimeout(final long availableSequence)
{
try
{
if (timeoutHandler != null)
{
timeoutHandler.onTimeout(availableSequence);
}
}
catch (Throwable e)
{
exceptionHandler.handleEventException(e, availableSequence, null);
}
}
/**
* Notifies the EventHandler when this processor is starting up
*/
private void notifyStart()
{
if (eventHandler instanceof LifecycleAware)
{
try
{
((LifecycleAware) eventHandler).onStart();
}
catch (final Throwable ex)
{
exceptionHandler.handleOnStartException(ex);
}
}
}
/**
* Notifies the EventHandler immediately prior to this processor shutting down
*/
private void notifyShutdown()
{
if (eventHandler instanceof LifecycleAware)
{
try
{
((LifecycleAware) eventHandler).onShutdown();
}
catch (final Throwable ex)
{
exceptionHandler.handleOnShutdownException(ex);
}
}
}
}
|
Whitespace
|
src/main/java/com/lmax/disruptor/BatchEventProcessor.java
|
Whitespace
|
|
Java
|
apache-2.0
|
63e1f8e71a4982b85e028b8484f9967962e1e0d3
| 0
|
jtablesaw/tablesaw,jtablesaw/tablesaw,jtablesaw/tablesaw
|
/*
* 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 tech.tablesaw.io.saw;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static tech.tablesaw.api.ColumnType.INSTANT;
import static tech.tablesaw.api.ColumnType.TEXT;
import java.time.Instant;
import java.time.LocalDate;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tech.tablesaw.api.BooleanColumn;
import tech.tablesaw.api.DateColumn;
import tech.tablesaw.api.DoubleColumn;
import tech.tablesaw.api.FloatColumn;
import tech.tablesaw.api.InstantColumn;
import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.LongColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;
/** Tests for reading and writing saw files */
class SawStorageTest {
private final Table empty = Table.create("empty table");
private final Table noData =
Table.create("no data", IntColumn.create("empty int"), DoubleColumn.create("empty double"));
private final Table intsOnly =
Table.create(
"Ints only",
IntColumn.indexColumn("index1", 100, 1),
IntColumn.indexColumn("index2", 100, 1));
private final Table intsAndStrings =
Table.create("Ints and strings", IntColumn.indexColumn("index1", 100, 300));
private final Table intsAndText =
Table.create("Ints and text", IntColumn.indexColumn("index1", 100, 300));
private final Table instants =
Table.create(
"Instants",
IntColumn.indexColumn("index1", 100, 300),
InstantColumn.create("Instants", 100));
private static final int COUNT = 5;
private static final String tempDir = System.getProperty("java.io.tmpdir");
private final Table table = Table.create("t");
private final FloatColumn floatColumn = FloatColumn.create("float");
private final StringColumn categoryColumn = StringColumn.create("string");
private final DateColumn localDateColumn = DateColumn.create("date");
private final LongColumn longColumn = LongColumn.create("long");
private final BooleanColumn booleanColumn = BooleanColumn.create("bool");
@BeforeEach
void setUp() {
intsAndStrings.addColumns(intsAndStrings.intColumn("index1").asStringColumn());
intsAndText.addColumns(intsAndText.intColumn("index1").asStringColumn().asTextColumn());
for (int i = 0; i < COUNT; i++) {
floatColumn.append((float) i);
localDateColumn.append(LocalDate.now());
categoryColumn.append("Category " + i);
longColumn.append(i);
booleanColumn.append(i % 2 == 0);
}
table.addColumns(floatColumn);
table.addColumns(localDateColumn);
table.addColumns(categoryColumn);
table.addColumns(longColumn);
table.addColumns(booleanColumn);
instants.instantColumn(1).fillWith((Supplier<Instant>) Instant::now);
}
@Test
void testWriteTable() {
new SawWriter(tempDir + "/zeta", table).write();
Table t = new SawReader(tempDir + "/zeta/t.saw").read();
assertEquals(table.columnCount(), t.columnCount());
assertEquals(table.rowCount(), t.rowCount());
for (int i = 0; i < table.rowCount(); i++) {
assertEquals(categoryColumn.get(i), t.stringColumn("string").get(i));
}
t.sortOn("string"); // exercise the column a bit
}
@Test
void testWriteTable2() {
new SawWriter(tempDir + "/zeta", table).write();
Table t = new SawReader(tempDir + "/zeta/t.saw").read();
assertEquals(table.columnCount(), t.columnCount());
assertEquals(table.rowCount(), t.rowCount());
for (int i = 0; i < table.rowCount(); i++) {
assertEquals(booleanColumn.get(i), t.booleanColumn("bool").get(i));
}
t.sortOn("string"); // exercise the column a bit
}
@Test
void testWriteTableTwice() {
new SawWriter(tempDir + "/mytables2", table).write();
Table t = new SawReader(tempDir + "/mytables2/t.saw").read();
t.floatColumn("float").setName("a float column");
new SawWriter(tempDir + "/mytables2", table);
t = new SawReader(tempDir + "/mytables2/t.saw").read();
assertEquals(table.name(), t.name());
assertEquals(table.rowCount(), t.rowCount());
assertEquals(table.columnCount(), t.columnCount());
}
@Test
void saveEmptyTable() {
String path = new SawWriter(tempDir, empty).write();
Table table = new SawReader(path).read();
assertNotNull(table);
}
@Test
void saveNoDataTable() {
String path = new SawWriter(tempDir, noData).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertTrue(table.columnCount() > 0);
assertTrue(table.isEmpty());
}
@Test
void saveIntsOnly() {
String path = new SawWriter(tempDir, intsOnly).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertEquals(intsOnly.rowCount(), table.rowCount());
}
@Test
void saveIntsAndStrings() {
String path = new SawWriter(tempDir, intsAndStrings).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertEquals(intsAndStrings.rowCount(), table.rowCount());
}
@Test
void saveIntsAndText() {
String path = new SawWriter(tempDir, intsAndText).write();
Table table = new SawReader(path).read();
assertTrue(table.column(1).size() > 0);
assertEquals(TEXT, table.column(1).type());
assertEquals(intsAndText.rowCount(), table.rowCount());
}
@Test
void saveInstants() {
String path = new SawWriter(tempDir, instants).write();
Table table = new SawReader(path).read();
assertEquals(100, table.column(0).size());
assertEquals(INSTANT, table.column(1).type());
assertEquals(instants.rowCount(), table.rowCount());
assertEquals(instants.instantColumn(1).get(20), table.instantColumn(1).get(20));
}
@Test
void bush() throws Exception {
Table bush = Table.read().csv("../data/bush.csv");
String path = new SawWriter("../testoutput/bush", bush).write();
Table table = new SawReader(path).read();
assertEquals(table.column(1).size(), bush.rowCount());
}
@Test
void tornado() throws Exception {
Table tornado = Table.read().csv("../data/tornadoes_1950-2014.csv");
String path = new SawWriter("../testoutput/tornadoes_1950-2014", tornado).write();
Table table = new SawReader(path).read();
assertTrue(table.column(1).size() > 0);
assertEquals(tornado.columnCount(), table.columnCount());
assertEquals(tornado.rowCount(), table.rowCount());
}
@Test
void baseball() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
Table table = new SawReader(path).read();
assertTrue(baseball.column(1).size() > 0);
assertEquals(baseball.columnCount(), table.columnCount());
assertEquals(baseball.rowCount(), table.rowCount());
}
@Test
void metadata() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
assertEquals("1232 rows X 15 cols", new SawReader(path).shape());
assertEquals(1232, new SawReader(path).rowCount());
assertEquals(15, new SawReader(path).columnCount());
assertEquals(baseball.columnNames(), new SawReader(path).columnNames());
assertEquals(baseball.structure().printAll(), new SawReader(path).structure().printAll());
}
@Test
void selectedColumns() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
Table bb2 = new SawReader(path, new ReadOptions().selectedColumns("OBP", "SLG", "BA")).read();
assertEquals(3, bb2.columnCount());
assertTrue(bb2.columnNames().contains("OBP"));
assertTrue(bb2.columnNames().contains("SLG"));
assertTrue(bb2.columnNames().contains("BA"));
assertEquals(baseball.rowCount(), bb2.rowCount());
}
@Test
void noCompression() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path =
new SawWriter(
"../testoutput/baseball",
baseball,
new WriteOptions().compressionType(CompressionType.NONE))
.write();
Table bb2 = new SawReader(path, new ReadOptions().selectedColumns("OBP", "SLG", "BA")).read();
assertEquals(3, bb2.columnCount());
assertTrue(bb2.columnNames().contains("OBP"));
assertTrue(bb2.columnNames().contains("SLG"));
assertTrue(bb2.columnNames().contains("BA"));
assertEquals(baseball.rowCount(), bb2.rowCount());
}
@Test
void boston_roberies() throws Exception {
Table robereries = Table.read().csv("../data/boston-robberies.csv");
String path = new SawWriter("../testoutput/boston_robberies", robereries).write();
Table table = new SawReader(path).read();
assertEquals(robereries.columnCount(), table.columnCount());
assertEquals(robereries.rowCount(), table.rowCount());
}
@Test
void sacramento() throws Exception {
Table sacramento = Table.read().csv("../data/sacramento_real_estate_transactions.csv");
String path = new SawWriter("../testoutput/sacramento", sacramento).write();
Table table = new SawReader(path).read();
assertEquals(sacramento.columnCount(), table.columnCount());
assertEquals(sacramento.rowCount(), table.rowCount());
}
@Test
void test_wines() throws Exception {
Table wines = Table.read().csv("../data/test_wines.csv");
String path = new SawWriter("../testoutput/test_wines", wines).write();
Table table = new SawReader(path).read();
assertEquals(wines.columnCount(), table.columnCount());
assertEquals(wines.rowCount(), table.rowCount());
assertEquals(
wines.stringColumn("name").getDictionary(), table.stringColumn("name").getDictionary());
new SawWriter("../testoutput/test_wines", table);
Table table1 = new SawReader(path).read();
assertEquals(
wines.stringColumn("name").getDictionary(), table1.stringColumn("name").getDictionary());
}
@Test
void saveIntsLarger() {
final Table intsOnlyLarger =
Table.create(
"Ints only, larger",
IntColumn.indexColumn("index1", 10_000_000, 1),
IntColumn.indexColumn("index2", 10_000_000, 1));
String path = new SawWriter(tempDir, intsOnlyLarger).write();
Table table = new SawReader(path).read();
assertEquals(10_000_000, table.rowCount());
}
@Test
void saveStrings() {
StringColumn index2 = StringColumn.create("index2");
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 1000; i++) {
index2.append(String.valueOf(i));
}
}
StringColumn index3 = StringColumn.create("index3");
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100000; i++) {
index3.append(String.valueOf(i));
}
}
final Table wines =
Table.create(
"million ints",
IntColumn.indexColumn("index1", 1_000_000, 1).asStringColumn().setName("index1"),
index2,
index3);
String path = new SawWriter(tempDir, wines).write();
Table table = new SawReader(path).read();
assertEquals(wines.columnCount(), table.columnCount());
assertEquals(wines.rowCount(), table.rowCount());
assertEquals(
wines.stringColumn("index2").getDictionary(), table.stringColumn("index2").getDictionary());
new SawWriter(tempDir, table);
Table table1 = new SawReader(path).read();
assertEquals(
wines.stringColumn("index1").getDictionary(),
table1.stringColumn("index1").getDictionary());
assertEquals(
wines.stringColumn("index2").getDictionary(),
table1.stringColumn("index2").getDictionary());
}
}
|
saw/src/test/java/tech/tablesaw/io/saw/SawStorageTest.java
|
/*
* 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 tech.tablesaw.io.saw;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static tech.tablesaw.api.ColumnType.INSTANT;
import static tech.tablesaw.api.ColumnType.TEXT;
import java.time.Instant;
import java.time.LocalDate;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tech.tablesaw.api.BooleanColumn;
import tech.tablesaw.api.DateColumn;
import tech.tablesaw.api.DoubleColumn;
import tech.tablesaw.api.FloatColumn;
import tech.tablesaw.api.InstantColumn;
import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.LongColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;
/** Tests for reading and writing saw files */
class SawStorageTest {
private final Table empty = Table.create("empty table");
private final Table noData =
Table.create("no data", IntColumn.create("empty int"), DoubleColumn.create("empty double"));
private final Table intsOnly =
Table.create(
"Ints only",
IntColumn.indexColumn("index1", 100, 1),
IntColumn.indexColumn("index2", 100, 1));
private final Table intsAndStrings =
Table.create("Ints and strings", IntColumn.indexColumn("index1", 100, 300));
private final Table intsAndText =
Table.create("Ints and text", IntColumn.indexColumn("index1", 100, 300));
private final Table instants =
Table.create(
"Instants",
IntColumn.indexColumn("index1", 100, 300),
InstantColumn.create("Instants", 100));
private static final int COUNT = 5;
private static final String tempDir = System.getProperty("java.io.tmpdir");
private final Table table = Table.create("t");
private final FloatColumn floatColumn = FloatColumn.create("float");
private final StringColumn categoryColumn = StringColumn.create("string");
private final DateColumn localDateColumn = DateColumn.create("date");
private final LongColumn longColumn = LongColumn.create("long");
private final BooleanColumn booleanColumn = BooleanColumn.create("bool");
@BeforeEach
void setUp() {
intsAndStrings.addColumns(intsAndStrings.intColumn("index1").asStringColumn());
intsAndText.addColumns(intsAndText.intColumn("index1").asStringColumn().asTextColumn());
for (int i = 0; i < COUNT; i++) {
floatColumn.append((float) i);
localDateColumn.append(LocalDate.now());
categoryColumn.append("Category " + i);
longColumn.append(i);
booleanColumn.append(i % 2 == 0);
}
table.addColumns(floatColumn);
table.addColumns(localDateColumn);
table.addColumns(categoryColumn);
table.addColumns(longColumn);
table.addColumns(booleanColumn);
instants.instantColumn(1).fillWith((Supplier<Instant>) Instant::now);
}
@Test
void testWriteTable() {
new SawWriter(tempDir + "/zeta", table);
Table t = new SawReader(tempDir + "/zeta/t.saw").read();
assertEquals(table.columnCount(), t.columnCount());
assertEquals(table.rowCount(), t.rowCount());
for (int i = 0; i < table.rowCount(); i++) {
assertEquals(categoryColumn.get(i), t.stringColumn("string").get(i));
}
t.sortOn("string"); // exercise the column a bit
}
@Test
void testWriteTable2() {
new SawWriter(tempDir + "/zeta", table);
Table t = new SawReader(tempDir + "/zeta/t.saw").read();
assertEquals(table.columnCount(), t.columnCount());
assertEquals(table.rowCount(), t.rowCount());
for (int i = 0; i < table.rowCount(); i++) {
assertEquals(booleanColumn.get(i), t.booleanColumn("bool").get(i));
}
t.sortOn("string"); // exercise the column a bit
}
@Test
void testWriteTableTwice() {
new SawWriter(tempDir + "/mytables2", table);
Table t = new SawReader(tempDir + "/mytables2/t.saw").read();
t.floatColumn("float").setName("a float column");
new SawWriter(tempDir + "/mytables2", table);
t = new SawReader(tempDir + "/mytables2/t.saw").read();
assertEquals(table.name(), t.name());
assertEquals(table.rowCount(), t.rowCount());
assertEquals(table.columnCount(), t.columnCount());
}
@Test
void saveEmptyTable() {
String path = new SawWriter(tempDir, empty).write();
Table table = new SawReader(path).read();
assertNotNull(table);
}
@Test
void saveNoDataTable() {
String path = new SawWriter(tempDir, noData).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertTrue(table.columnCount() > 0);
assertTrue(table.isEmpty());
}
@Test
void saveIntsOnly() {
String path = new SawWriter(tempDir, intsOnly).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertEquals(intsOnly.rowCount(), table.rowCount());
}
@Test
void saveIntsAndStrings() {
String path = new SawWriter(tempDir, intsAndStrings).write();
Table table = new SawReader(path).read();
assertNotNull(table);
assertEquals(intsAndStrings.rowCount(), table.rowCount());
}
@Test
void saveIntsAndText() {
String path = new SawWriter(tempDir, intsAndText).write();
Table table = new SawReader(path).read();
assertTrue(table.column(1).size() > 0);
assertEquals(TEXT, table.column(1).type());
assertEquals(intsAndText.rowCount(), table.rowCount());
}
@Test
void saveInstants() {
String path = new SawWriter(tempDir, instants).write();
Table table = new SawReader(path).read();
assertEquals(100, table.column(0).size());
assertEquals(INSTANT, table.column(1).type());
assertEquals(instants.rowCount(), table.rowCount());
assertEquals(instants.instantColumn(1).get(20), table.instantColumn(1).get(20));
}
@Test
void bush() throws Exception {
Table bush = Table.read().csv("../data/bush.csv");
String path = new SawWriter("../testoutput/bush", bush).write();
Table table = new SawReader(path).read();
assertEquals(table.column(1).size(), bush.rowCount());
}
@Test
void tornado() throws Exception {
Table tornado = Table.read().csv("../data/tornadoes_1950-2014.csv");
String path = new SawWriter("../testoutput/tornadoes_1950-2014", tornado).write();
Table table = new SawReader(path).read();
assertTrue(table.column(1).size() > 0);
assertEquals(tornado.columnCount(), table.columnCount());
assertEquals(tornado.rowCount(), table.rowCount());
}
@Test
void baseball() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
Table table = new SawReader(path).read();
assertTrue(baseball.column(1).size() > 0);
assertEquals(baseball.columnCount(), table.columnCount());
assertEquals(baseball.rowCount(), table.rowCount());
}
@Test
void metadata() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
assertEquals("1232 rows X 15 cols", new SawReader(path).shape());
assertEquals(1232, new SawReader(path).rowCount());
assertEquals(15, new SawReader(path).columnCount());
assertEquals(baseball.columnNames(), new SawReader(path).columnNames());
assertEquals(baseball.structure().printAll(), new SawReader(path).structure().printAll());
}
@Test
void selectedColumns() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path = new SawWriter("../testoutput/baseball", baseball).write();
Table bb2 = new SawReader(path, new ReadOptions().selectedColumns("OBP", "SLG", "BA")).read();
assertEquals(3, bb2.columnCount());
assertTrue(bb2.columnNames().contains("OBP"));
assertTrue(bb2.columnNames().contains("SLG"));
assertTrue(bb2.columnNames().contains("BA"));
assertEquals(baseball.rowCount(), bb2.rowCount());
}
@Test
void noCompression() throws Exception {
Table baseball = Table.read().csv("../data/baseball.csv");
String path =
new SawWriter(
"../testoutput/baseball",
baseball,
new WriteOptions().compressionType(CompressionType.NONE))
.write();
Table bb2 = new SawReader(path, new ReadOptions().selectedColumns("OBP", "SLG", "BA")).read();
assertEquals(3, bb2.columnCount());
assertTrue(bb2.columnNames().contains("OBP"));
assertTrue(bb2.columnNames().contains("SLG"));
assertTrue(bb2.columnNames().contains("BA"));
assertEquals(baseball.rowCount(), bb2.rowCount());
}
@Test
void boston_roberies() throws Exception {
Table robereries = Table.read().csv("../data/boston-robberies.csv");
String path = new SawWriter("../testoutput/boston_robberies", robereries).write();
Table table = new SawReader(path).read();
assertEquals(robereries.columnCount(), table.columnCount());
assertEquals(robereries.rowCount(), table.rowCount());
}
@Test
void sacramento() throws Exception {
Table sacramento = Table.read().csv("../data/sacramento_real_estate_transactions.csv");
String path = new SawWriter("../testoutput/sacramento", sacramento).write();
Table table = new SawReader(path).read();
assertEquals(sacramento.columnCount(), table.columnCount());
assertEquals(sacramento.rowCount(), table.rowCount());
}
@Test
void test_wines() throws Exception {
Table wines = Table.read().csv("../data/test_wines.csv");
String path = new SawWriter("../testoutput/test_wines", wines).write();
Table table = new SawReader(path).read();
assertEquals(wines.columnCount(), table.columnCount());
assertEquals(wines.rowCount(), table.rowCount());
assertEquals(
wines.stringColumn("name").getDictionary(), table.stringColumn("name").getDictionary());
new SawWriter("../testoutput/test_wines", table);
Table table1 = new SawReader(path).read();
assertEquals(
wines.stringColumn("name").getDictionary(), table1.stringColumn("name").getDictionary());
}
@Test
void saveIntsLarger() {
final Table intsOnlyLarger =
Table.create(
"Ints only, larger",
IntColumn.indexColumn("index1", 10_000_000, 1),
IntColumn.indexColumn("index2", 10_000_000, 1));
String path = new SawWriter(tempDir, intsOnlyLarger).write();
Table table = new SawReader(path).read();
assertEquals(10_000_000, table.rowCount());
}
@Test
void saveStrings() {
StringColumn index2 = StringColumn.create("index2");
for (int j = 0; j < 1000; j++) {
for (int i = 0; i < 1000; i++) {
index2.append(String.valueOf(i));
}
}
StringColumn index3 = StringColumn.create("index3");
for (int j = 0; j < 10; j++) {
for (int i = 0; i < 100000; i++) {
index3.append(String.valueOf(i));
}
}
final Table wines =
Table.create(
"million ints",
IntColumn.indexColumn("index1", 1_000_000, 1).asStringColumn().setName("index1"),
index2,
index3);
String path = new SawWriter(tempDir, wines).write();
Table table = new SawReader(path).read();
assertEquals(wines.columnCount(), table.columnCount());
assertEquals(wines.rowCount(), table.rowCount());
assertEquals(
wines.stringColumn("index2").getDictionary(), table.stringColumn("index2").getDictionary());
new SawWriter(tempDir, table);
Table table1 = new SawReader(path).read();
assertEquals(
wines.stringColumn("index1").getDictionary(),
table1.stringColumn("index1").getDictionary());
assertEquals(
wines.stringColumn("index2").getDictionary(),
table1.stringColumn("index2").getDictionary());
}
}
|
Update SawStorageTest.java (#833)
|
saw/src/test/java/tech/tablesaw/io/saw/SawStorageTest.java
|
Update SawStorageTest.java (#833)
|
|
Java
|
apache-2.0
|
ac9318ccbb7bd9a35871136d4ab7084577a20871
| 0
|
usc-isi-i2/image-metadata-enhancement,usc-isi-i2/image-metadata-enhancement,usc-isi-i2/image-metadata-enhancement,usc-isi-i2/image-metadata-enhancement
|
package edu.isi.karma.ugde.osm;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/*
*
* Java Program to download and extract building and street information from OSM data
*
*
*/
public class osmFetch {
//The url to download OSM data
private static String url = "";
private static String OSM_API_KEY="b8uBAGZowqebVTadpoak56zmANQtQyUA";
//The string of OSM data in xml format
private static String xmlResult = "";
private int PRETTY_PRINT_INDENT_FACTOR = 4;
private static String minLon = "";
private static String minLat = "";
private static String maxLon = "";
private static String maxLat = "";
private static String type = "";
private static DocumentBuilderFactory builderFactory, builderFactoryCreator;
private static DocumentBuilder builder, builderCreator;
private static Document document, documentCreate;
private static Element osmroot, root;
//The hashMap used for fast retrieving building information needed in street information extraction, with key as node id and value as node entity
private static HashMap hashMapNode;
//The file path to save original OSM xml data
private static String osmFile_path ="GET_OPENSTREETMAP_KML.xml";
//The file path to save original OSM xml data only including street information
private static String osmFilePathStreet= "OPENSTREETMAP_STREET.xml";
//The file path to save original OSM xml data only including building information
private static String osmFilePathNode = "OPENSTREETMAP_BUILDING.xml";
//The file path to save complete original OSM xml data
private static String osmFilePathAll="OPENSTREETMAP_ALL.xml";
public static void main(String[] args) throws ClientProtocolException, IOException{
// System.out.println(args[0]+" "+args[1]+" "+args[2]+" "+args[3]+" "+args[4]);
Scanner scanf = new Scanner(System.in);
// System.out.println("The order of input parameters are longN, latE, longS, latW and type");
//The order of input parameters are longN, latE, longS, latW and type
minLon = args[0];
minLat = args[1];
maxLon = args[2];
maxLat = args[3];
type = args[4];
System.out.println(minLon+" "+minLat+" "+maxLon+" "+maxLat+" "+type);
url = "bbox=" + minLon+","+minLat+","+maxLon+","+maxLat;
url += ("&key=" +OSM_API_KEY);
//Download original OSM data
outputToOSM(url);
System.out.println("~~~");
builderFactory = DocumentBuilderFactory.newInstance();
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
document = builder.parse(osmFile_path);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element rootElement = document.getDocumentElement();
//NodeList datastructure to save node information of OSM data
NodeList nodeElements = rootElement.getElementsByTagName("node");
//NodeList datastructure to save street information of OSM data
NodeList wayElements = rootElement.getElementsByTagName("way");
//NodeList datastructure to save relation information between buildings and streets of OSM data
NodeList relationElements = rootElement.getElementsByTagName("relation");
//Save all nodes information into hashmap
initHashMapNode(nodeElements);
builderFactoryCreator = DocumentBuilderFactory.newInstance();
try {
builderCreator = builderFactoryCreator.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
documentCreate = builderCreator.newDocument();
osmroot = documentCreate.createElement("osm");
root = documentCreate.createElement("kml");
root.setAttribute("xmlns", "http://www.opengis.net/kml/2.2");
osmroot.appendChild(root);
documentCreate.appendChild(osmroot);
//Invoke the street information extraction if query type is street
if (type.equalsIgnoreCase("streets") || type.equalsIgnoreCase("street")){
String xmlWays = "";
System.out.println(" --- ");
try {
wayExtraction(wayElements, nodeElements);
// relationExtraction(relationElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(type.equalsIgnoreCase("building") || type.equalsIgnoreCase("buildings")){
//Invoke the building information extraction if query type is buildings
String xmlNodes = "";
System.out.println(" @@@ ");
try {
nodeExtraction(nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//Invoke both the street and building information extraction if query type is "all"
try {
wayExtraction(wayElements, nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
nodeExtraction(nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// PrintWriter out = response.getWriter();
// out.println(xmlResult);
}
/*
*Function: Initialize the hashmap to save the node information with key as node id and value as node entity
*Input: The list of all the node information of OSM data downloaded
*Output: Null
*/
public static void initHashMapNode(NodeList nodeElements){
hashMapNode = new HashMap();
for (int i = 0 ; i < nodeElements.getLength(); i++) {
Element node = (Element)nodeElements.item(i);
String id = node.getAttribute("id");
hashMapNode.put(id, node);
}
}
/*
*Function: Extract only building information among all the node information and then save it into xml file
*Input: The list of all the node information of OSM data downloaded
*Algorithm: Enumerate all the nodes in the list, only consider those that have tags and the k value of all the tags does not contain "way" substring as buildings
* Only extract state, city, county, and name information of the street;
* To identify state name, find v value of tags whose k value contains both "state(s)" or "province(s)" and "addr" or "tiger" substring;
* To identify city name, find v value of tags whose k value contains both "city" and "addr" or "tiger" substring;
* To identify county name, find v value of tags whose k value contains both "county" and "addr" or "tiger" substring
*Output: Null
*/
public static void nodeExtraction(NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmBuildings = documentCreate.createElement("Document");
/* osmBuildings.setAttribute("xmlns", "http://www.myphotos.org");
osmBuildings.setAttribute("xmlns:kml", "http://www.opengis.net/kml");
osmBuildings.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
*/
System.out.println(" # of nodes = " + nodeElements.getLength());
for (int i = 0 ; i < nodeElements.getLength(); i++) {
Element node = (Element)nodeElements.item(i);
NodeList tagElements = node.getElementsByTagName("tag");
boolean isbuildings = true;
if(tagElements.getLength() == 0)
isbuildings = false;
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
isbuildings = false;
break;
}
}
if(isbuildings){
Element osmBuliding = documentCreate.createElement("Placemark");
osmBuliding.setAttribute("id", node.getAttribute("id"));
String buildingName = "";
String cityName = "";
String countyName = "";
String stateName = "";
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("name") || k.contains("source")){
buildingName = v;
}
if(k.contains("state") || k.contains("states") || k.contains("province") || k.contains("provinces") && (k.contains("addr") || k.contains("tiger"))){
stateName = v;
}
if(k.contains("city") && (k.contains("addr") || k.contains("tiger"))){
cityName = v;
}
if(k.contains("county") && (k.contains("addr") || k.contains("tiger"))){
countyName = v;
}
}
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(buildingName));
osmBuliding.appendChild(kmlname);
/* Element address = documentCreate.createElement("Address");
kmlname.appendChild(documentCreate.createTextNode(buildingName));
osmBuliding.appendChild(address);
*/
Element cityname = documentCreate.createElement("CityName");
cityname.appendChild(documentCreate.createTextNode(cityName));
osmBuliding.appendChild(cityname);
Element countyname = documentCreate.createElement("CountyName");
countyname.appendChild(documentCreate.createTextNode(countyName));
osmBuliding.appendChild(countyname);
Element statename = documentCreate.createElement("StateName");
statename.appendChild(documentCreate.createTextNode(stateName));
osmBuliding.appendChild(statename);
Element kmltype = documentCreate.createElement("Type");
kmltype.appendChild(documentCreate.createTextNode("building"));
osmBuliding.appendChild(kmltype);
// osmBuliding.setAttribute("name", buildingName);
System.out.println(node.getAttribute("id") + " " + buildingName);
// Element kml = documentCreate.createElement("Point");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
// Element kmlcoordinate = documentCreate.createElement("coordinates");
CDATASection cdata = documentCreate.createCDATASection("");
Element kmlgeometry = documentCreate.createElement("KmlGeometry");
String pointValue = "<Point>";
//Reversing lat long output format
//String coordinate = ""+node.getAttribute("lat")+","+node.getAttribute("lon");
String coordinate = ""+node.getAttribute("lon")+","+node.getAttribute("lat");
// kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
// kml.appendChild(kmlcoordinate);
pointValue += "<coordinates>"+coordinate+"</coordinates>";
pointValue += "</Point>";
cdata.appendData(pointValue);
kmlgeometry.appendChild(cdata);
osmBuliding.appendChild(kmlgeometry);
osmBuildings.appendChild(osmBuliding);
}
}
root.appendChild(osmBuildings);
//Save the building information into xml file
CreateFile();
}
/*
*Function: Extract street information and then save it into xml file
*Input: The list of all the street information of OSM data downloaded
*Algorithm: Enumerate all the streets in the list, and for each street, enumerate all the nodes in its node list;
* Only extract state, city, county, name and type information of the street;
* To identify state name, find v value of tags whose k value contains both "state(s)" or "province(s)" and "addr" or "tiger" substring;
* To identify city name, find v value of tags whose k value contains both "city" and "addr" or "tiger" substring;
* To identify county name, find v value of tags whose k value contains both "county" and "addr" or "tiger" substring
*Output: Null
*/
public static void wayExtraction(NodeList wayElements, NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmStreets = documentCreate.createElement("Document");
/* osmStreets.setAttribute("xmlns", "http://www.myphotos.org");
osmStreets.setAttribute("xmlns:kml", "http://www.opengis.net/kml");
osmStreets.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
*/
System.out.println(" # of ways = " + wayElements.getLength());
for (int i = 0 ; i < wayElements.getLength(); i++) {
Element way = (Element)wayElements.item(i);
NodeList ndElements = way.getElementsByTagName("nd");
NodeList tagElements = way.getElementsByTagName("tag");
String wayName = "", wayType = "";
String cityName = "";
String countyName = "";
String stateName = "";
String wayId = way.getAttribute("id");
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
wayType = k;
}
if(k.contains("name")){
wayName = v;
}
if(k.contains("state") || k.contains("states") || k.contains("province") || k.contains("provinces")
&& (k.contains("addr") || k.contains("tiger"))){
stateName = v;
}
if(k.contains("city") && (k.contains("addr") || k.contains("tiger"))){
cityName = v;
}
if(k.contains("county") && (k.contains("addr") || k.contains("tiger"))){
countyName = v;
}
}
Element osmStreet = documentCreate.createElement("Placemark");
osmStreet.setAttribute("id", wayId);
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(wayName));
osmStreet.appendChild(kmlname);
Element cityname = documentCreate.createElement("CityName");
cityname.appendChild(documentCreate.createTextNode(cityName));
osmStreet.appendChild(cityname);
Element countyname = documentCreate.createElement("CountyName");
countyname.appendChild(documentCreate.createTextNode(countyName));
osmStreet.appendChild(countyname);
Element statename = documentCreate.createElement("StateName");
statename.appendChild(documentCreate.createTextNode(stateName));
osmStreet.appendChild(statename);
Element kmltype = documentCreate.createElement("Type");
//http://examples.javacodegeeks.com/core-java/xml/dom/add-cdata-section-to-dom-document/
//documentCreate.createCDATASection(arg0)
kmltype.appendChild(documentCreate.createTextNode(wayType));
osmStreet.appendChild(kmltype);
// osmStreet.setAttribute("type", wayType);
System.out.println(wayId + " " + wayName + " " + wayType);
CDATASection cdata = documentCreate.createCDATASection("");
Element kmlgeometry = documentCreate.createElement("KmlGeometry");
// Element kml = documentCreate.createElement("LineString");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
// Element kmlcoordinate = documentCreate.createElement("coordinates");
boolean firstNd = true;
String lineStringValue = "<LineString>";
String coordinate = "";
for(int j = 0; j < ndElements.getLength(); ++ j){
Element nd = (Element)ndElements.item(j);
String id = nd.getAttribute("ref");
// Ids.add(id);
if(hashMapNode.containsKey(id)){
Element node = (Element) hashMapNode.get(id);
String lat = node.getAttribute("lat");
String lon = node.getAttribute("lon");
if(!firstNd)
coordinate += " ";
//reversing lat long output format
//coordinate += lat+","+lon+",0";
coordinate += lon+","+lat+",0";
firstNd = false;
}
}
lineStringValue += "<coordinates>"+coordinate+"</coordinates>";
lineStringValue += "</LineString>";
// kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
// kml.appendChild(kmlcoordinate);
cdata.appendData(lineStringValue);
// cdata.appendChild(kml);
kmlgeometry.appendChild(cdata);
osmStreet.appendChild(kmlgeometry);
osmStreets.appendChild(osmStreet);
}
root.appendChild(osmStreets);
//Save the street information into xml file
CreateFile();
}
public static void relationExtraction(NodeList wayElements, NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmStreets = documentCreate.createElement("Document");
System.out.println(" # of ways = " + wayElements.getLength());
for (int i = 0 ; i < wayElements.getLength(); i++) {
Element way = (Element)wayElements.item(i);
NodeList ndElements = way.getElementsByTagName("nd");
NodeList tagElements = way.getElementsByTagName("tag");
String wayName = "", wayType = "";
String wayId = way.getAttribute("id");
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
wayType = k;
}
if(k.contains("name")){
wayName = v;
}
}
Element osmStreet = documentCreate.createElement("Placemark");
osmStreet.setAttribute("id", wayId);
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(wayName));
osmStreet.appendChild(kmlname);
Element kmltype = documentCreate.createElement("Type");
kmltype.appendChild(documentCreate.createTextNode(wayType));
osmStreet.appendChild(kmltype);
// osmStreet.setAttribute("type", wayType);
System.out.println(wayId + " " + wayName + " " + wayType);
Element kml = documentCreate.createElement("LineString");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
Element kmlcoordinate = documentCreate.createElement("coordinates");
boolean firstNd = true;
String coordinate = "";
Set<String> Ids = new HashSet<String>();
for(int j = 0; j < ndElements.getLength(); ++ j){
Element nd = (Element)ndElements.item(j);
String id = nd.getAttribute("ref");
Ids.add(id);
}
for(int j = 0; j < nodeElements.getLength(); ++ j){
Element node = (Element)nodeElements.item(j);
String id = node.getAttribute("id");
if(Ids.contains(id)){
String lat = node.getAttribute("lat");
String lon = node.getAttribute("lon");
if(!firstNd)
coordinate += " ";
//reversing output format
//coordinate += lat+","+lon+",0";
coordinate += lon+","+lat+",0";
firstNd = false;
}
}
kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
kml.appendChild(kmlcoordinate);
osmStreet.appendChild(kml);
osmStreets.appendChild(osmStreet);
}
root.appendChild(osmStreets);
CreateFile();
}
/*
*Function: Download the original OSM data of xml format and save it in the local folder
*Input : The url of parameters for OSM xapi
*Output : Null
*/
private static void outputToOSM(String urls) throws ClientProtocolException, IOException {
//this.url = "'http://open.mapquestapi.com/xapi/api/0.6/map?bbox=" + url; //Extract normal size data;
url = "http://open.mapquestapi.com/xapi/api/0.6/map?" + urls; //Extract bigger size data;
System.out.println("this.url="+url);
DefaultHttpClient client = new DefaultHttpClient();
//Use the Http Get method to download the OSM data from given
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
xmlResult = EntityUtils.toString(entity);
FileOutputStream fout = new FileOutputStream(osmFile_path);
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, "utf-8");
out.write(xmlResult);
out.close();
}
/*
*Function: Save the extracted information into a local xml file
*Input : Null
*Output : Null
*/
private static void CreateFile() throws FileNotFoundException, TransformerException{
PrintWriter pw;
if(type.equalsIgnoreCase("street") || type.equalsIgnoreCase("streets")){
pw = new PrintWriter(new FileOutputStream(osmFilePathStreet));
}else if(type.equalsIgnoreCase("building") || type.equalsIgnoreCase("buildings")){
pw = new PrintWriter(new FileOutputStream(osmFilePathNode));
}else{
pw = new PrintWriter(new FileOutputStream(osmFilePathAll));
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(documentCreate);
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
xmlResult = writer.toString();
System.out.println(xmlResult);
pw.println(xmlResult);
pw.flush();
pw.close();
// System.out.println(""+result.toString());
// StringWriter writer = new StringWriter();
// result = new StreamResult(writer);
// transformer.transform(source, result);
}
}
|
scripts/src/main/java/edu/isi/karma/ugde/osm/osmFetch.java
|
package edu.isi.karma.ugde.osm;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/*
*
* Java Program to download and extract building and street information from OSM data
*
*
*/
public class osmFetch {
//The url to download OSM data
private static String url = "";
//The string of OSM data in xml format
private static String xmlResult = "";
private int PRETTY_PRINT_INDENT_FACTOR = 4;
private static String minLon = "";
private static String minLat = "";
private static String maxLon = "";
private static String maxLat = "";
private static String type = "";
private static DocumentBuilderFactory builderFactory, builderFactoryCreator;
private static DocumentBuilder builder, builderCreator;
private static Document document, documentCreate;
private static Element osmroot, root;
//The hashMap used for fast retrieving building information needed in street information extraction, with key as node id and value as node entity
private static HashMap hashMapNode;
//The file path to save original OSM xml data
private static String osmFile_path ="GET_OPENSTREETMAP_KML.xml";
//The file path to save original OSM xml data only including street information
private static String osmFilePathStreet= "OPENSTREETMAP_STREET.xml";
//The file path to save original OSM xml data only including building information
private static String osmFilePathNode = "OPENSTREETMAP_BUILDING.xml";
//The file path to save complete original OSM xml data
private static String osmFilePathAll="OPENSTREETMAP_ALL.xml";
public static void main(String[] args) throws ClientProtocolException, IOException{
// System.out.println(args[0]+" "+args[1]+" "+args[2]+" "+args[3]+" "+args[4]);
Scanner scanf = new Scanner(System.in);
// System.out.println("The order of input parameters are longN, latE, longS, latW and type");
//The order of input parameters are longN, latE, longS, latW and type
minLon = args[0];
minLat = args[1];
maxLon = args[2];
maxLat = args[3];
type = args[4];
System.out.println(minLon+" "+minLat+" "+maxLon+" "+maxLat+" "+type);
url = "bbox=" + minLon+","+minLat+","+maxLon+","+maxLat;
//Download original OSM data
outputToOSM(url);
System.out.println("~~~");
builderFactory = DocumentBuilderFactory.newInstance();
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
document = builder.parse(osmFile_path);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element rootElement = document.getDocumentElement();
//NodeList datastructure to save node information of OSM data
NodeList nodeElements = rootElement.getElementsByTagName("node");
//NodeList datastructure to save street information of OSM data
NodeList wayElements = rootElement.getElementsByTagName("way");
//NodeList datastructure to save relation information between buildings and streets of OSM data
NodeList relationElements = rootElement.getElementsByTagName("relation");
//Save all nodes information into hashmap
initHashMapNode(nodeElements);
builderFactoryCreator = DocumentBuilderFactory.newInstance();
try {
builderCreator = builderFactoryCreator.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
documentCreate = builderCreator.newDocument();
osmroot = documentCreate.createElement("osm");
root = documentCreate.createElement("kml");
root.setAttribute("xmlns", "http://www.opengis.net/kml/2.2");
osmroot.appendChild(root);
documentCreate.appendChild(osmroot);
//Invoke the street information extraction if query type is street
if (type.equalsIgnoreCase("streets") || type.equalsIgnoreCase("street")){
String xmlWays = "";
System.out.println(" --- ");
try {
wayExtraction(wayElements, nodeElements);
// relationExtraction(relationElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(type.equalsIgnoreCase("building") || type.equalsIgnoreCase("buildings")){
//Invoke the building information extraction if query type is buildings
String xmlNodes = "";
System.out.println(" @@@ ");
try {
nodeExtraction(nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
//Invoke both the street and building information extraction if query type is "all"
try {
wayExtraction(wayElements, nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
nodeExtraction(nodeElements);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// PrintWriter out = response.getWriter();
// out.println(xmlResult);
}
/*
*Function: Initialize the hashmap to save the node information with key as node id and value as node entity
*Input: The list of all the node information of OSM data downloaded
*Output: Null
*/
public static void initHashMapNode(NodeList nodeElements){
hashMapNode = new HashMap();
for (int i = 0 ; i < nodeElements.getLength(); i++) {
Element node = (Element)nodeElements.item(i);
String id = node.getAttribute("id");
hashMapNode.put(id, node);
}
}
/*
*Function: Extract only building information among all the node information and then save it into xml file
*Input: The list of all the node information of OSM data downloaded
*Algorithm: Enumerate all the nodes in the list, only consider those that have tags and the k value of all the tags does not contain "way" substring as buildings
* Only extract state, city, county, and name information of the street;
* To identify state name, find v value of tags whose k value contains both "state(s)" or "province(s)" and "addr" or "tiger" substring;
* To identify city name, find v value of tags whose k value contains both "city" and "addr" or "tiger" substring;
* To identify county name, find v value of tags whose k value contains both "county" and "addr" or "tiger" substring
*Output: Null
*/
public static void nodeExtraction(NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmBuildings = documentCreate.createElement("Document");
/* osmBuildings.setAttribute("xmlns", "http://www.myphotos.org");
osmBuildings.setAttribute("xmlns:kml", "http://www.opengis.net/kml");
osmBuildings.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
*/
System.out.println(" # of nodes = " + nodeElements.getLength());
for (int i = 0 ; i < nodeElements.getLength(); i++) {
Element node = (Element)nodeElements.item(i);
NodeList tagElements = node.getElementsByTagName("tag");
boolean isbuildings = true;
if(tagElements.getLength() == 0)
isbuildings = false;
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
isbuildings = false;
break;
}
}
if(isbuildings){
Element osmBuliding = documentCreate.createElement("Placemark");
osmBuliding.setAttribute("id", node.getAttribute("id"));
String buildingName = "";
String cityName = "";
String countyName = "";
String stateName = "";
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("name") || k.contains("source")){
buildingName = v;
}
if(k.contains("state") || k.contains("states") || k.contains("province") || k.contains("provinces") && (k.contains("addr") || k.contains("tiger"))){
stateName = v;
}
if(k.contains("city") && (k.contains("addr") || k.contains("tiger"))){
cityName = v;
}
if(k.contains("county") && (k.contains("addr") || k.contains("tiger"))){
countyName = v;
}
}
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(buildingName));
osmBuliding.appendChild(kmlname);
/* Element address = documentCreate.createElement("Address");
kmlname.appendChild(documentCreate.createTextNode(buildingName));
osmBuliding.appendChild(address);
*/
Element cityname = documentCreate.createElement("CityName");
cityname.appendChild(documentCreate.createTextNode(cityName));
osmBuliding.appendChild(cityname);
Element countyname = documentCreate.createElement("CountyName");
countyname.appendChild(documentCreate.createTextNode(countyName));
osmBuliding.appendChild(countyname);
Element statename = documentCreate.createElement("StateName");
statename.appendChild(documentCreate.createTextNode(stateName));
osmBuliding.appendChild(statename);
Element kmltype = documentCreate.createElement("Type");
kmltype.appendChild(documentCreate.createTextNode("building"));
osmBuliding.appendChild(kmltype);
// osmBuliding.setAttribute("name", buildingName);
System.out.println(node.getAttribute("id") + " " + buildingName);
// Element kml = documentCreate.createElement("Point");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
// Element kmlcoordinate = documentCreate.createElement("coordinates");
CDATASection cdata = documentCreate.createCDATASection("");
Element kmlgeometry = documentCreate.createElement("KmlGeometry");
String pointValue = "<Point>";
//Reversing lat long output format
//String coordinate = ""+node.getAttribute("lat")+","+node.getAttribute("lon");
String coordinate = ""+node.getAttribute("lon")+","+node.getAttribute("lat");
// kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
// kml.appendChild(kmlcoordinate);
pointValue += "<coordinates>"+coordinate+"</coordinates>";
pointValue += "</Point>";
cdata.appendData(pointValue);
kmlgeometry.appendChild(cdata);
osmBuliding.appendChild(kmlgeometry);
osmBuildings.appendChild(osmBuliding);
}
}
root.appendChild(osmBuildings);
//Save the building information into xml file
CreateFile();
}
/*
*Function: Extract street information and then save it into xml file
*Input: The list of all the street information of OSM data downloaded
*Algorithm: Enumerate all the streets in the list, and for each street, enumerate all the nodes in its node list;
* Only extract state, city, county, name and type information of the street;
* To identify state name, find v value of tags whose k value contains both "state(s)" or "province(s)" and "addr" or "tiger" substring;
* To identify city name, find v value of tags whose k value contains both "city" and "addr" or "tiger" substring;
* To identify county name, find v value of tags whose k value contains both "county" and "addr" or "tiger" substring
*Output: Null
*/
public static void wayExtraction(NodeList wayElements, NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmStreets = documentCreate.createElement("Document");
/* osmStreets.setAttribute("xmlns", "http://www.myphotos.org");
osmStreets.setAttribute("xmlns:kml", "http://www.opengis.net/kml");
osmStreets.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
*/
System.out.println(" # of ways = " + wayElements.getLength());
for (int i = 0 ; i < wayElements.getLength(); i++) {
Element way = (Element)wayElements.item(i);
NodeList ndElements = way.getElementsByTagName("nd");
NodeList tagElements = way.getElementsByTagName("tag");
String wayName = "", wayType = "";
String cityName = "";
String countyName = "";
String stateName = "";
String wayId = way.getAttribute("id");
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
wayType = k;
}
if(k.contains("name")){
wayName = v;
}
if(k.contains("state") || k.contains("states") || k.contains("province") || k.contains("provinces")
&& (k.contains("addr") || k.contains("tiger"))){
stateName = v;
}
if(k.contains("city") && (k.contains("addr") || k.contains("tiger"))){
cityName = v;
}
if(k.contains("county") && (k.contains("addr") || k.contains("tiger"))){
countyName = v;
}
}
Element osmStreet = documentCreate.createElement("Placemark");
osmStreet.setAttribute("id", wayId);
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(wayName));
osmStreet.appendChild(kmlname);
Element cityname = documentCreate.createElement("CityName");
cityname.appendChild(documentCreate.createTextNode(cityName));
osmStreet.appendChild(cityname);
Element countyname = documentCreate.createElement("CountyName");
countyname.appendChild(documentCreate.createTextNode(countyName));
osmStreet.appendChild(countyname);
Element statename = documentCreate.createElement("StateName");
statename.appendChild(documentCreate.createTextNode(stateName));
osmStreet.appendChild(statename);
Element kmltype = documentCreate.createElement("Type");
//http://examples.javacodegeeks.com/core-java/xml/dom/add-cdata-section-to-dom-document/
//documentCreate.createCDATASection(arg0)
kmltype.appendChild(documentCreate.createTextNode(wayType));
osmStreet.appendChild(kmltype);
// osmStreet.setAttribute("type", wayType);
System.out.println(wayId + " " + wayName + " " + wayType);
CDATASection cdata = documentCreate.createCDATASection("");
Element kmlgeometry = documentCreate.createElement("KmlGeometry");
// Element kml = documentCreate.createElement("LineString");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
// Element kmlcoordinate = documentCreate.createElement("coordinates");
boolean firstNd = true;
String lineStringValue = "<LineString>";
String coordinate = "";
for(int j = 0; j < ndElements.getLength(); ++ j){
Element nd = (Element)ndElements.item(j);
String id = nd.getAttribute("ref");
// Ids.add(id);
if(hashMapNode.containsKey(id)){
Element node = (Element) hashMapNode.get(id);
String lat = node.getAttribute("lat");
String lon = node.getAttribute("lon");
if(!firstNd)
coordinate += " ";
//reversing lat long output format
//coordinate += lat+","+lon+",0";
coordinate += lon+","+lat+",0";
firstNd = false;
}
}
lineStringValue += "<coordinates>"+coordinate+"</coordinates>";
lineStringValue += "</LineString>";
// kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
// kml.appendChild(kmlcoordinate);
cdata.appendData(lineStringValue);
// cdata.appendChild(kml);
kmlgeometry.appendChild(cdata);
osmStreet.appendChild(kmlgeometry);
osmStreets.appendChild(osmStreet);
}
root.appendChild(osmStreets);
//Save the street information into xml file
CreateFile();
}
public static void relationExtraction(NodeList wayElements, NodeList nodeElements) throws FileNotFoundException, TransformerException{
Element osmStreets = documentCreate.createElement("Document");
System.out.println(" # of ways = " + wayElements.getLength());
for (int i = 0 ; i < wayElements.getLength(); i++) {
Element way = (Element)wayElements.item(i);
NodeList ndElements = way.getElementsByTagName("nd");
NodeList tagElements = way.getElementsByTagName("tag");
String wayName = "", wayType = "";
String wayId = way.getAttribute("id");
for(int j = 0; j < tagElements.getLength(); ++ j){
Element tag = (Element)tagElements.item(j);
String k = tag.getAttribute("k");
String v = tag.getAttribute("v");
if(k.contains("way")){
wayType = k;
}
if(k.contains("name")){
wayName = v;
}
}
Element osmStreet = documentCreate.createElement("Placemark");
osmStreet.setAttribute("id", wayId);
Element kmlname = documentCreate.createElement("Name");
kmlname.appendChild(documentCreate.createTextNode(wayName));
osmStreet.appendChild(kmlname);
Element kmltype = documentCreate.createElement("Type");
kmltype.appendChild(documentCreate.createTextNode(wayType));
osmStreet.appendChild(kmltype);
// osmStreet.setAttribute("type", wayType);
System.out.println(wayId + " " + wayName + " " + wayType);
Element kml = documentCreate.createElement("LineString");
// kml.setAttribute("srsDimension", "2");
// kml.setAttribute("srsName", "http://www.opengis.net/def/crs/EPSG/0/4326");
Element kmlcoordinate = documentCreate.createElement("coordinates");
boolean firstNd = true;
String coordinate = "";
Set<String> Ids = new HashSet<String>();
for(int j = 0; j < ndElements.getLength(); ++ j){
Element nd = (Element)ndElements.item(j);
String id = nd.getAttribute("ref");
Ids.add(id);
}
for(int j = 0; j < nodeElements.getLength(); ++ j){
Element node = (Element)nodeElements.item(j);
String id = node.getAttribute("id");
if(Ids.contains(id)){
String lat = node.getAttribute("lat");
String lon = node.getAttribute("lon");
if(!firstNd)
coordinate += " ";
//reversing output format
//coordinate += lat+","+lon+",0";
coordinate += lon+","+lat+",0";
firstNd = false;
}
}
kmlcoordinate.appendChild(documentCreate.createTextNode(coordinate));
kml.appendChild(kmlcoordinate);
osmStreet.appendChild(kml);
osmStreets.appendChild(osmStreet);
}
root.appendChild(osmStreets);
CreateFile();
}
/*
*Function: Download the original OSM data of xml format and save it in the local folder
*Input : The url of parameters for OSM xapi
*Output : Null
*/
private static void outputToOSM(String urls) throws ClientProtocolException, IOException {
//this.url = "'http://open.mapquestapi.com/xapi/api/0.6/map?bbox=" + url; //Extract normal size data;
url = "http://open.mapquestapi.com/xapi/api/0.6/map?" + urls; //Extract bigger size data;
System.out.println("this.url="+url);
DefaultHttpClient client = new DefaultHttpClient();
//Use the Http Get method to download the OSM data from given
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
xmlResult = EntityUtils.toString(entity);
FileOutputStream fout = new FileOutputStream(osmFile_path);
OutputStream bout = new BufferedOutputStream(fout);
OutputStreamWriter out = new OutputStreamWriter(bout, "utf-8");
out.write(xmlResult);
out.close();
}
/*
*Function: Save the extracted information into a local xml file
*Input : Null
*Output : Null
*/
private static void CreateFile() throws FileNotFoundException, TransformerException{
PrintWriter pw;
if(type.equalsIgnoreCase("street") || type.equalsIgnoreCase("streets")){
pw = new PrintWriter(new FileOutputStream(osmFilePathStreet));
}else if(type.equalsIgnoreCase("building") || type.equalsIgnoreCase("buildings")){
pw = new PrintWriter(new FileOutputStream(osmFilePathNode));
}else{
pw = new PrintWriter(new FileOutputStream(osmFilePathAll));
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(documentCreate);
transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
xmlResult = writer.toString();
System.out.println(xmlResult);
pw.println(xmlResult);
pw.flush();
pw.close();
// System.out.println(""+result.toString());
// StringWriter writer = new StringWriter();
// result = new StreamResult(writer);
// transformer.transform(source, result);
}
}
|
add api key for OSM
|
scripts/src/main/java/edu/isi/karma/ugde/osm/osmFetch.java
|
add api key for OSM
|
|
Java
|
apache-2.0
|
c923717ddb86174c3a683d2ee6110a8485be571e
| 0
|
OpenHFT/Chronicle-Core
|
/*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* 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.openhft.chronicle.core;
import net.openhft.chronicle.core.annotation.DontChain;
import net.openhft.chronicle.core.onoes.*;
import net.openhft.chronicle.core.util.ObjectUtils;
import net.openhft.chronicle.core.util.ThrowingSupplier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import sun.misc.Unsafe;
import sun.nio.ch.DirectBuffer;
import sun.nio.ch.Interruptible;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.lang.Runtime.getRuntime;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
import static net.openhft.chronicle.core.OS.*;
import static net.openhft.chronicle.core.UnsafeMemory.UNSAFE;
/**
* Utility class to access information in the JVM.
*/
public enum Jvm {
;
public static final String JAVA_CLASS_PATH = "java.class.path";
public static final String SYSTEM_PROPERTIES = "system.properties";
private static final List<String> INPUT_ARGUMENTS = getRuntimeMXBean().getInputArguments();
private static final String INPUT_ARGUMENTS2 = " " + String.join(" ", INPUT_ARGUMENTS);
private static final int COMPILE_THRESHOLD = getCompileThreshold0();
private static final boolean IS_DEBUG = INPUT_ARGUMENTS2.contains("jdwp") || Jvm.getBoolean("debug");
// e.g-verbose:gc -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=dumponexit=true,filename=myrecording.jfr,settings=profile -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
private static final boolean IS_FLIGHT_RECORDER = INPUT_ARGUMENTS2.contains(" -XX:+FlightRecorder") || Jvm.getBoolean("jfr");
private static final boolean IS_COVERAGE = INPUT_ARGUMENTS2.contains("coverage");
private static final boolean REPORT_UNOPTIMISED;
private static final Supplier<Long> reservedMemory;
private static final boolean IS_64BIT = is64bit0();
private static final int PROCESS_ID = getProcessId0();
private static final boolean IS_AZUL_ZING = Bootstrap.isAzulZing0();
private static final boolean IS_AZUL_ZULU = Bootstrap.isAzulZulu0();
@NotNull
private static final ThreadLocalisedExceptionHandler FATAL = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.FATAL);
@NotNull
private static final ThreadLocalisedExceptionHandler ERROR = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.ERROR);
@NotNull
private static final ThreadLocalisedExceptionHandler WARN = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.WARN);
@NotNull
private static final ThreadLocalisedExceptionHandler PERF = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.PERF);
@NotNull
private static final ThreadLocalisedExceptionHandler DEBUG = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.DEBUG);
private static final int JVM_JAVA_MAJOR_VERSION;
private static final boolean IS_JAVA_9_PLUS;
private static final boolean IS_JAVA_12_PLUS;
private static final boolean IS_JAVA_14_PLUS;
private static final boolean IS_JAVA_15_PLUS;
private static final long MAX_DIRECT_MEMORY;
private static final boolean SAFEPOINT_ENABLED;
private static final boolean IS_ARM = Bootstrap.isArm0();
private static final boolean IS_MAC_ARM = Bootstrap.isMacArm0();
private static final Map<Class, ClassMetrics> CLASS_METRICS_MAP =
new ConcurrentHashMap<>();
private static final Map<Class, Integer> PRIMITIVE_SIZE = new HashMap<Class, Integer>() {{
put(boolean.class, 1);
put(byte.class, 1);
put(char.class, 2);
put(short.class, 2);
put(int.class, 4);
put(float.class, 4);
put(long.class, 8);
put(double.class, 8);
}};
private static final MethodHandle setAccessible0_Method;
private static final MethodHandle onSpinWaitMH;
private static final ChainedSignalHandler signalHandlerGlobal;
private static final boolean RESOURCE_TRACING;
private static final boolean PROC_EXISTS = new File("/proc").exists();
private static final int OBJECT_HEADER_SIZE;
static {
final Field[] declaredFields = ObjectHeaderSizeChecker.class.getDeclaredFields();
JVM_JAVA_MAJOR_VERSION = getMajorVersion0();
IS_JAVA_9_PLUS = JVM_JAVA_MAJOR_VERSION > 8; // IS_JAVA_9_PLUS value is used in maxDirectMemory0 method.
IS_JAVA_12_PLUS = JVM_JAVA_MAJOR_VERSION > 11;
IS_JAVA_14_PLUS = JVM_JAVA_MAJOR_VERSION > 13;
IS_JAVA_15_PLUS = JVM_JAVA_MAJOR_VERSION > 14;
// get this here before we call getField
setAccessible0_Method = get_setAccessible0_Method();
MAX_DIRECT_MEMORY = maxDirectMemory0();
OBJECT_HEADER_SIZE = (int) UnsafeMemory.INSTANCE.getFieldOffset(declaredFields[0]);
Supplier<Long> reservedMemoryGetter;
try {
final Class<?> bitsClass = Class.forName("java.nio.Bits");
final Field firstTry = getFieldOrNull(bitsClass, "reservedMemory");
final Field f = firstTry != null ? firstTry : getField(bitsClass, "RESERVED_MEMORY");
if (f.getType() == AtomicLong.class) {
AtomicLong reservedMemory = (AtomicLong) f.get(null);
reservedMemoryGetter = reservedMemory::get;
} else {
reservedMemoryGetter = ThrowingSupplier.asSupplier(() -> f.getLong(null));
}
} catch (Exception e) {
System.err.println(Jvm.class.getName() + ": Unable to determine the reservedMemory value, will always report 0");
reservedMemoryGetter = () -> 0L;
}
reservedMemory = reservedMemoryGetter;
signalHandlerGlobal = new ChainedSignalHandler();
MethodHandle onSpinWait = null;
if (IS_JAVA_9_PLUS) {
try {
onSpinWait = MethodHandles.lookup()
.findStatic(Thread.class, "onSpinWait", MethodType.methodType(Void.TYPE));
} catch (Exception ignored) {
}
}
onSpinWaitMH = onSpinWait;
findAndLoadSystemProperties();
boolean disablePerfInfo = Jvm.getBoolean("disable.perf.info");
if (disablePerfInfo)
PERF.defaultHandler(NullExceptionHandler.NOTHING);
SAFEPOINT_ENABLED = Jvm.getBoolean("jvm.safepoint.enabled");
RESOURCE_TRACING = Jvm.getBoolean("jvm.resource.tracing");
Logger logger = LoggerFactory.getLogger(Jvm.class);
logger.info("Chronicle core loaded from " + Jvm.class.getProtectionDomain().getCodeSource().getLocation());
if (RESOURCE_TRACING && !Jvm.getBoolean("disable.resource.warning"))
logger.warn("Resource tracing is turned on. If you are performance testing or running in PROD you probably don't want this");
REPORT_UNOPTIMISED = Jvm.getBoolean("report.unoptimised");
}
public static void reportUnoptimised() {
if (!REPORT_UNOPTIMISED)
return;
final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
int i = 0;
while (i < stes.length)
if (stes[i++].getMethodName().equals("reportUnoptimised"))
break;
while (i < stes.length)
if (stes[i++].getMethodName().equals("<clinit>"))
break;
Jvm.warn().on(Jvm.class, "Reporting usage of unoptimised method " + stes[i]);
}
private static void findAndLoadSystemProperties() {
String systemProperties = System.getProperty(SYSTEM_PROPERTIES);
boolean wasSet = true;
if (systemProperties == null) {
if (new File(SYSTEM_PROPERTIES).exists())
systemProperties = SYSTEM_PROPERTIES;
else if (new File("../" + SYSTEM_PROPERTIES).exists())
systemProperties = "../" + SYSTEM_PROPERTIES;
else {
systemProperties = SYSTEM_PROPERTIES;
wasSet = false;
}
}
loadSystemProperties(systemProperties, wasSet);
}
private static MethodHandle get_setAccessible0_Method() {
if (!IS_JAVA_9_PLUS) {
return null;
}
final MethodType signature = MethodType.methodType(boolean.class, boolean.class);
try {
// Access privateLookupIn() reflectively to support compilation with JDK 8
Method privateLookupIn = MethodHandles.class.getDeclaredMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class);
MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupIn.invoke(null, AccessibleObject.class, MethodHandles.lookup());
return lookup.findVirtual(AccessibleObject.class, "setAccessible0", signature);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void init() {
// force static initialisation
}
private static void loadSystemProperties(final String name, final boolean wasSet) {
try {
final ClassLoader classLoader = Jvm.class.getClassLoader();
InputStream is0 = classLoader == null ? null : classLoader.getResourceAsStream(name);
if (is0 == null) {
File file = new File(name);
if (file.exists())
is0 = new FileInputStream(file);
}
try (InputStream is = is0) {
if (is == null) {
(wasSet ? Slf4jExceptionHandler.WARN : Slf4jExceptionHandler.DEBUG)
.on(Jvm.class, "No " + name + " file found");
} else {
final Properties prop = new Properties();
prop.load(is);
// if user has specified a property using -D then don't overwrite it from system.properties
prop.forEach((o, o2) -> System.getProperties().putIfAbsent(o, o2));
Slf4jExceptionHandler.DEBUG.on(Jvm.class, "Loaded " + name + " with " + prop);
}
}
} catch (Exception e) {
Slf4jExceptionHandler.WARN.on(Jvm.class, "Error loading " + name, e);
}
}
private static int getCompileThreshold0() {
for (String inputArgument : INPUT_ARGUMENTS) {
final String prefix = "-XX:CompileThreshold=";
if (inputArgument.startsWith(prefix)) {
try {
return Integer.parseInt(inputArgument.substring(prefix.length()));
} catch (NumberFormatException nfe) {
// ignore
}
}
}
return 10_000;
}
/**
* Returns the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000).
* <p>
* The compile threshold can be explicitly set using the command
* line parameter "-XX:CompileThreshold="
*
* @return the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000)
*/
public static int compileThreshold() {
return COMPILE_THRESHOLD;
}
/**
* Returns the major Java version (e.g. 8, 11 or 17)
*
* @return the major Java version (e.g. 8, 11 or 17)
*/
public static int majorVersion() {
return JVM_JAVA_MAJOR_VERSION;
}
/**
* Returns if the major Java version is 9 or higher.
*
* @return if the major Java version is 9 or higher
*/
public static boolean isJava9Plus() {
return IS_JAVA_9_PLUS;
}
/**
* Returns if the major Java version is 12 or higher.
*
* @return if the major Java version is 12 or higher
*/
public static boolean isJava12Plus() {
return IS_JAVA_12_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava14Plus() {
return IS_JAVA_14_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava15Plus() {
return IS_JAVA_15_PLUS;
}
private static boolean is64bit0() {
String systemProp;
systemProp = System.getProperty("com.ibm.vm.bitmode");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = System.getProperty("sun.arch.data.model");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = System.getProperty("java.vm.version");
return systemProp != null && systemProp.contains("_64");
}
/**
* Returns the current process id.
*
* @return the current process id or, if the process id cannot be determined, 1 is used.
*/
// Todo: Discuss the rational behind the random number. Alternately, 0 could be returned or perhaps -1
public static int getProcessId() {
return PROCESS_ID;
}
private static int getProcessId0() {
String pid = null;
final File self = new File("/proc/self");
try {
if (self.exists()) {
pid = self.getCanonicalFile().getName();
}
} catch (IOException ignored) {
}
if (pid == null) {
pid = getRuntimeMXBean().getName().split("@", 0)[0];
}
if (pid != null) {
try {
return Integer.parseInt(pid);
} catch (NumberFormatException nfe) {
// ignore
}
}
int rpid = 1;
System.err.println(Jvm.class.getName() + ": Unable to determine PID, picked 1 as a PID");
return rpid;
}
/**
* Cast any Throwable (e.g. a checked exception) to a RuntimeException.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@NotNull
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
/**
* Append the provided {@code StackTraceElements} to the provided {@code stringBuilder} trimming some internal methods.
*
* @param stringBuilder to append to
* @param stackTraceElements stack trace elements
*/
public static void trimStackTrace(@NotNull final StringBuilder stringBuilder, @NotNull final StackTraceElement... stackTraceElements) {
final int first = trimFirst(stackTraceElements);
final int last = trimLast(first, stackTraceElements);
for (int i = first; i <= last; i++)
stringBuilder.append("\n\tat ").append(stackTraceElements[i]);
}
static int trimFirst(@NotNull final StackTraceElement[] stes) {
if (stes.length > 2 && stes[1].getMethodName().endsWith("afepoint"))
return 2;
int first = 0;
for (; first < stes.length; first++)
if (!isInternal(stes[first].getClassName()))
break;
return Math.max(0, first - 2);
}
public static int trimLast(final int first, @NotNull final StackTraceElement[] stes) {
int last = stes.length - 1;
for (; first < last; last--)
if (!isInternal(stes[last].getClassName()))
break;
if (last < stes.length - 1) last++;
return last;
}
static boolean isInternal(@NotNull final String className) {
return className.startsWith("jdk.") || className.startsWith("sun.") || className.startsWith("java.");
}
/**
* Returns if the JVM is running in debug mode.
*
* @return if the JVM is running in debug mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isDebug() {
return IS_DEBUG;
}
/**
* Returns if the JVM is running in flight recorder mode.
*
* @return if the JVM is running in flight recorder mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isFlightRecorder() {
return IS_FLIGHT_RECORDER;
}
/**
* Returns if the JVM is running in code coverage mode.
*
* @return if the JVM is running in code coverage mode
*/
public static boolean isCodeCoverage() {
return IS_COVERAGE;
}
/**
* Silently pause for the provided {@code durationMs} milliseconds.
* <p>
* If the provided {@code durationMs} is positive, then the
* current thread sleeps.
* <p>
* If the provided {@code durationMs} is zero, then the
* current thread yields.
*
* @param durationMs to sleep for.
*/
public static void pause(final long durationMs) {
if (durationMs <= 0) {
Thread.yield();
return;
}
try {
Thread.sleep(durationMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Pause in a busy loop for a very short time.
*/
public static void nanoPause() {
if (onSpinWaitMH == null) {
safepoint();
} else {
try {
onSpinWaitMH.invokeExact();
} catch (Throwable throwable) {
throw new AssertionError(throwable);
}
}
}
/**
* Pause in a busy loop for the provided {@code durationUs} microseconds.
* <p>
* This method is designed to be used when the time to be waited is very small,
* typically under a millisecond (@{code durationUs < 1_000}).
*
* @param durationUs Time in durationUs
*/
public static void busyWaitMicros(final long durationUs) {
busyWaitUntil(System.nanoTime() + (durationUs * 1_000));
}
/**
* Pauses the current thread in a busy loop until the provided {@code waitUntilNs} time is reached.
* <p>
* This method is designed to be used when the time to be waited is very small,
* typically under a millisecond (@{code durationNs < 1_000_000}).
*
* @param waitUntilNs nanosecond precision counter value to await.
*/
public static void busyWaitUntil(final long waitUntilNs) {
while (waitUntilNs > System.nanoTime()) {
Jvm.nanoPause();
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or
* throws an Exception if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Field getField(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
return getField0(clazz, fieldName, true);
}
static Field getField0(@NotNull final Class<?> clazz,
@NotNull final String name,
final boolean error) {
try {
final Field field = clazz.getDeclaredField(name);
setAccessible(field);
return field;
} catch (NoSuchFieldException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
final Field field = getField0(superclass, name, false);
if (field != null)
return field;
}
if (error)
throw new AssertionError(e);
return null;
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or {@code null}
* if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
@Nullable
public static Field getFieldOrNull(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
try {
return getField(clazz, fieldName);
} catch (AssertionError e) {
return null;
}
}
/**
* Returns the Method for the provided {@code clazz}, {@code methodName} and
* {@code argTypes} or throws an Exception.
* <p>
* if it exists or throws {@link AssertionError}.
* <p>
* Default methods are not detected unless the class explicitly overrides it
*
* @param clazz class
* @param methodName methodName
* @param argTypes argument types
* @return method
* @throws AssertionError if no such Method exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Method getMethod(@NotNull final Class<?> clazz,
@NotNull final String methodName,
final Class... argTypes) {
return getMethod0(clazz, methodName, argTypes, true);
}
private static Method getMethod0(@NotNull final Class<?> clazz,
@NotNull final String name,
final Class[] args,
final boolean first) {
try {
final Method method = clazz.getDeclaredMethod(name, args);
if (!Modifier.isPublic(method.getModifiers()) ||
!Modifier.isPublic(method.getDeclaringClass().getModifiers()))
setAccessible(method);
return method;
} catch (NoSuchMethodException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null)
try {
final Method m = getMethod0(superclass, name, args, false);
if (m != null)
return m;
} catch (Exception ignored) {
}
if (first)
throw new AssertionError(e);
return null;
}
}
/**
* Set the accessible flag for the provided {@code accessibleObject} indicating that
* the reflected object should suppress Java language access checking when it is used.
* <p>
* The setting of the accessible flag might be subject to security manager approval.
*
* @param accessibleObject to modify
* @throws SecurityException – if the request is denied.
* @see SecurityManager#checkPermission
* @see RuntimePermission
*/
public static void setAccessible(@NotNull final AccessibleObject accessibleObject) {
if (IS_JAVA_9_PLUS)
try {
boolean newFlag = (boolean) setAccessible0_Method.invokeExact(accessibleObject, true);
assert newFlag;
} catch (Throwable throwable) {
throw Jvm.rethrow(throwable);
}
else
accessibleObject.setAccessible(true);
}
/**
* Returns the value of the provided {@code fieldName} extracted from the provided {@code target}.
* <p>
* The provided {@code fieldName} can denote fields of arbitrary depth (e.g. foo.bar.baz, whereby
* the foo value will be extracted from the provided {@code target} and then the bar value
* will be extracted from the foo value and so on).
*
* @param target used for extraction
* @param fieldName denoting the field(s) to extract
* @param <V> return type
* @return the value of the provided {@code fieldName} extracted from the provided {@code target}
*/
@Nullable
public static <V> V getValue(@NotNull Object target, @NotNull final String fieldName) {
Class<?> aClass = target.getClass();
for (String n : fieldName.split("/")) {
Field f = getField(aClass, n);
try {
target = f.get(target);
if (target == null)
return null;
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new AssertionError(e);
}
aClass = target.getClass();
}
return (V) target;
}
/**
* Log the stack trace of the thread holding a lock.
*
* @param lock to log
* @return the lock.toString plus a stack trace.
*/
public static String lockWithStack(@NotNull final ReentrantLock lock) {
final Thread t = getValue(lock, "sync/exclusiveOwnerThread");
if (t == null) {
return lock.toString();
}
final StringBuilder ret = new StringBuilder();
ret.append(lock).append(" running at");
trimStackTrace(ret, t.getStackTrace());
return ret.toString();
}
/**
* @param clazz the class for which you want to get field from [ it wont see inherited fields ]
* @param fieldName the name of the field
* @return the offset
*/
public static long fieldOffset(final Class<?> clazz, final String fieldName) {
try {
return UNSAFE.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
}
/**
* Returns the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined.
* <p>
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined
*/
public static long usedDirectMemory() {
return reservedMemory.get();
}
/**
* Returns the accumulated amount of memory used in bytes by UnsafeMemory.allocate().
*
* @return the accumulated amount of memory used in bytes by UnsafeMemory.allocate()
*/
public static long usedNativeMemory() {
return UnsafeMemory.INSTANCE.nativeMemoryUsed();
}
/**
* Returns the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined.
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined
*/
public static long maxDirectMemory() {
return MAX_DIRECT_MEMORY;
}
/**
* Returns if the JVM runs in 64 bit mode.
*
* @return if the JVM runs in 64 bit mode
*/
public static boolean is64bit() {
return IS_64BIT;
}
public static void resetExceptionHandlers() {
FATAL.defaultHandler(Slf4jExceptionHandler.FATAL).resetThreadLocalHandler();
ERROR.defaultHandler(Slf4jExceptionHandler.ERROR).resetThreadLocalHandler();
WARN.defaultHandler(Slf4jExceptionHandler.WARN).resetThreadLocalHandler();
DEBUG.defaultHandler(Slf4jExceptionHandler.DEBUG).resetThreadLocalHandler();
PERF.defaultHandler(Slf4jExceptionHandler.DEBUG).resetThreadLocalHandler();
}
public static void disableDebugHandler() {
DEBUG.defaultHandler(null).resetThreadLocalHandler();
}
public static void disablePerfHandler() {
PERF.defaultHandler(null).resetThreadLocalHandler();
}
public static void disableWarnHandler() {
WARN.defaultHandler(null).resetThreadLocalHandler();
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions() {
return recordExceptions(true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug) {
return recordExceptions(debug, false);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug, boolean exceptionsOnly) {
return recordExceptions(debug, exceptionsOnly, true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(final boolean debug,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final Map<ExceptionKey, Integer> map = Collections.synchronizedMap(new LinkedHashMap<>());
FATAL.defaultHandler(recordingExceptionHandler(LogLevel.FATAL, map, exceptionsOnly, logToSlf4j));
ERROR.defaultHandler(recordingExceptionHandler(LogLevel.ERROR, map, exceptionsOnly, logToSlf4j));
WARN.defaultHandler(recordingExceptionHandler(LogLevel.WARN, map, exceptionsOnly, logToSlf4j));
PERF.defaultHandler(debug
? recordingExceptionHandler(LogLevel.PERF, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.PERF : NullExceptionHandler.NOTHING);
DEBUG.defaultHandler(debug
? recordingExceptionHandler(LogLevel.DEBUG, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.DEBUG : NullExceptionHandler.NOTHING);
return map;
}
private static ExceptionHandler recordingExceptionHandler(final LogLevel logLevel,
final Map<ExceptionKey, Integer> map,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final ExceptionHandler eh = new RecordingExceptionHandler(logLevel, map, exceptionsOnly);
if (logToSlf4j)
return new ChainedExceptionHandler(eh, Slf4jExceptionHandler.valueOf(logLevel));
return eh;
}
public static boolean hasException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
final Iterator<ExceptionKey> iterator = exceptions.keySet().iterator();
while (iterator.hasNext()) {
final ExceptionKey k = iterator.next();
if (k.level != LogLevel.DEBUG && k.level != LogLevel.PERF)
return true;
}
return false;
}
@Deprecated(/* to be removed in x.22 */)
public static void setExceptionsHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
setExceptionHandlers(fatal, warn, debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
FATAL.defaultHandler(fatal);
WARN.defaultHandler(warn);
DEBUG.defaultHandler(debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setExceptionHandlers(fatal, warn, debug);
PERF.defaultHandler(perf);
}
// Use {@link #setExceptionHandlers(ExceptionHandler, ExceptionHandler, ExceptionHandler, ExceptionHandler)} in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setExceptionHandlers(fatal, warn, debug);
ERROR.defaultHandler(error);
PERF.defaultHandler(perf);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
FATAL.threadLocalHandler(fatal);
WARN.threadLocalHandler(warn);
DEBUG.threadLocalHandler(debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setThreadLocalExceptionHandlers(fatal, warn, debug);
PERF.threadLocalHandler(perf);
}
// Use {@link #setThreadLocalExceptionHandlers(ExceptionHandler, ExceptionHandler, ExceptionHandler, ExceptionHandler)} in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setThreadLocalExceptionHandlers(fatal, warn, debug);
ERROR.threadLocalHandler(error);
PERF.threadLocalHandler(perf);
}
/**
* @deprecated use {@link #error()}
*/
@Deprecated(/* remove in x.23*/)
@NotNull
public static ExceptionHandler fatal() {
return FATAL;
}
/**
* Returns an ExceptionHandler for errors, this prints as System.err or ERROR level logging.
* In tests these messages are usually captured and checked that the error expected and only those expected are produced.
*
* @return the ERROR exception handler
*/
@NotNull
public static ExceptionHandler error() {
return ERROR;
}
/**
* Returns an ExceptionHandler for warnings, this prints as System.out or WARN level logging.
* In tests these messages are usually captured and checked that the warning expected and only those expected are produced.
*
* @return the WARN exception handler
*/
@NotNull
public static ExceptionHandler warn() {
return WARN;
}
/**
* Returns an ExceptionHandler for startup messages, this prints as System.out or INFO level logging.
* In tests these messages are generally not captured for checking.
*
* @return the STARTUP exception handler
*/
@NotNull
public static ExceptionHandler startup() {
// TODO, add a startup level?
return PERF;
}
/**
* Returns an ExceptionHandler for performance messages, this prints as System.out or INFO level logging.
* In tests these messages are generally not captured for checking, but a few tests may check performance metrics are reported.
*
* @return the PERF exception handler
*/
@NotNull
public static ExceptionHandler perf() {
return PERF;
}
/**
* Returns an ExceptionHandler for debug messages, this prints as System.out or DEBUG level logging.
* In tests these messages are generally not captured for checking.
*
* @return the DEBUG exception handler
*/
@NotNull
public static ExceptionHandler debug() {
return DEBUG;
}
public static void dumpException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
System.out.println("exceptions: " + exceptions.size());
for (@NotNull Map.Entry<ExceptionKey, Integer> entry : exceptions.entrySet()) {
final ExceptionKey key = entry.getKey();
System.err.println(key.level + " " + key.clazz.getSimpleName() + " " + key.message);
if (key.throwable != null)
key.throwable.printStackTrace();
final Integer value = entry.getValue();
if (value > 1)
System.err.println("Repeated " + value + " times");
}
resetExceptionHandlers();
}
public static boolean isDebugEnabled(final Class<?> aClass) {
return DEBUG.isEnabled(aClass) || isDebug();
}
private static long maxDirectMemory0() {
try {
final Class<?> clz;
if (IS_JAVA_9_PLUS) {
clz = Class.forName("jdk.internal.misc.VM");
} else {
clz = Class.forName("sun.misc.VM");
}
final Field f = getField(clz, "directMemory");
return f.getLong(null);
} catch (Exception e) {
// ignore
}
System.err.println(Jvm.class.getName() + ": Unable to determine max direct memory");
return 0L;
}
private static int getMajorVersion0() {
try {
final Method method = Runtime.class.getDeclaredMethod("version");
if (method != null) {
final Object version = method.invoke(getRuntime());
final Class<?> clz = Class.forName("java.lang.Runtime$Version");
return (Integer) clz.getDeclaredMethod("major").invoke(version);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | IllegalArgumentException e) {
// ignore and fall back to pre-jdk9
}
try {
return Integer.parseInt(Runtime.class.getPackage().getSpecificationVersion().split("\\.")[1]);
} catch (NumberFormatException nfe) {
Jvm.warn().on(Jvm.class, "Unable to get the major version, defaulting to 8 " + nfe);
return 8;
}
}
/**
* Adds the provided {@code signalHandler} to an internal chain of handlers that will be invoked
* upon detecting system signals (e.g. HUP, INT, TERM).
* <p>
* Not all signals are available on all operating systems.
*
* @param signalHandler to call on a signal
*/
public static void signalHandler(final SignalHandler signalHandler) {
if (signalHandlerGlobal.handlers.isEmpty()) {
if (!OS.isWindows()) // not available on windows.
addSignalHandler("HUP", signalHandlerGlobal);
addSignalHandler("INT", signalHandlerGlobal);
addSignalHandler("TERM", signalHandlerGlobal);
}
final SignalHandler signalHandler2 = signal -> {
Jvm.warn().on(signalHandler.getClass(), "Signal " + signal.getName() + " triggered");
signalHandler.handle(signal);
};
signalHandlerGlobal.handlers.add(signalHandler2);
}
private static void addSignalHandler(final String sig, final SignalHandler signalHandler) {
try {
Signal.handle(new Signal(sig), signalHandler);
} catch (IllegalArgumentException e) {
// When -Xrs is specified the user is responsible for
// ensuring that shutdown hooks are run by calling
// System.exit()
Jvm.warn().on(signalHandler.getClass(), "Unable add a signal handler", e);
}
}
/**
* Inserts a low-cost Java safe-point in the code path.
*/
public static void safepoint() {
if (SAFEPOINT_ENABLED)
if (IS_JAVA_9_PLUS)
Safepoint.force(); // 1 ns on Java 11
else
Compiler.enable(); // 5 ns on Java 8
}
@Deprecated(/* to be removed in x.22 */)
public static void optionalSafepoint() {
safepoint();
}
public static boolean areOptionalSafepointsEnabled() {
return SAFEPOINT_ENABLED;
}
/**
* Returns if there is a class name that ends with the provided {@code endsWith} string
* when examining the current stack trace of depth at most up to the provided {@code maxDepth}.
*
* @param endsWith to test against the current stack trace
* @param maxDepth to examine
* @return if there is a class name that ends with the provided {@code endsWith} string
* when examining the current stack trace of depth at most up to the provided {@code maxDepth}
*/
public static boolean stackTraceEndsWith(final String endsWith, final int maxDepth) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = maxDepth + 2; i < stackTrace.length; i++)
if (stackTrace[i].getClassName().endsWith(endsWith))
return true;
return false;
}
/**
* Returns if the JVM runs on a CPU using the ARM architecture.
*
* @return if the JVM runs on a CPU using the ARM architecture
*/
public static boolean isArm() {
return IS_ARM;
}
/**
* Returns if the JVM runs on a CPU using a Mac ARM architecture.
*
* @return if the JVM runs on a CPU using the Mac ARM architecture e.g. Apple M1.
*/
public static boolean isMacArm() {
return IS_MAC_ARM;
}
/**
* Acquires and returns the ClassMetrics for the provided {@code clazz}.
*
* @param clazz for which ClassMetrics shall be acquired
* @return the ClassMetrics for the provided {@code clazz}
* @throws IllegalArgumentException if no ClassMetrics can be acquired
* @see ClassMetrics
*/
@NotNull
public static ClassMetrics classMetrics(final Class<?> clazz) throws IllegalArgumentException {
return CLASS_METRICS_MAP.computeIfAbsent(clazz, Jvm::getClassMetrics);
}
private static ClassMetrics getClassMetrics(final Class<?> c) {
final Class<?> superclass = c.getSuperclass();
int start = Integer.MAX_VALUE, end = 0;
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
if (!f.getType().isPrimitive())
continue;
int start0 = Math.toIntExact(UnsafeMemory.unsafeObjectFieldOffset(f));
int size = PRIMITIVE_SIZE.get(f.getType());
start = Math.min(start0, start);
end = Math.max(start0 + size, end);
}
if (superclass != null && superclass != Object.class) {
final ClassMetrics cm0 = getClassMetrics(superclass);
start = Math.min(cm0.offset(), start);
end = Math.max(cm0.offset() + cm0.length(), end);
validateClassMetrics(superclass, start, end);
}
validateClassMetrics(c, start, end);
return new ClassMetrics(start, end - start);
}
private static void validateClassMetrics(final Class<?> c,
final int start,
final int end) {
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) != 0)
continue;
if (f.getType().isPrimitive())
continue;
final int start0 = Math.toIntExact(UnsafeMemory.unsafeObjectFieldOffset(f));
if (start <= start0 && start0 < end) {
rethrow(new IllegalArgumentException(c + " is not suitable for raw copies due to " + f));
}
}
}
/**
* Returns the user's home directory (e.g. "/home/alice") or "."
* if the user's home director cannot be determined.
*
* @return the user's home directory (e.g. "/home/alice") or "."
* if the user's home director cannot be determined
*/
@NotNull
public static String userHome() {
return System.getProperty("user.home", ".");
}
public static boolean dontChain(final Class<?> tClass) {
return tClass.getAnnotation(DontChain.class) != null || tClass.getName().startsWith("java");
}
/**
* Returns if certain chronicle resources (such as memory regions) are traced.
* <p>
* Tracing resources incurs slightly less performance but provides a means
* of detecting proper release of resources.
*
* @return if certain chronicle resources (such as memory regions) are traced
*/
public static boolean isResourceTracing() {
return RESOURCE_TRACING;
}
/**
* Returns if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true".
* <p>
* This provides a more permissive boolean System systemPropertyKey flag where
* {@code -Dflag} {@code -Dflag=true} {@code -Dflag=yes} are all accepted.
*
* @param systemPropertyKey name to lookup
* @return if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true"
*/
public static boolean getBoolean(final String systemPropertyKey) {
return getBoolean(systemPropertyKey, false);
}
/**
* Returns if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true" or, if it does not exist,
* returns the provided {@code defaultValue}.
* <p>
* This provides a more permissive boolean System systemPropertyKey flag where
* {@code -Dflag} {@code -Dflag=true} {@code -Dflag=yes} are all accepted.
*
* @param systemPropertyKey name to lookup
* @param defaultValue value to be used if unknown
* @return if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true" or, if it does not exist,
* returns the provided {@code defaultValue}.
*/
public static boolean getBoolean(final String systemPropertyKey, final boolean defaultValue) {
final String value = System.getProperty(systemPropertyKey);
if (value == null)
return defaultValue;
if (value.isEmpty())
return true;
final String trim = value.trim();
return defaultValue
? !ObjectUtils.isFalse(trim)
: ObjectUtils.isTrue(trim);
}
/**
* Parse a string as a decimal memory size with an optional scale.
* K/k = * 2<sup>10</sup>, M/m = 2<sup>20</sup>, G/g = 2<sup>10</sup>, T/t = 2<sup>40</sup>
* <p>
* trailing B/b/iB/ib are ignored.
* <table>
* <tr><td>100</td><td>100 bytes</td></tr>
* <tr><td>100b</td><td>100 bytes</td></tr>
* <tr><td>0.5kb</td><td>512 bytes</td></tr>
* <tr><td>0.125MB</td><td>128 KiB</td></tr>
* <tr><td>2M</td><td>2 MiB</td></tr>
* <tr><td>0.75GiB</td><td>768 MiB</td></tr>
* <tr><td>0.001TiB</td><td>1.024 GiB</td></tr>
* </table>
* </p>
*
* @param value size to parse
* @return the size
* @throws IllegalArgumentException if the string could be parsed
*/
public static long parseSize(@NotNull String value) throws IllegalArgumentException {
long factor = 1;
if (value.length() > 1) {
char last = value.charAt(value.length() - 1);
// assume we meant bytes, not bits
if (last == 'b' || last == 'B') {
value = value.substring(0, value.length() - 1);
last = value.charAt(value.length() - 1);
}
if (last == 'i') {
value = value.substring(0, value.length() - 1);
last = value.charAt(value.length() - 1);
}
if (Character.isLetter(last)) {
switch (last) {
case 't':
case 'T':
factor = 1L << 40;
break;
case 'g':
case 'G':
factor = 1L << 30;
break;
case 'm': // technically milli, but we will assume mega
case 'M':
factor = 1L << 20;
break;
case 'k':
case 'K':
factor = 1L << 10;
break;
default:
throw new IllegalArgumentException("Unrecognised suffix for size " + value);
}
value = value.substring(0, value.length() - 1);
}
}
double number = Double.parseDouble(value.trim());
factor *= number;
return factor;
}
/**
* Uses Jvm.parseSize to parse a system property or returns defaultValue if not present, empty or unparseable.
*
* @param property to look up
* @param defaultValue to use otherwise
* @return the size in bytes as a long
*/
public static long getSize(final String property, final long defaultValue) {
final String value = System.getProperty(property);
if (value == null || value.length() <= 0)
return defaultValue;
try {
return parseSize(value);
} catch (IllegalArgumentException iae) {
Jvm.warn().on(Jvm.class, "Unable to parse the property " + property + " as a size " + iae.getMessage() + " using " + defaultValue);
return defaultValue;
}
}
/**
* Returns the native address of the provided {@code byteBuffer}.
* <p>
* <em>Use with caution!</em>. Native address should always be carefully
* guarded to prevent unspecified results or even JVM crashes.
*
* @param byteBuffer from which to extract the native address
* @return the native address of the provided {@code byteBuffer}
*/
public static long address(@NotNull final ByteBuffer byteBuffer) {
return ((DirectBuffer) byteBuffer).address();
}
/**
* Returns the array byte base offset used by this JVM.
* <p>
* The value is the number of bytes that precedes the actual
* memory layout of a {@code byte[] } array in a java array object.
* <p>
* <em>Use with caution!</em>. Native address should always be carefully
* guarded to prevent unspecified results or even JVM crashes.
*
* @return the array byte base offset used by this JVM
*/
public static int arrayByteBaseOffset() {
return Unsafe.ARRAY_BYTE_BASE_OFFSET;
}
/**
* Employs a best-effort of preventing the provided {@code fc } from being automatically closed
* whenever the current thread gets interrupted.
* <p>
* If the effort failed, the provided {@code clazz} is used for logging purposes.
*
* @param clazz to use for logging should the effort fail.
* @param fc to prevent from automatically closing upon interrupt.
*/
public static void doNotCloseOnInterrupt(final Class<?> clazz, final FileChannel fc) {
if (Jvm.isJava9Plus())
doNotCloseOnInterrupt9(clazz, fc);
else
doNotCloseOnInterrupt8(clazz, fc);
}
private static void doNotCloseOnInterrupt8(final Class<?> clazz, final FileChannel fc) {
try {
final Field field = AbstractInterruptibleChannel.class
.getDeclaredField("interruptor");
Jvm.setAccessible(field);
final CommonInterruptible ci = new CommonInterruptible(clazz, fc);
field.set(fc, (Interruptible) thread -> ci.interrupt());
} catch (Throwable e) {
Jvm.warn().on(clazz, "Couldn't disable close on interrupt", e);
}
}
// based on a solution by https://stackoverflow.com/users/9199167/max-vollmer
// https://stackoverflow.com/a/52262779/57695
private static void doNotCloseOnInterrupt9(final Class<?> clazz, final FileChannel fc) {
try {
final Field field = AbstractInterruptibleChannel.class.getDeclaredField("interruptor");
final Class<?> interruptibleClass = field.getType();
Jvm.setAccessible(field);
final CommonInterruptible ci = new CommonInterruptible(clazz, fc);
field.set(fc, Proxy.newProxyInstance(
interruptibleClass.getClassLoader(),
new Class[]{interruptibleClass},
(p, m, a) -> {
if (m.getDeclaringClass() != Object.class)
ci.interrupt();
return ObjectUtils.defaultValue(m.getReturnType());
}));
} catch (Throwable e) {
Jvm.warn().on(clazz, "Couldn't disable close on interrupt", e);
}
}
/**
* Ensures that all the jars and other resources are added to the class path of the classloader
* associated by the provided {@code clazz}.
*
* @param clazz to use as a template.
*/
public static void addToClassPath(@NotNull final Class<?> clazz) {
ClassLoader cl = clazz.getClassLoader();
if (!(cl instanceof URLClassLoader))
return;
String property = System.getProperty(JAVA_CLASS_PATH);
Set<String> jcp = new LinkedHashSet<>();
Collections.addAll(jcp, property.split(File.pathSeparator));
jcp.addAll(jcp.stream()
.map(f -> new File(f).getAbsolutePath())
.collect(Collectors.toList()));
URLClassLoader ucl = (URLClassLoader) cl;
StringBuilder classpath = new StringBuilder(property);
for (URL url : ucl.getURLs()) {
try {
String path = Paths.get(url.toURI()).toString();
if (!jcp.contains(path)) {
if (isDebugEnabled(Jvm.class))
debug().on(Jvm.class, "Adding " + path + " to the classpath");
classpath.append(File.pathSeparator).append(path);
}
} catch (Throwable e) {
debug().on(Jvm.class, "Could not add URL " + url + " to classpath");
}
}
System.setProperty(JAVA_CLASS_PATH, classpath.toString());
}
/**
* Returns the System Property associated with the provided {@code systemPropertyKey}
* parsed as a {@code double} or, if no such parsable System Property exists,
* returns the provided {@code defaultValue}.
*
* @param systemPropertyKey to lookup in the System Properties
* @param defaultValue to be used if no parsable key association exists
* @return the System Property associated with the provided {@code systemPropertyKey}
* parsed as a {@code double} or, if no such parsable System Property exists,
* returns the provided {@code defaultValue}
*/
public static double getDouble(final String systemPropertyKey, final double defaultValue) {
final String value = System.getProperty(systemPropertyKey);
if (value != null)
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
Jvm.debug().on(Jvm.class, "Unable to parse property " + systemPropertyKey + " as a double " + e);
}
return defaultValue;
}
/**
* Returns if a process with the provided {@code pid} process id is alive.
*
* @param pid the process id (pid) of the process to check
* @return if a process with the provided {@code pid} process id is alive
*/
public static boolean isProcessAlive(long pid) {
if (isWindows()) {
final String command = "cmd /c tasklist /FI \"PID eq " + pid + "\"";
return isProcessAlive0(pid, command);
}
if (isLinux() && PROC_EXISTS) {
return new File("/proc/" + pid).exists();
}
if (isMacOSX() || isLinux()) {
final String command = "ps -p " + pid;
return isProcessAlive0(pid, command);
}
throw new UnsupportedOperationException("Not supported on this OS");
}
private static boolean isProcessAlive0(final long pid, final String command) {
try {
InputStreamReader isReader = new InputStreamReader(
getRuntime().exec(command).getInputStream());
final BufferedReader bReader = new BufferedReader(isReader);
String strLine;
while ((strLine = bReader.readLine()) != null) {
if (strLine.contains(" " + pid + " ") || strLine.startsWith(pid + " ")) {
return true;
}
}
return false;
} catch (Exception ex) {
return true;
}
}
public static boolean isAzulZing() {
return IS_AZUL_ZING;
}
public static boolean isAzulZulu() {
return IS_AZUL_ZULU;
}
public static int objectHeaderSize() {
return OBJECT_HEADER_SIZE;
}
static class ObjectHeaderSizeChecker {
public int a;
}
static final class CommonInterruptible {
static final ThreadLocal<AtomicBoolean> insideTL = ThreadLocal.withInitial(AtomicBoolean::new);
private final Class<?> clazz;
private final FileChannel fc;
CommonInterruptible(Class<?> clazz, FileChannel fc) {
this.clazz = clazz;
this.fc = fc;
}
public void interrupt() {
final AtomicBoolean inside = insideTL.get();
if (inside.get())
return;
inside.set(true);
assert Thread.currentThread().isInterrupted();
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(clazz, fc + " not closed on interrupt");
inside.set(false);
}
}
// from https://stackoverflow.com/questions/62550828/is-there-a-lightweight-method-which-adds-a-safepoint-in-java-9
static final class Safepoint {
// must be volatile
private static volatile int one = 1;
public static void force() {
// trick only works from Java 9+
for (int i = 0; i < one; i++) ;
}
}
static final class ChainedSignalHandler implements SignalHandler {
final List<SignalHandler> handlers = new CopyOnWriteArrayList<>();
@Override
public void handle(final Signal signal) {
for (SignalHandler handler : handlers) {
try {
if (handler != null)
handler.handle(signal);
} catch (Throwable t) {
Jvm.warn().on(this.getClass(), "Problem handling signal", t);
}
}
}
}
/**
* @return Obtain the model of CPU on Linux or the os.arch on other OSes.
*/
public static String getCpuClass() {
return CpuClass.CPU_MODEL;
}
static final class CpuClass {
static final String CPU_MODEL;
static {
String model = System.getProperty("os.arch", "unknown");
try {
final Path path = Paths.get("/proc/cpuinfo");
if (Files.isReadable(path)) {
model = Files.lines(path)
.filter(line -> line.startsWith("model name"))
.map(line -> line.replaceAll(".*: ", ""))
.findFirst().orElse(model);
} else if (OS.isWindows()) {
String cmd = "wmic cpu get name";
Process process = new ProcessBuilder(cmd.split(" "))
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
model = reader.lines()
.map(String::trim)
.filter(s -> !"Name".equals(s) && !s.isEmpty())
.findFirst().orElse(model);
}
try {
int ret = process.waitFor();
if (ret != 0)
Jvm.warn().on(CpuClass.class, "process " + cmd + " returned " + ret);
} catch (InterruptedException e) {
Jvm.warn().on(CpuClass.class, "process " + cmd + " waitFor threw ", e);
}
process.destroy();
} else if (OS.isMacOSX()) {
String cmd = "sysctl -a";
Process process = new ProcessBuilder(cmd.split(" "))
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
model = reader.lines()
.map(String::trim)
.filter(s -> s.startsWith("machdep.cpu.brand_string"))
.map(line -> line.replaceAll(".*: ", ""))
.findFirst().orElse(model);
}
try {
int ret = process.waitFor();
if (ret != 0)
Jvm.warn().on(CpuClass.class, "process " + cmd + " returned " + ret);
} catch (InterruptedException e) {
Jvm.warn().on(CpuClass.class, "process " + cmd + " waitFor threw ", e);
}
process.destroy();
}
} catch (IOException e) {
Jvm.debug().on(CpuClass.class, "Unable to read cpuinfo", e);
}
CPU_MODEL = model;
}
}
}
|
src/main/java/net/openhft/chronicle/core/Jvm.java
|
/*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* 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.openhft.chronicle.core;
import net.openhft.chronicle.core.annotation.DontChain;
import net.openhft.chronicle.core.onoes.*;
import net.openhft.chronicle.core.util.ObjectUtils;
import net.openhft.chronicle.core.util.ThrowingSupplier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import sun.misc.Unsafe;
import sun.nio.ch.DirectBuffer;
import sun.nio.ch.Interruptible;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.lang.Runtime.getRuntime;
import static java.lang.management.ManagementFactory.getRuntimeMXBean;
import static net.openhft.chronicle.core.OS.*;
import static net.openhft.chronicle.core.UnsafeMemory.UNSAFE;
/**
* Utility class to access information in the JVM.
*/
public enum Jvm {
;
public static final String JAVA_CLASS_PATH = "java.class.path";
public static final String SYSTEM_PROPERTIES = "system.properties";
private static final List<String> INPUT_ARGUMENTS = getRuntimeMXBean().getInputArguments();
private static final String INPUT_ARGUMENTS2 = " " + String.join(" ", INPUT_ARGUMENTS);
private static final int COMPILE_THRESHOLD = getCompileThreshold0();
private static final boolean IS_DEBUG = INPUT_ARGUMENTS2.contains("jdwp") || Jvm.getBoolean("debug");
// e.g-verbose:gc -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=dumponexit=true,filename=myrecording.jfr,settings=profile -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints
private static final boolean IS_FLIGHT_RECORDER = INPUT_ARGUMENTS2.contains(" -XX:+FlightRecorder") || Jvm.getBoolean("jfr");
private static final boolean IS_COVERAGE = INPUT_ARGUMENTS2.contains("coverage");
private static final boolean REPORT_UNOPTIMISED;
private static final Supplier<Long> reservedMemory;
private static final boolean IS_64BIT = is64bit0();
private static final int PROCESS_ID = getProcessId0();
private static final boolean IS_AZUL_ZING = Bootstrap.isAzulZing0();
private static final boolean IS_AZUL_ZULU = Bootstrap.isAzulZulu0();
@NotNull
private static final ThreadLocalisedExceptionHandler FATAL = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.FATAL);
@NotNull
private static final ThreadLocalisedExceptionHandler ERROR = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.ERROR);
@NotNull
private static final ThreadLocalisedExceptionHandler WARN = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.WARN);
@NotNull
private static final ThreadLocalisedExceptionHandler PERF = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.PERF);
@NotNull
private static final ThreadLocalisedExceptionHandler DEBUG = new ThreadLocalisedExceptionHandler(Slf4jExceptionHandler.DEBUG);
private static final int JVM_JAVA_MAJOR_VERSION;
private static final boolean IS_JAVA_9_PLUS;
private static final boolean IS_JAVA_12_PLUS;
private static final boolean IS_JAVA_14_PLUS;
private static final boolean IS_JAVA_15_PLUS;
private static final long MAX_DIRECT_MEMORY;
private static final boolean SAFEPOINT_ENABLED;
private static final boolean IS_ARM = Bootstrap.isArm0();
private static final boolean IS_MAC_ARM = Bootstrap.isMacArm0();
private static final Map<Class, ClassMetrics> CLASS_METRICS_MAP =
new ConcurrentHashMap<>();
private static final Map<Class, Integer> PRIMITIVE_SIZE = new HashMap<Class, Integer>() {{
put(boolean.class, 1);
put(byte.class, 1);
put(char.class, 2);
put(short.class, 2);
put(int.class, 4);
put(float.class, 4);
put(long.class, 8);
put(double.class, 8);
}};
private static final MethodHandle setAccessible0_Method;
private static final MethodHandle onSpinWaitMH;
private static final ChainedSignalHandler signalHandlerGlobal;
private static final boolean RESOURCE_TRACING;
private static final boolean PROC_EXISTS = new File("/proc").exists();
private static final int OBJECT_HEADER_SIZE;
static {
final Field[] declaredFields = ObjectHeaderSizeChecker.class.getDeclaredFields();
JVM_JAVA_MAJOR_VERSION = getMajorVersion0();
IS_JAVA_9_PLUS = JVM_JAVA_MAJOR_VERSION > 8; // IS_JAVA_9_PLUS value is used in maxDirectMemory0 method.
IS_JAVA_12_PLUS = JVM_JAVA_MAJOR_VERSION > 11;
IS_JAVA_14_PLUS = JVM_JAVA_MAJOR_VERSION > 13;
IS_JAVA_15_PLUS = JVM_JAVA_MAJOR_VERSION > 14;
// get this here before we call getField
setAccessible0_Method = get_setAccessible0_Method();
MAX_DIRECT_MEMORY = maxDirectMemory0();
OBJECT_HEADER_SIZE = (int) UnsafeMemory.INSTANCE.getFieldOffset(declaredFields[0]);
Supplier<Long> reservedMemoryGetter;
try {
final Class<?> bitsClass = Class.forName("java.nio.Bits");
final Field firstTry = getFieldOrNull(bitsClass, "reservedMemory");
final Field f = firstTry != null ? firstTry : getField(bitsClass, "RESERVED_MEMORY");
if (f.getType() == AtomicLong.class) {
AtomicLong reservedMemory = (AtomicLong) f.get(null);
reservedMemoryGetter = reservedMemory::get;
} else {
reservedMemoryGetter = ThrowingSupplier.asSupplier(() -> f.getLong(null));
}
} catch (Exception e) {
System.err.println(Jvm.class.getName() + ": Unable to determine the reservedMemory value, will always report 0");
reservedMemoryGetter = () -> 0L;
}
reservedMemory = reservedMemoryGetter;
signalHandlerGlobal = new ChainedSignalHandler();
MethodHandle onSpinWait = null;
if (IS_JAVA_9_PLUS) {
try {
onSpinWait = MethodHandles.lookup()
.findStatic(Thread.class, "onSpinWait", MethodType.methodType(Void.TYPE));
} catch (Exception ignored) {
}
}
onSpinWaitMH = onSpinWait;
findAndLoadSystemProperties();
boolean disablePerfInfo = Jvm.getBoolean("disable.perf.info");
if (disablePerfInfo)
PERF.defaultHandler(NullExceptionHandler.NOTHING);
SAFEPOINT_ENABLED = Jvm.getBoolean("jvm.safepoint.enabled");
RESOURCE_TRACING = Jvm.getBoolean("jvm.resource.tracing");
Logger logger = LoggerFactory.getLogger(Jvm.class);
logger.info("Chronicle core loaded from " + Jvm.class.getProtectionDomain().getCodeSource().getLocation());
if (RESOURCE_TRACING && !Jvm.getBoolean("disable.resource.warning"))
logger.warn("Resource tracing is turned on. If you are performance testing or running in PROD you probably don't want this");
REPORT_UNOPTIMISED = Jvm.getBoolean("report.unoptimised");
}
public static void reportUnoptimised() {
if (!REPORT_UNOPTIMISED)
return;
final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
int i = 0;
while (i < stes.length)
if (stes[i++].getMethodName().equals("reportUnoptimised"))
break;
while (i < stes.length)
if (stes[i++].getMethodName().equals("<clinit>"))
break;
Jvm.warn().on(Jvm.class, "Reporting usage of unoptimised method " + stes[i]);
}
private static void findAndLoadSystemProperties() {
String systemProperties = System.getProperty(SYSTEM_PROPERTIES);
boolean wasSet = true;
if (systemProperties == null) {
if (new File(SYSTEM_PROPERTIES).exists())
systemProperties = SYSTEM_PROPERTIES;
else if (new File("../" + SYSTEM_PROPERTIES).exists())
systemProperties = "../" + SYSTEM_PROPERTIES;
else {
systemProperties = SYSTEM_PROPERTIES;
wasSet = false;
}
}
loadSystemProperties(systemProperties, wasSet);
}
private static MethodHandle get_setAccessible0_Method() {
if (!IS_JAVA_9_PLUS) {
return null;
}
final MethodType signature = MethodType.methodType(boolean.class, boolean.class);
try {
// Access privateLookupIn() reflectively to support compilation with JDK 8
Method privateLookupIn = MethodHandles.class.getDeclaredMethod("privateLookupIn", Class.class, MethodHandles.Lookup.class);
MethodHandles.Lookup lookup = (MethodHandles.Lookup) privateLookupIn.invoke(null, AccessibleObject.class, MethodHandles.lookup());
return lookup.findVirtual(AccessibleObject.class, "setAccessible0", signature);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new ExceptionInInitializerError(e);
}
}
public static void init() {
// force static initialisation
}
private static void loadSystemProperties(final String name, final boolean wasSet) {
try {
final ClassLoader classLoader = Jvm.class.getClassLoader();
InputStream is0 = classLoader == null ? null : classLoader.getResourceAsStream(name);
if (is0 == null) {
File file = new File(name);
if (file.exists())
is0 = new FileInputStream(file);
}
try (InputStream is = is0) {
if (is == null) {
(wasSet ? Slf4jExceptionHandler.WARN : Slf4jExceptionHandler.DEBUG)
.on(Jvm.class, "No " + name + " file found");
} else {
final Properties prop = new Properties();
prop.load(is);
// if user has specified a property using -D then don't overwrite it from system.properties
prop.forEach((o, o2) -> System.getProperties().putIfAbsent(o, o2));
Slf4jExceptionHandler.DEBUG.on(Jvm.class, "Loaded " + name + " with " + prop);
}
}
} catch (Exception e) {
Slf4jExceptionHandler.WARN.on(Jvm.class, "Error loading " + name, e);
}
}
private static int getCompileThreshold0() {
for (String inputArgument : INPUT_ARGUMENTS) {
final String prefix = "-XX:CompileThreshold=";
if (inputArgument.startsWith(prefix)) {
try {
return Integer.parseInt(inputArgument.substring(prefix.length()));
} catch (NumberFormatException nfe) {
// ignore
}
}
}
return 10_000;
}
/**
* Returns the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000).
* <p>
* The compile threshold can be explicitly set using the command
* line parameter "-XX:CompileThreshold="
*
* @return the compile threshold for the JVM or else an
* estimate thereof (e.g. 10_000)
*/
public static int compileThreshold() {
return COMPILE_THRESHOLD;
}
/**
* Returns the major Java version (e.g. 8, 11 or 17)
*
* @return the major Java version (e.g. 8, 11 or 17)
*/
public static int majorVersion() {
return JVM_JAVA_MAJOR_VERSION;
}
/**
* Returns if the major Java version is 9 or higher.
*
* @return if the major Java version is 9 or higher
*/
public static boolean isJava9Plus() {
return IS_JAVA_9_PLUS;
}
/**
* Returns if the major Java version is 12 or higher.
*
* @return if the major Java version is 12 or higher
*/
public static boolean isJava12Plus() {
return IS_JAVA_12_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava14Plus() {
return IS_JAVA_14_PLUS;
}
/**
* Returns if the major Java version is 14 or higher.
*
* @return if the major Java version is 14 or higher
*/
public static boolean isJava15Plus() {
return IS_JAVA_15_PLUS;
}
private static boolean is64bit0() {
String systemProp;
systemProp = System.getProperty("com.ibm.vm.bitmode");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = System.getProperty("sun.arch.data.model");
if (systemProp != null) {
return "64".equals(systemProp);
}
systemProp = System.getProperty("java.vm.version");
return systemProp != null && systemProp.contains("_64");
}
/**
* Returns the current process id.
*
* @return the current process id or, if the process id cannot be determined, 1 is used.
*/
// Todo: Discuss the rational behind the random number. Alternately, 0 could be returned or perhaps -1
public static int getProcessId() {
return PROCESS_ID;
}
private static int getProcessId0() {
String pid = null;
final File self = new File("/proc/self");
try {
if (self.exists()) {
pid = self.getCanonicalFile().getName();
}
} catch (IOException ignored) {
}
if (pid == null) {
pid = getRuntimeMXBean().getName().split("@", 0)[0];
}
if (pid != null) {
try {
return Integer.parseInt(pid);
} catch (NumberFormatException nfe) {
// ignore
}
}
int rpid = 1;
System.err.println(Jvm.class.getName() + ": Unable to determine PID, picked 1 as a PID");
return rpid;
}
/**
* Cast any Throwable (e.g. a checked exception) to a RuntimeException.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@NotNull
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
/**
* Append the provided {@code StackTraceElements} to the provided {@code stringBuilder} trimming some internal methods.
*
* @param stringBuilder to append to
* @param stackTraceElements stack trace elements
*/
public static void trimStackTrace(@NotNull final StringBuilder stringBuilder, @NotNull final StackTraceElement... stackTraceElements) {
final int first = trimFirst(stackTraceElements);
final int last = trimLast(first, stackTraceElements);
for (int i = first; i <= last; i++)
stringBuilder.append("\n\tat ").append(stackTraceElements[i]);
}
static int trimFirst(@NotNull final StackTraceElement[] stes) {
if (stes.length > 2 && stes[1].getMethodName().endsWith("afepoint"))
return 2;
int first = 0;
for (; first < stes.length; first++)
if (!isInternal(stes[first].getClassName()))
break;
return Math.max(0, first - 2);
}
public static int trimLast(final int first, @NotNull final StackTraceElement[] stes) {
int last = stes.length - 1;
for (; first < last; last--)
if (!isInternal(stes[last].getClassName()))
break;
if (last < stes.length - 1) last++;
return last;
}
static boolean isInternal(@NotNull final String className) {
return className.startsWith("jdk.") || className.startsWith("sun.") || className.startsWith("java.");
}
/**
* Returns if the JVM is running in debug mode.
*
* @return if the JVM is running in debug mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isDebug() {
return IS_DEBUG;
}
/**
* Returns if the JVM is running in flight recorder mode.
*
* @return if the JVM is running in flight recorder mode
*/
@SuppressWarnings("SameReturnValue")
public static boolean isFlightRecorder() {
return IS_FLIGHT_RECORDER;
}
/**
* Returns if the JVM is running in code coverage mode.
*
* @return if the JVM is running in code coverage mode
*/
public static boolean isCodeCoverage() {
return IS_COVERAGE;
}
/**
* Silently pause for the provided {@code durationMs} milliseconds.
* <p>
* If the provided {@code durationMs} is positive, then the
* current thread sleeps.
* <p>
* If the provided {@code durationMs} is zero, then the
* current thread yields.
*
* @param durationMs to sleep for.
*/
public static void pause(final long durationMs) {
if (durationMs <= 0) {
Thread.yield();
return;
}
try {
Thread.sleep(durationMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* Pause in a busy loop for a very short time.
*/
public static void nanoPause() {
if (onSpinWaitMH == null) {
safepoint();
} else {
try {
onSpinWaitMH.invokeExact();
} catch (Throwable throwable) {
throw new AssertionError(throwable);
}
}
}
/**
* Pause in a busy loop for the provided {@code durationUs} microseconds.
* <p>
* This method is designed to be used when the time to be waited is very small,
* typically under a millisecond (@{code durationUs < 1_000}).
*
* @param durationUs Time in durationUs
*/
public static void busyWaitMicros(final long durationUs) {
busyWaitUntil(System.nanoTime() + (durationUs * 1_000));
}
/**
* Pauses the current thread in a busy loop until the provided {@code waitUntilNs} time is reached.
* <p>
* This method is designed to be used when the time to be waited is very small,
* typically under a millisecond (@{code durationNs < 1_000_000}).
*
* @param waitUntilNs nanosecond precision counter value to await.
*/
public static void busyWaitUntil(final long waitUntilNs) {
while (waitUntilNs > System.nanoTime()) {
Jvm.nanoPause();
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or
* throws an Exception if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Field getField(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
return getField0(clazz, fieldName, true);
}
static Field getField0(@NotNull final Class<?> clazz,
@NotNull final String name,
final boolean error) {
try {
final Field field = clazz.getDeclaredField(name);
setAccessible(field);
return field;
} catch (NoSuchFieldException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
final Field field = getField0(superclass, name, false);
if (field != null)
return field;
}
if (error)
throw new AssertionError(e);
return null;
}
}
/**
* Returns the Field for the provided {@code clazz} and the provided {@code fieldName} or {@code null}
* if no such Field exists.
*
* @param clazz to get the field for
* @param fieldName of the field
* @return the Field.
* @throws AssertionError if no such Field exists
*/
@Nullable
public static Field getFieldOrNull(@NotNull final Class<?> clazz, @NotNull final String fieldName) {
try {
return getField(clazz, fieldName);
} catch (AssertionError e) {
return null;
}
}
/**
* Returns the Method for the provided {@code clazz}, {@code methodName} and
* {@code argTypes} or throws an Exception.
* <p>
* if it exists or throws {@link AssertionError}.
* <p>
* Default methods are not detected unless the class explicitly overrides it
*
* @param clazz class
* @param methodName methodName
* @param argTypes argument types
* @return method
* @throws AssertionError if no such Method exists
*/
// Todo: Should not throw an AssertionError but rather a RuntimeException
@NotNull
public static Method getMethod(@NotNull final Class<?> clazz,
@NotNull final String methodName,
final Class... argTypes) {
return getMethod0(clazz, methodName, argTypes, true);
}
private static Method getMethod0(@NotNull final Class<?> clazz,
@NotNull final String name,
final Class[] args,
final boolean first) {
try {
final Method method = clazz.getDeclaredMethod(name, args);
if (!Modifier.isPublic(method.getModifiers()) ||
!Modifier.isPublic(method.getDeclaringClass().getModifiers()))
setAccessible(method);
return method;
} catch (NoSuchMethodException e) {
final Class<?> superclass = clazz.getSuperclass();
if (superclass != null)
try {
final Method m = getMethod0(superclass, name, args, false);
if (m != null)
return m;
} catch (Exception ignored) {
}
if (first)
throw new AssertionError(e);
return null;
}
}
/**
* Set the accessible flag for the provided {@code accessibleObject} indicating that
* the reflected object should suppress Java language access checking when it is used.
* <p>
* The setting of the accessible flag might be subject to security manager approval.
*
* @param accessibleObject to modify
* @throws SecurityException – if the request is denied.
* @see SecurityManager#checkPermission
* @see RuntimePermission
*/
public static void setAccessible(@NotNull final AccessibleObject accessibleObject) {
if (IS_JAVA_9_PLUS)
try {
boolean newFlag = (boolean) setAccessible0_Method.invokeExact(accessibleObject, true);
assert newFlag;
} catch (Throwable throwable) {
throw Jvm.rethrow(throwable);
}
else
accessibleObject.setAccessible(true);
}
/**
* Returns the value of the provided {@code fieldName} extracted from the provided {@code target}.
* <p>
* The provided {@code fieldName} can denote fields of arbitrary depth (e.g. foo.bar.baz, whereby
* the foo value will be extracted from the provided {@code target} and then the bar value
* will be extracted from the foo value and so on).
*
* @param target used for extraction
* @param fieldName denoting the field(s) to extract
* @param <V> return type
* @return the value of the provided {@code fieldName} extracted from the provided {@code target}
*/
@Nullable
public static <V> V getValue(@NotNull Object target, @NotNull final String fieldName) {
Class<?> aClass = target.getClass();
for (String n : fieldName.split("/")) {
Field f = getField(aClass, n);
try {
target = f.get(target);
if (target == null)
return null;
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new AssertionError(e);
}
aClass = target.getClass();
}
return (V) target;
}
/**
* Log the stack trace of the thread holding a lock.
*
* @param lock to log
* @return the lock.toString plus a stack trace.
*/
public static String lockWithStack(@NotNull final ReentrantLock lock) {
final Thread t = getValue(lock, "sync/exclusiveOwnerThread");
if (t == null) {
return lock.toString();
}
final StringBuilder ret = new StringBuilder();
ret.append(lock).append(" running at");
trimStackTrace(ret, t.getStackTrace());
return ret.toString();
}
/**
* @param clazz the class for which you want to get field from [ it wont see inherited fields ]
* @param fieldName the name of the field
* @return the offset
*/
public static long fieldOffset(final Class<?> clazz, final String fieldName) {
try {
return UNSAFE.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
}
/**
* Returns the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined.
* <p>
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the accumulated amount of memory in bytes used by direct ByteBuffers
* or 0 if the value cannot be determined
*/
public static long usedDirectMemory() {
return reservedMemory.get();
}
/**
* Returns the accumulated amount of memory used in bytes by UnsafeMemory.allocate().
*
* @return the accumulated amount of memory used in bytes by UnsafeMemory.allocate()
*/
public static long usedNativeMemory() {
return UnsafeMemory.INSTANCE.nativeMemoryUsed();
}
/**
* Returns the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined.
* (i.e. ever allocated via ByteBuffer.allocateDirect())
*
* @return the maximum direct memory in bytes that can ever be allocated or 0 if the
* value cannot be determined
*/
public static long maxDirectMemory() {
return MAX_DIRECT_MEMORY;
}
/**
* Returns if the JVM runs in 64 bit mode.
*
* @return if the JVM runs in 64 bit mode
*/
public static boolean is64bit() {
return IS_64BIT;
}
public static void resetExceptionHandlers() {
FATAL.defaultHandler(Slf4jExceptionHandler.FATAL).resetThreadLocalHandler();
ERROR.defaultHandler(Slf4jExceptionHandler.ERROR).resetThreadLocalHandler();
WARN.defaultHandler(Slf4jExceptionHandler.WARN).resetThreadLocalHandler();
DEBUG.defaultHandler(Slf4jExceptionHandler.DEBUG).resetThreadLocalHandler();
PERF.defaultHandler(Slf4jExceptionHandler.DEBUG).resetThreadLocalHandler();
}
public static void disableDebugHandler() {
DEBUG.defaultHandler(null).resetThreadLocalHandler();
}
public static void disablePerfHandler() {
PERF.defaultHandler(null).resetThreadLocalHandler();
}
public static void disableWarnHandler() {
WARN.defaultHandler(null).resetThreadLocalHandler();
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions() {
return recordExceptions(true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug) {
return recordExceptions(debug, false);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(boolean debug, boolean exceptionsOnly) {
return recordExceptions(debug, exceptionsOnly, true);
}
@NotNull
public static Map<ExceptionKey, Integer> recordExceptions(final boolean debug,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final Map<ExceptionKey, Integer> map = Collections.synchronizedMap(new LinkedHashMap<>());
FATAL.defaultHandler(recordingExceptionHandler(LogLevel.FATAL, map, exceptionsOnly, logToSlf4j));
ERROR.defaultHandler(recordingExceptionHandler(LogLevel.ERROR, map, exceptionsOnly, logToSlf4j));
WARN.defaultHandler(recordingExceptionHandler(LogLevel.WARN, map, exceptionsOnly, logToSlf4j));
PERF.defaultHandler(debug
? recordingExceptionHandler(LogLevel.PERF, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.PERF : NullExceptionHandler.NOTHING);
DEBUG.defaultHandler(debug
? recordingExceptionHandler(LogLevel.DEBUG, map, exceptionsOnly, logToSlf4j)
: logToSlf4j ? Slf4jExceptionHandler.DEBUG : NullExceptionHandler.NOTHING);
return map;
}
private static ExceptionHandler recordingExceptionHandler(final LogLevel logLevel,
final Map<ExceptionKey, Integer> map,
final boolean exceptionsOnly,
final boolean logToSlf4j) {
final ExceptionHandler eh = new RecordingExceptionHandler(logLevel, map, exceptionsOnly);
if (logToSlf4j)
return new ChainedExceptionHandler(eh, Slf4jExceptionHandler.valueOf(logLevel));
return eh;
}
public static boolean hasException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
final Iterator<ExceptionKey> iterator = exceptions.keySet().iterator();
while (iterator.hasNext()) {
final ExceptionKey k = iterator.next();
if (k.level != LogLevel.DEBUG && k.level != LogLevel.PERF)
return true;
}
return false;
}
@Deprecated(/* to be removed in x.22 */)
public static void setExceptionsHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
setExceptionHandlers(fatal, warn, debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
FATAL.defaultHandler(fatal);
WARN.defaultHandler(warn);
DEBUG.defaultHandler(debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setExceptionHandlers(fatal, warn, debug);
PERF.defaultHandler(perf);
}
// Use {@link #setExceptionHandlers(ExceptionHandler, ExceptionHandler, ExceptionHandler, ExceptionHandler)} in x.23
public static void setExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setExceptionHandlers(fatal, warn, debug);
ERROR.defaultHandler(error);
PERF.defaultHandler(perf);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug) {
FATAL.threadLocalHandler(fatal);
WARN.threadLocalHandler(warn);
DEBUG.threadLocalHandler(debug);
}
// Note: 'fatal' param will be replaced with 'error' in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setThreadLocalExceptionHandlers(fatal, warn, debug);
PERF.threadLocalHandler(perf);
}
// Use {@link #setThreadLocalExceptionHandlers(ExceptionHandler, ExceptionHandler, ExceptionHandler, ExceptionHandler)} in x.23
public static void setThreadLocalExceptionHandlers(@Nullable final ExceptionHandler fatal,
@Nullable final ExceptionHandler error,
@Nullable final ExceptionHandler warn,
@Nullable final ExceptionHandler debug,
@Nullable final ExceptionHandler perf) {
setThreadLocalExceptionHandlers(fatal, warn, debug);
ERROR.threadLocalHandler(error);
PERF.threadLocalHandler(perf);
}
/**
* @deprecated use {@link #error()}
*/
@Deprecated(/* remove in x.23*/)
@NotNull
public static ExceptionHandler fatal() {
return FATAL;
}
@NotNull
public static ExceptionHandler error() {
return ERROR;
}
@NotNull
public static ExceptionHandler warn() {
return WARN;
}
@NotNull
public static ExceptionHandler startup() {
// TODO, add a startup level?
return PERF;
}
@NotNull
public static ExceptionHandler perf() {
return PERF;
}
@NotNull
public static ExceptionHandler debug() {
return DEBUG;
}
public static void dumpException(@NotNull final Map<ExceptionKey, Integer> exceptions) {
System.out.println("exceptions: " + exceptions.size());
for (@NotNull Map.Entry<ExceptionKey, Integer> entry : exceptions.entrySet()) {
final ExceptionKey key = entry.getKey();
System.err.println(key.level + " " + key.clazz.getSimpleName() + " " + key.message);
if (key.throwable != null)
key.throwable.printStackTrace();
final Integer value = entry.getValue();
if (value > 1)
System.err.println("Repeated " + value + " times");
}
resetExceptionHandlers();
}
public static boolean isDebugEnabled(final Class<?> aClass) {
return DEBUG.isEnabled(aClass) || isDebug();
}
private static long maxDirectMemory0() {
try {
final Class<?> clz;
if (IS_JAVA_9_PLUS) {
clz = Class.forName("jdk.internal.misc.VM");
} else {
clz = Class.forName("sun.misc.VM");
}
final Field f = getField(clz, "directMemory");
return f.getLong(null);
} catch (Exception e) {
// ignore
}
System.err.println(Jvm.class.getName() + ": Unable to determine max direct memory");
return 0L;
}
private static int getMajorVersion0() {
try {
final Method method = Runtime.class.getDeclaredMethod("version");
if (method != null) {
final Object version = method.invoke(getRuntime());
final Class<?> clz = Class.forName("java.lang.Runtime$Version");
return (Integer) clz.getDeclaredMethod("major").invoke(version);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | IllegalArgumentException e) {
// ignore and fall back to pre-jdk9
}
try {
return Integer.parseInt(Runtime.class.getPackage().getSpecificationVersion().split("\\.")[1]);
} catch (NumberFormatException nfe) {
Jvm.warn().on(Jvm.class, "Unable to get the major version, defaulting to 8 " + nfe);
return 8;
}
}
/**
* Adds the provided {@code signalHandler} to an internal chain of handlers that will be invoked
* upon detecting system signals (e.g. HUP, INT, TERM).
* <p>
* Not all signals are available on all operating systems.
*
* @param signalHandler to call on a signal
*/
public static void signalHandler(final SignalHandler signalHandler) {
if (signalHandlerGlobal.handlers.isEmpty()) {
if (!OS.isWindows()) // not available on windows.
addSignalHandler("HUP", signalHandlerGlobal);
addSignalHandler("INT", signalHandlerGlobal);
addSignalHandler("TERM", signalHandlerGlobal);
}
final SignalHandler signalHandler2 = signal -> {
Jvm.warn().on(signalHandler.getClass(), "Signal " + signal.getName() + " triggered");
signalHandler.handle(signal);
};
signalHandlerGlobal.handlers.add(signalHandler2);
}
private static void addSignalHandler(final String sig, final SignalHandler signalHandler) {
try {
Signal.handle(new Signal(sig), signalHandler);
} catch (IllegalArgumentException e) {
// When -Xrs is specified the user is responsible for
// ensuring that shutdown hooks are run by calling
// System.exit()
Jvm.warn().on(signalHandler.getClass(), "Unable add a signal handler", e);
}
}
/**
* Inserts a low-cost Java safe-point in the code path.
*/
public static void safepoint() {
if (SAFEPOINT_ENABLED)
if (IS_JAVA_9_PLUS)
Safepoint.force(); // 1 ns on Java 11
else
Compiler.enable(); // 5 ns on Java 8
}
@Deprecated(/* to be removed in x.22 */)
public static void optionalSafepoint() {
safepoint();
}
public static boolean areOptionalSafepointsEnabled() {
return SAFEPOINT_ENABLED;
}
/**
* Returns if there is a class name that ends with the provided {@code endsWith} string
* when examining the current stack trace of depth at most up to the provided {@code maxDepth}.
*
* @param endsWith to test against the current stack trace
* @param maxDepth to examine
* @return if there is a class name that ends with the provided {@code endsWith} string
* when examining the current stack trace of depth at most up to the provided {@code maxDepth}
*/
public static boolean stackTraceEndsWith(final String endsWith, final int maxDepth) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = maxDepth + 2; i < stackTrace.length; i++)
if (stackTrace[i].getClassName().endsWith(endsWith))
return true;
return false;
}
/**
* Returns if the JVM runs on a CPU using the ARM architecture.
*
* @return if the JVM runs on a CPU using the ARM architecture
*/
public static boolean isArm() {
return IS_ARM;
}
/**
* Returns if the JVM runs on a CPU using a Mac ARM architecture.
*
* @return if the JVM runs on a CPU using the Mac ARM architecture e.g. Apple M1.
*/
public static boolean isMacArm() {
return IS_MAC_ARM;
}
/**
* Acquires and returns the ClassMetrics for the provided {@code clazz}.
*
* @param clazz for which ClassMetrics shall be acquired
* @return the ClassMetrics for the provided {@code clazz}
* @throws IllegalArgumentException if no ClassMetrics can be acquired
* @see ClassMetrics
*/
@NotNull
public static ClassMetrics classMetrics(final Class<?> clazz) throws IllegalArgumentException {
return CLASS_METRICS_MAP.computeIfAbsent(clazz, Jvm::getClassMetrics);
}
private static ClassMetrics getClassMetrics(final Class<?> c) {
final Class<?> superclass = c.getSuperclass();
int start = Integer.MAX_VALUE, end = 0;
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) != 0)
continue;
if (!f.getType().isPrimitive())
continue;
int start0 = Math.toIntExact(UnsafeMemory.unsafeObjectFieldOffset(f));
int size = PRIMITIVE_SIZE.get(f.getType());
start = Math.min(start0, start);
end = Math.max(start0 + size, end);
}
if (superclass != null && superclass != Object.class) {
final ClassMetrics cm0 = getClassMetrics(superclass);
start = Math.min(cm0.offset(), start);
end = Math.max(cm0.offset() + cm0.length(), end);
validateClassMetrics(superclass, start, end);
}
validateClassMetrics(c, start, end);
return new ClassMetrics(start, end - start);
}
private static void validateClassMetrics(final Class<?> c,
final int start,
final int end) {
for (Field f : c.getDeclaredFields()) {
if ((f.getModifiers() & Modifier.STATIC) != 0)
continue;
if (f.getType().isPrimitive())
continue;
final int start0 = Math.toIntExact(UnsafeMemory.unsafeObjectFieldOffset(f));
if (start <= start0 && start0 < end) {
rethrow(new IllegalArgumentException(c + " is not suitable for raw copies due to " + f));
}
}
}
/**
* Returns the user's home directory (e.g. "/home/alice") or "."
* if the user's home director cannot be determined.
*
* @return the user's home directory (e.g. "/home/alice") or "."
* if the user's home director cannot be determined
*/
@NotNull
public static String userHome() {
return System.getProperty("user.home", ".");
}
public static boolean dontChain(final Class<?> tClass) {
return tClass.getAnnotation(DontChain.class) != null || tClass.getName().startsWith("java");
}
/**
* Returns if certain chronicle resources (such as memory regions) are traced.
* <p>
* Tracing resources incurs slightly less performance but provides a means
* of detecting proper release of resources.
*
* @return if certain chronicle resources (such as memory regions) are traced
*/
public static boolean isResourceTracing() {
return RESOURCE_TRACING;
}
/**
* Returns if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true".
* <p>
* This provides a more permissive boolean System systemPropertyKey flag where
* {@code -Dflag} {@code -Dflag=true} {@code -Dflag=yes} are all accepted.
*
* @param systemPropertyKey name to lookup
* @return if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true"
*/
public static boolean getBoolean(final String systemPropertyKey) {
return getBoolean(systemPropertyKey, false);
}
/**
* Returns if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true" or, if it does not exist,
* returns the provided {@code defaultValue}.
* <p>
* This provides a more permissive boolean System systemPropertyKey flag where
* {@code -Dflag} {@code -Dflag=true} {@code -Dflag=yes} are all accepted.
*
* @param systemPropertyKey name to lookup
* @param defaultValue value to be used if unknown
* @return if a System Property with the provided {@code systemPropertyKey}
* either exists, is set to "yes" or is set to "true" or, if it does not exist,
* returns the provided {@code defaultValue}.
*/
public static boolean getBoolean(final String systemPropertyKey, final boolean defaultValue) {
final String value = System.getProperty(systemPropertyKey);
if (value == null)
return defaultValue;
if (value.isEmpty())
return true;
final String trim = value.trim();
return defaultValue
? !ObjectUtils.isFalse(trim)
: ObjectUtils.isTrue(trim);
}
/**
* Parse a string as a decimal memory size with an optional scale.
* K/k = * 2<sup>10</sup>, M/m = 2<sup>20</sup>, G/g = 2<sup>10</sup>, T/t = 2<sup>40</sup>
* <p>
* trailing B/b/iB/ib are ignored.
* <table>
* <tr><td>100</td><td>100 bytes</td></tr>
* <tr><td>100b</td><td>100 bytes</td></tr>
* <tr><td>0.5kb</td><td>512 bytes</td></tr>
* <tr><td>0.125MB</td><td>128 KiB</td></tr>
* <tr><td>2M</td><td>2 MiB</td></tr>
* <tr><td>0.75GiB</td><td>768 MiB</td></tr>
* <tr><td>0.001TiB</td><td>1.024 GiB</td></tr>
* </table>
* </p>
*
* @param value size to parse
* @return the size
* @throws IllegalArgumentException if the string could be parsed
*/
public static long parseSize(@NotNull String value) throws IllegalArgumentException {
long factor = 1;
if (value.length() > 1) {
char last = value.charAt(value.length() - 1);
// assume we meant bytes, not bits
if (last == 'b' || last == 'B') {
value = value.substring(0, value.length() - 1);
last = value.charAt(value.length() - 1);
}
if (last == 'i') {
value = value.substring(0, value.length() - 1);
last = value.charAt(value.length() - 1);
}
if (Character.isLetter(last)) {
switch (last) {
case 't':
case 'T':
factor = 1L << 40;
break;
case 'g':
case 'G':
factor = 1L << 30;
break;
case 'm': // technically milli, but we will assume mega
case 'M':
factor = 1L << 20;
break;
case 'k':
case 'K':
factor = 1L << 10;
break;
default:
throw new IllegalArgumentException("Unrecognised suffix for size " + value);
}
value = value.substring(0, value.length() - 1);
}
}
double number = Double.parseDouble(value.trim());
factor *= number;
return factor;
}
/**
* Uses Jvm.parseSize to parse a system property or returns defaultValue if not present, empty or unparseable.
*
* @param property to look up
* @param defaultValue to use otherwise
* @return the size in bytes as a long
*/
public static long getSize(final String property, final long defaultValue) {
final String value = System.getProperty(property);
if (value == null || value.length() <= 0)
return defaultValue;
try {
return parseSize(value);
} catch (IllegalArgumentException iae) {
Jvm.warn().on(Jvm.class, "Unable to parse the property " + property + " as a size " + iae.getMessage() + " using " + defaultValue);
return defaultValue;
}
}
/**
* Returns the native address of the provided {@code byteBuffer}.
* <p>
* <em>Use with caution!</em>. Native address should always be carefully
* guarded to prevent unspecified results or even JVM crashes.
*
* @param byteBuffer from which to extract the native address
* @return the native address of the provided {@code byteBuffer}
*/
public static long address(@NotNull final ByteBuffer byteBuffer) {
return ((DirectBuffer) byteBuffer).address();
}
/**
* Returns the array byte base offset used by this JVM.
* <p>
* The value is the number of bytes that precedes the actual
* memory layout of a {@code byte[] } array in a java array object.
* <p>
* <em>Use with caution!</em>. Native address should always be carefully
* guarded to prevent unspecified results or even JVM crashes.
*
* @return the array byte base offset used by this JVM
*/
public static int arrayByteBaseOffset() {
return Unsafe.ARRAY_BYTE_BASE_OFFSET;
}
/**
* Employs a best-effort of preventing the provided {@code fc } from being automatically closed
* whenever the current thread gets interrupted.
* <p>
* If the effort failed, the provided {@code clazz} is used for logging purposes.
*
* @param clazz to use for logging should the effort fail.
* @param fc to prevent from automatically closing upon interrupt.
*/
public static void doNotCloseOnInterrupt(final Class<?> clazz, final FileChannel fc) {
if (Jvm.isJava9Plus())
doNotCloseOnInterrupt9(clazz, fc);
else
doNotCloseOnInterrupt8(clazz, fc);
}
private static void doNotCloseOnInterrupt8(final Class<?> clazz, final FileChannel fc) {
try {
final Field field = AbstractInterruptibleChannel.class
.getDeclaredField("interruptor");
Jvm.setAccessible(field);
final CommonInterruptible ci = new CommonInterruptible(clazz, fc);
field.set(fc, (Interruptible) thread -> ci.interrupt());
} catch (Throwable e) {
Jvm.warn().on(clazz, "Couldn't disable close on interrupt", e);
}
}
// based on a solution by https://stackoverflow.com/users/9199167/max-vollmer
// https://stackoverflow.com/a/52262779/57695
private static void doNotCloseOnInterrupt9(final Class<?> clazz, final FileChannel fc) {
try {
final Field field = AbstractInterruptibleChannel.class.getDeclaredField("interruptor");
final Class<?> interruptibleClass = field.getType();
Jvm.setAccessible(field);
final CommonInterruptible ci = new CommonInterruptible(clazz, fc);
field.set(fc, Proxy.newProxyInstance(
interruptibleClass.getClassLoader(),
new Class[]{interruptibleClass},
(p, m, a) -> {
if (m.getDeclaringClass() != Object.class)
ci.interrupt();
return ObjectUtils.defaultValue(m.getReturnType());
}));
} catch (Throwable e) {
Jvm.warn().on(clazz, "Couldn't disable close on interrupt", e);
}
}
/**
* Ensures that all the jars and other resources are added to the class path of the classloader
* associated by the provided {@code clazz}.
*
* @param clazz to use as a template.
*/
public static void addToClassPath(@NotNull final Class<?> clazz) {
ClassLoader cl = clazz.getClassLoader();
if (!(cl instanceof URLClassLoader))
return;
String property = System.getProperty(JAVA_CLASS_PATH);
Set<String> jcp = new LinkedHashSet<>();
Collections.addAll(jcp, property.split(File.pathSeparator));
jcp.addAll(jcp.stream()
.map(f -> new File(f).getAbsolutePath())
.collect(Collectors.toList()));
URLClassLoader ucl = (URLClassLoader) cl;
StringBuilder classpath = new StringBuilder(property);
for (URL url : ucl.getURLs()) {
try {
String path = Paths.get(url.toURI()).toString();
if (!jcp.contains(path)) {
if (isDebugEnabled(Jvm.class))
debug().on(Jvm.class, "Adding " + path + " to the classpath");
classpath.append(File.pathSeparator).append(path);
}
} catch (Throwable e) {
debug().on(Jvm.class, "Could not add URL " + url + " to classpath");
}
}
System.setProperty(JAVA_CLASS_PATH, classpath.toString());
}
/**
* Returns the System Property associated with the provided {@code systemPropertyKey}
* parsed as a {@code double} or, if no such parsable System Property exists,
* returns the provided {@code defaultValue}.
*
* @param systemPropertyKey to lookup in the System Properties
* @param defaultValue to be used if no parsable key association exists
* @return the System Property associated with the provided {@code systemPropertyKey}
* parsed as a {@code double} or, if no such parsable System Property exists,
* returns the provided {@code defaultValue}
*/
public static double getDouble(final String systemPropertyKey, final double defaultValue) {
final String value = System.getProperty(systemPropertyKey);
if (value != null)
try {
return Double.parseDouble(value);
} catch (NumberFormatException e) {
Jvm.debug().on(Jvm.class, "Unable to parse property " + systemPropertyKey + " as a double " + e);
}
return defaultValue;
}
/**
* Returns if a process with the provided {@code pid} process id is alive.
*
* @param pid the process id (pid) of the process to check
* @return if a process with the provided {@code pid} process id is alive
*/
public static boolean isProcessAlive(long pid) {
if (isWindows()) {
final String command = "cmd /c tasklist /FI \"PID eq " + pid + "\"";
return isProcessAlive0(pid, command);
}
if (isLinux() && PROC_EXISTS) {
return new File("/proc/" + pid).exists();
}
if (isMacOSX() || isLinux()) {
final String command = "ps -p " + pid;
return isProcessAlive0(pid, command);
}
throw new UnsupportedOperationException("Not supported on this OS");
}
private static boolean isProcessAlive0(final long pid, final String command) {
try {
InputStreamReader isReader = new InputStreamReader(
getRuntime().exec(command).getInputStream());
final BufferedReader bReader = new BufferedReader(isReader);
String strLine;
while ((strLine = bReader.readLine()) != null) {
if (strLine.contains(" " + pid + " ") || strLine.startsWith(pid + " ")) {
return true;
}
}
return false;
} catch (Exception ex) {
return true;
}
}
public static boolean isAzulZing() {
return IS_AZUL_ZING;
}
public static boolean isAzulZulu() {
return IS_AZUL_ZULU;
}
public static int objectHeaderSize() {
return OBJECT_HEADER_SIZE;
}
static class ObjectHeaderSizeChecker {
public int a;
}
static final class CommonInterruptible {
static final ThreadLocal<AtomicBoolean> insideTL = ThreadLocal.withInitial(AtomicBoolean::new);
private final Class<?> clazz;
private final FileChannel fc;
CommonInterruptible(Class<?> clazz, FileChannel fc) {
this.clazz = clazz;
this.fc = fc;
}
public void interrupt() {
final AtomicBoolean inside = insideTL.get();
if (inside.get())
return;
inside.set(true);
assert Thread.currentThread().isInterrupted();
if (Jvm.isDebugEnabled(getClass()))
Jvm.debug().on(clazz, fc + " not closed on interrupt");
inside.set(false);
}
}
// from https://stackoverflow.com/questions/62550828/is-there-a-lightweight-method-which-adds-a-safepoint-in-java-9
static final class Safepoint {
// must be volatile
private static volatile int one = 1;
public static void force() {
// trick only works from Java 9+
for (int i = 0; i < one; i++) ;
}
}
static final class ChainedSignalHandler implements SignalHandler {
final List<SignalHandler> handlers = new CopyOnWriteArrayList<>();
@Override
public void handle(final Signal signal) {
for (SignalHandler handler : handlers) {
try {
if (handler != null)
handler.handle(signal);
} catch (Throwable t) {
Jvm.warn().on(this.getClass(), "Problem handling signal", t);
}
}
}
}
/**
* @return Obtain the model of CPU on Linux or the os.arch on other OSes.
*/
public static String getCpuClass() {
return CpuClass.CPU_MODEL;
}
static final class CpuClass {
static final String CPU_MODEL;
static {
String model = System.getProperty("os.arch", "unknown");
try {
final Path path = Paths.get("/proc/cpuinfo");
if (Files.isReadable(path)) {
model = Files.lines(path)
.filter(line -> line.startsWith("model name"))
.map(line -> line.replaceAll(".*: ", ""))
.findFirst().orElse(model);
} else if (OS.isWindows()) {
String cmd = "wmic cpu get name";
Process process = new ProcessBuilder(cmd.split(" "))
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
model = reader.lines()
.map(String::trim)
.filter(s -> !"Name".equals(s) && !s.isEmpty())
.findFirst().orElse(model);
}
try {
int ret = process.waitFor();
if (ret != 0)
Jvm.warn().on(CpuClass.class, "process " + cmd + " returned " + ret);
} catch (InterruptedException e) {
Jvm.warn().on(CpuClass.class, "process " + cmd + " waitFor threw ", e);
}
process.destroy();
} else if (OS.isMacOSX()) {
String cmd = "sysctl -a";
Process process = new ProcessBuilder(cmd.split(" "))
.redirectErrorStream(true)
.start();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
model = reader.lines()
.map(String::trim)
.filter(s -> s.startsWith("machdep.cpu.brand_string"))
.map(line -> line.replaceAll(".*: ", ""))
.findFirst().orElse(model);
}
try {
int ret = process.waitFor();
if (ret != 0)
Jvm.warn().on(CpuClass.class, "process " + cmd + " returned " + ret);
} catch (InterruptedException e) {
Jvm.warn().on(CpuClass.class, "process " + cmd + " waitFor threw ", e);
}
process.destroy();
}
} catch (IOException e) {
Jvm.debug().on(CpuClass.class, "Unable to read cpuinfo", e);
}
CPU_MODEL = model;
}
}
}
|
Document Jvm exception handlers #211
|
src/main/java/net/openhft/chronicle/core/Jvm.java
|
Document Jvm exception handlers #211
|
|
Java
|
apache-2.0
|
6ffe4f33cc01b354a82ed7a36d6048a84b13fde8
| 0
|
agwlvssainokuni/springapp,agwlvssainokuni/springapp,agwlvssainokuni/springapp,agwlvssainokuni/springapp
|
/*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.goods.crypto;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
public class AESCryptoTest {
@Test
public void testDefault() throws Exception {
AESCrypto crypto = new AESCrypto();
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testCBC() throws Exception {
AESCrypto crypto = new AESCrypto();
crypto.setAlgorithm("AES/CBC/PKCS5Padding");
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testUsingKeyCrypto() throws Exception {
byte[] key = RandomUtils.nextBytes(16);
AESCrypto crypto0 = new AESCrypto();
crypto0.setSecretKeyBytes(key);
AESCrypto keyCrypto = new AESCrypto();
keyCrypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
AESCrypto crypto1 = new AESCrypto();
crypto1.setKeyCrypto(keyCrypto);
crypto1.setSecretKeyBytes(keyCrypto.encrypt(key));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc0 = crypto0.encrypt(plain);
byte[] enc1 = crypto1.encrypt(plain);
assertThat(enc1, is(not(enc0)));
byte[] dec0 = crypto0.decrypt(enc0);
byte[] dec1 = crypto1.decrypt(enc1);
assertThat(dec0, is(plain));
assertThat(dec1, is(plain));
}
}
@Test
public void testRandomizing() {
int size = 10000;
for (int i = 0; i < 10; i++) {
byte[] key = RandomUtils.nextBytes(16);
byte[] plain = RandomUtils.nextBytes(1024);
AESCrypto crypto = new AESCrypto();
crypto.setSecretKeyBytes(key);
Set<String> set = new HashSet<>();
for (int j = 0; j < size; j++) {
byte[] enc = crypto.encrypt(plain);
set.add(Hex.encodeHexString(enc));
}
assertThat(set.size(), is(size));
}
}
}
|
goods/src/test/java/cherry/goods/crypto/AESCryptoTest.java
|
/*
* Copyright 2014,2015 agwlvssainokuni
*
* 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 cherry.goods.crypto;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
public class AESCryptoTest {
@Test
public void testDefault() throws Exception {
AESCrypto crypto = new AESCrypto();
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testCBC() throws Exception {
AESCrypto crypto = new AESCrypto();
crypto.setAlgorithm("AES/CBC/PKCS5Padding");
crypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc = crypto.encrypt(plain);
byte[] dec = crypto.decrypt(enc);
assertThat(dec, is(plain));
}
}
@Test
public void testUsingKeyCrypto() throws Exception {
byte[] key = RandomUtils.nextBytes(16);
AESCrypto crypto0 = new AESCrypto();
crypto0.setSecretKeyBytes(key);
AESCrypto keyCrypto = new AESCrypto();
keyCrypto.setSecretKeyBytes(RandomUtils.nextBytes(16));
AESCrypto crypto1 = new AESCrypto();
crypto1.setKeyCrypto(keyCrypto);
crypto1.setSecretKeyBytes(keyCrypto.encrypt(key));
for (int i = 0; i < 100; i++) {
byte[] plain = RandomUtils.nextBytes(1024);
byte[] enc0 = crypto0.encrypt(plain);
byte[] enc1 = crypto1.encrypt(plain);
assertThat(enc1, is(not(enc0)));
byte[] dec0 = crypto0.decrypt(enc0);
byte[] dec1 = crypto1.decrypt(enc1);
assertThat(dec0, is(plain));
assertThat(dec1, is(plain));
}
}
}
|
goods: 暗号機能
AES暗号機能のテストケース補強。
|
goods/src/test/java/cherry/goods/crypto/AESCryptoTest.java
|
goods: 暗号機能
|
|
Java
|
apache-2.0
|
3253b1d2af80b061935deaf63498f5143d054469
| 0
|
RuthRainbow/anemone
|
package group7.anemone;
import group7.anemone.Genetics.Genome;
import group7.anemone.Genetics.NeatEdge;
import group7.anemone.Genetics.NeatNode;
import group7.anemone.MNetwork.MFactory;
import group7.anemone.MNetwork.MNetwork;
import group7.anemone.MNetwork.MNeuron;
import group7.anemone.MNetwork.MNeuronParams;
import group7.anemone.MNetwork.MNeuronState;
import group7.anemone.MNetwork.MSimulation;
import group7.anemone.MNetwork.MSimulationConfig;
import group7.anemone.MNetwork.MSynapse;
import group7.anemone.MNetwork.MVec3f;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import processing.core.PApplet;
public class Agent extends SimulationObject implements Serializable {
private static final long serialVersionUID = -6755516656827008579L;
transient PApplet parent;
/* Anatomical parameters. */
public static int configNumSegments = 7;
final double visionRange = 100;
final double fov = 90;
/* Physics state. */
private final Point2D.Double speed = new Point2D.Double(0, 0);
private double viewHeading = 0; // in degrees 0-360
/* The agent's genome (from which the brain is generated). */
private final Genome genome;
/* Brain state. */
private MNetwork mnetwork;
/* Brain simulation instance. */
private MSimulation msimulation;
/* Interface between the world and the brain. */
private final NInterface ninterface = new NInterface(configNumSegments);
/* Health state and stats. */
private double fitness = 2;
private double health = 1;
private int numFoodsEaten = 0;
private int numWallsHit = 0;
private int age = 0; // Age of agent in number of updates.
//JBox2D variables
private transient World world;
protected transient Body body;
/* Objects of interest within the agent's visual field. */
private ArrayList<SightInformation> canSee
= new ArrayList<SightInformation>();
/**
* Instanciates an agent at a given coordinate in the simulation, with a
* given orientation and genome.
*
* The constructor uses genome to construct the neural network which is
* simulated in order to influence the physical state of the agent.
*
* @param coords initial agent position within the world
* @param viewHeading initial orientation of the agent
* @param p
* @param genome the genome to be used to construct the brain
*/
public Agent(Point2D.Double coords, double viewHeading, PApplet p,
Genome genome, World world) {
super(coords);
this.parent = p;
this.viewHeading = viewHeading;
this.genome = genome;
createNeuralNet();
calculateNetworkPositions(false);
this.world = world;
setupBox2d();
thrust(1);
}
public Agent(Point2D.Double coords){
super(coords);
this.genome = null;
}
private void setupBox2d(){
float box2Dx = (float) (coords.x/Simulation.meterToPixel);
float box2Dy = (float) (coords.y/Simulation.meterToPixel);
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(box2Dx,box2Dy);
CircleShape cs = new CircleShape();
cs.m_radius = 10.0f/Simulation.meterToPixel;
FixtureDef fd = new FixtureDef();
fd.shape = cs;
fd.density = 0.6f;
fd.friction = 0.3f;
fd.restitution = 0.5f;
fd.filter.categoryBits = Collision.TYPE_AGENT;
if(this instanceof Enemy){
fd.filter.maskBits = Collision.TYPE_AGENT | Collision.TYPE_WALL | Collision.TYPE_WALL_AGENT;
}else{
fd.filter.maskBits = Collision.TYPE_AGENT | Collision.TYPE_WALL | Collision.TYPE_WALL_ENEMY;
}
fd.userData = this;
body = world.createBody(bd);
body.createFixture(fd);
}
/**
* Uses the agent's genome to construct a neural network.
*/
private void createNeuralNet() {
MSimulationConfig simConfig;
HashMap<Integer, MNeuron> neuronMap
= new HashMap<Integer, MNeuron>();
ArrayList<MNeuron> neurons = new ArrayList<MNeuron>();
ArrayList<MSynapse> synapses = new ArrayList<MSynapse>();
/* Create neurons. */
for (NeatNode nn : genome.getNodes()) {
int id = nn.getId();
MNeuronParams params = nn.getParams();
MNeuronState state =
MFactory.createInitialRSNeuronState();
/* Create a neuron. */
MNeuron neuron = new MNeuron(params, state, id);
/* Add it to temporary NID->Neuron map. */
neuronMap.put(id, neuron);
/* Add neuron to the list. */
neurons.add(neuron);
}
/* Create synapses. */
for (NeatEdge g : genome.getGene()) {
/* Get the synapse information. */
NeatNode preNode = g.getIn();
NeatNode postNode = g.getOut();
double weight = g.getWeight();
int delay = g.getDelay();
Integer preNid = new Integer(preNode.getId());
Integer postNid = new Integer(postNode.getId());
/* Find the pre and post neurons. */
MNeuron preNeuron = neuronMap.get(preNid);
MNeuron postNeuron = neuronMap.get(postNid);
/* Create the synapse. */
MSynapse synapse = new MSynapse(preNeuron, postNeuron,
weight, delay);
/*
Add the synapse to the pre and post neuron synapse list
*/
ArrayList<MSynapse> postSynapses
= preNeuron.getPostSynapses();
ArrayList<MSynapse> preSynapses
= postNeuron.getPreSynapses();
postSynapses.add(synapse);
preSynapses.add(synapse);
preNeuron.setPostSynapses(postSynapses);
postNeuron.setPreSynapses(preSynapses);
/* Add the synapse to the list. */
synapses.add(synapse);
}
/* Create the network. */
this.mnetwork = new MNetwork(neurons, synapses);
/* Create and set the simulation configuration parameters. */
simConfig = new MSimulationConfig(20);
/* Create the simulation instance with our network. */
this.msimulation = new MSimulation(this.mnetwork, simConfig);
}
/**
* Uses the sensory components of the interface to provide sensory input
* current to the brain.
*/
private void applySensoryInputToBrain() {
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
/* Temporarily hardcode id's of neurons of interest. */
int numVSegs = Agent.configNumSegments;
int firstVFoodNid = 3;
int lastVFoodNid = firstVFoodNid + numVSegs - 1;
int firstVWallNid = lastVFoodNid + 1;
int lastVWallNid = firstVWallNid + numVSegs - 1;
int firstVEnemyNid = lastVWallNid + 1;
int lastVEnemyNid = firstVEnemyNid + numVSegs - 1;
/*
Provide input current the network using the sensory
components of the interface.
*/
for (MNeuron n : neurons) {
double current;
int index;
int id = n.getID();
/* If the neuron is a food visual neuron. */
if (id >= firstVFoodNid && id <= lastVFoodNid) {
index = id - 3;
current = ninterface.affectors.vFood[index];
n.addCurrent(60.0*current);
} /* If the neuron is a wall visual neuron. */ else if (id >= firstVWallNid && id <= lastVWallNid) {
index = id - numVSegs - 3;
current = ninterface.affectors.vWall[index];
n.addCurrent(60.0*current);
} /* If the neuron is an enemy visual neuron. */ else if (id >= firstVEnemyNid && id <= lastVEnemyNid) {
index = id - 2 * numVSegs - 3;
current = ninterface.affectors.vEnemy[index];
n.addCurrent(60.0*current);
}
}
}
/**
* Applies sensory input from the interface to the brain and steps the
* brain simulation.
*/
private void updateMNetwork() {
/*
Having applied the network inputs, update the brain simulation.
*/
msimulation.step();
}
/**
* Inspects the brain's motor neurons for activity and performs motor
* actions accordingly (thrust and turning).
*/
private void applyMotorOutputs() {
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
int thrustNeuronID = 0;
int turnNegativeNeuronID = 1;
int turnPositiveNeuronID = 2;
for (MNeuron n : neurons) {
/*
Perform physical actions if effector neurons are firing.
*/
if (n.getID() == thrustNeuronID) {
if (n.isFiring()) {
thrust(2);
}
}
if (n.getID() == turnNegativeNeuronID) {
if (n.isFiring()) {
changeViewHeading(-20.0);
}
}
if (n.getID() == turnPositiveNeuronID) {
if (n.isFiring()) {
changeViewHeading(20.0);
}
}
}
}
public Genome getStringRep() {
return this.genome;
}
public double getFitness() {
return this.fitness;
}
//Use meter/pixel ratio to convert to draw coords
void updatePosition() {
coords.x = body.getPosition().x*Simulation.meterToPixel;
coords.y = body.getPosition().y*Simulation.meterToPixel;
//System.out.println("Box2D coords: "+body.getPosition().x+" , "+body.getPosition().y+" Pixel coords: "+coords.x+" , "+coords.y);
}
/**
* Updates the sensory components of neural interface.
*/
void updateSensors() {
int visionDim = ninterface.affectors.getVisionDim();
double distance;
/* Update food vision variables. */
for (int i = 0; i < visionDim; i++) {
/* Food sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_FOOD);
ninterface.affectors.vFood[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Ally sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_AGENT);
ninterface.affectors.vAlly[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Enemy sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_ENEMY);
ninterface.affectors.vEnemy[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Wall sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_WALL);
ninterface.affectors.vWall[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
}
}
void update() {
updateSensors();
applySensoryInputToBrain();
for (int i = 0; i < 4; i++) {
updateMNetwork();
}
applyMotorOutputs();
updatePosition();
age++;
health -= 0.001;
fitness = (1.0 + numFoodsEaten) / (1.0 + numWallsHit);
}
public void updateBrainOnly() {
updateSensors();
applySensoryInputToBrain();
for (int i = 0; i < 4; i++) {
updateMNetwork();
}
applyMotorOutputs();
}
protected void ateFood() {
numFoodsEaten++;
}
protected void hitWall() {
numWallsHit++;
}
//Pre-calculates the coordinates of each neuron in the network
private ArrayList<MNeuron> placed;
private HashMap<Integer, Integer> maxInLevel;
private int maxLevel = 0;
private int maxHeight = 0;
public void calculateNetworkPositions(boolean useLayered) {
placed = new ArrayList<MNeuron>(); //store coordinates of placed neurons
maxInLevel = new HashMap<Integer, Integer>(); //store max y coordinate at each level of tree
maxInLevel.put(0, 0);
maxLevel = 0;
maxHeight = 0;
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
ArrayList<MSynapse> synapses = mnetwork.getSynapses();
//TODO: place nodes in set position then spread out using algorithm below
//TODO: normalise to -125 to 125
if(useLayered){
for(MSynapse s : mnetwork.getSynapses()){ //determine the x, y coordinates for each node based on links
MNeuron pre = s.getPreNeuron();
MNeuron post = s.getPostNeuron();
int level = 0;
if(!placed.contains(pre)){
if(placed.contains(post)){ //pre node not placed but post is, place at level - 1
level = (int) (post.params.spatialCoords.x / 20.0) - 1;
}
int max = maxValue(level);
addNode(level, max, pre);
}
if(!placed.contains(post)){
if(placed.contains(pre)){ //post node not placed but pre is, place at level + 1
level = (int) (pre.params.spatialCoords.x / 20.0);
}
level++;
int max = maxValue(level);
addNode(level, max, post);
}
if(pre.params.spatialCoords.x == post.params.spatialCoords.x) pre.params.spatialCoords.z += 20;
}
//offset nodes centrally
int offsetX = -maxLevel * 10;
int offsetY = -maxHeight * 10;
for(MNeuron n : mnetwork.getNeurons()){
n.params.spatialCoords.x += offsetX;
n.params.spatialCoords.y += offsetY;
}
mnetwork.setNeurons(neurons);
return;
}
//Force directed graph drawing
float area = 250 * 250 * 250; //The size of the area
//float C = 2;
float k = (float) Math.sqrt(area / mnetwork.getVertexNumber());
int setIterations = 250;
double temp = 25;
float kPow = (float) Math.pow(k, 2);
for (int x = 0; x < neurons.size(); x++) {
Random generator = new Random();
int xAx = 125 - generator.nextInt(250);
int yAx = 125 - generator.nextInt(250);
int zAx = 125 - generator.nextInt(250);
neurons.get(x).params.spatialCoords = new MVec3f(xAx, yAx, zAx);
}
//For a pre set number of iterations
for (int i = 0; i < setIterations; i++) {
//Calculate the repulsive force between neurons
for (MNeuron v : neurons) {
v.disp = MVec3f.zero();
for (MNeuron u : neurons) {
if (v != u) {
//Calculate delta, the difference in position between the two neurons
MVec3f delta = v.getCoords().subtract(u.getCoords());
MVec3f absDelta = delta.abs();
if (delta.x != 0) {
v.disp.x += delta.x / absDelta.x * kPow / absDelta.x;
}
if (delta.y != 0) {
v.disp.y += delta.y / absDelta.y * kPow / absDelta.y;
}
if (delta.z != 0) {
v.disp.z += delta.z / absDelta.z * kPow / absDelta.z;
}
}
}
}
//Calculate the attractive forces
for (MSynapse e : synapses) {
MNeuron v = e.getPreNeuron();
MNeuron u = e.getPostNeuron();
//Calculate delta, the difference in position between the two neurons
MVec3f delta = v.getCoords().subtract(u.getCoords());
MVec3f deltaPow = delta.pow(2);
MVec3f absDelta = delta.abs();
if (delta.x != 0) {
v.disp.x -= delta.x / absDelta.x * deltaPow.x / k;
}
if (delta.y != 0) {
v.disp.y -= delta.y / absDelta.y * deltaPow.y / k;
}
if (delta.z != 0) {
v.disp.z -= delta.z / absDelta.z * deltaPow.z / k;
}
if (delta.x != 0) {
u.disp.x += delta.x / absDelta.x * deltaPow.x / k;
}
if (delta.y != 0) {
u.disp.y += delta.y / absDelta.y * deltaPow.y / k;
}
if (delta.z != 0) {
u.disp.z += delta.z / absDelta.z * deltaPow.z / k;
}
}
//Limit maximum displacement by the temperature
//Also prevent the thing from being displaced outside the frame
for (MNeuron v : neurons) {
if (v.disp.x != 0) {
v.getCoords().x += v.disp.x / Math.abs(v.disp.x) * Math.min(Math.abs(v.disp.x), temp);
}
if (v.disp.y != 0) {
v.getCoords().y += v.disp.y / Math.abs(v.disp.y) * Math.min(Math.abs(v.disp.y), temp);
}
if (v.disp.z != 0) {
v.getCoords().z += v.disp.z / Math.abs(v.disp.z) * Math.min(Math.abs(v.disp.z), temp);
}
v.getCoords().x = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().x));
v.getCoords().y = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().y));
v.getCoords().z = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().z));
}
//Reduce temperature
temp = temp - 0.5;
if (temp == 0) {
temp = 1;
}
}
mnetwork.setNeurons(neurons);
}
private void addNode(int level, int max, MNeuron node) {
node.params.spatialCoords.x = level * 20;
node.params.spatialCoords.y = max;
node.params.spatialCoords.z = 0;
maxInLevel.put(level, max + 20);
placed.add(node);
}
private int maxValue(int level) {
int max = 0;
if (!maxInLevel.containsKey(level)) {
maxInLevel.put(level, 0);
maxLevel++;
} else {
max = maxInLevel.get(level);
}
maxHeight = Math.max(maxHeight, (max / 20));
return max;
}
public void updateCanSee(ArrayList<SightInformation> see) {
canSee = see;
}
public ArrayList<SightInformation> getCanSee() {
return canSee;
}
protected void thrust(double strength) {
double x = strength * Math.cos(viewHeading * Math.PI / 180) * 400;
double y = strength * Math.sin(viewHeading * Math.PI / 180) * 400;
float box2Dx = (float) (x/Simulation.meterToPixel);
float box2Dy = (float) (y/Simulation.meterToPixel);
if(body != null){
Vec2 force = new Vec2(box2Dx,box2Dy);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body.applyLinearImpulse(force, point);
}
}
protected void changeViewHeading(double h) {
viewHeading += h;
}
protected void updateHealth(double h) {
health += h;
health = Math.min(1, health);
}
protected void updateFitness(double value) {
fitness += value;
}
//returns the distance of the closest object in a specified segment, -1 if none found.
public double viewingObjectOfTypeInSegment(int segment, int type) {
ArrayList<SightInformation> filtered = new ArrayList<SightInformation>();
for (SightInformation si : canSee) { //filter out those objects of type that are in the specified segment
if (si.getType() == type && si.getDistanceFromLower() >= ((double) segment / configNumSegments) && si.getDistanceFromLower() < ((segment + 1.0) / configNumSegments)) {
filtered.add(si);
}
}
if (filtered.size() == 0) {
return -1;
}
double dist = Double.MAX_VALUE;
for (SightInformation si : filtered) {
dist = Math.min(dist, si.getDistance());
}
return dist / visionRange;
}
public void stop() {
speed.x = 0;
speed.y = 0;
}
public void setX(int x) {
coords.x = x;
}
public void setY(int y) {
coords.y = y;
}
public double getHealth() {
return health;
}
public double getViewHeading() {
return viewHeading;
}
public double getVisionRange() {
return visionRange;
}
public ArrayList<SightInformation> getAllViewingObjects() {
return canSee;
}
int getNumSegments() {
return configNumSegments;
}
public double getFOV() {
return fov;
}
public double getChangeX() {
return speed.x;
}
public double getChangeY() {
return speed.y;
}
public double getMovingAngle() {
double angle = 0;
if (getChangeX() == 0) {
if (getChangeY() < 0) {
angle = -90;
} else {
angle = 90;
}
} else {
angle = Math.atan((getChangeY()) / (getChangeX())) * 180.0 / Math.PI;
}
if (getChangeX() > 0) {
if (getChangeY() < 0) {
angle = 360 + angle;
}
} else {
if (getChangeY() >= 0) {
angle = 180 + angle;
} else {
angle += 180;
}
}
return angle;
}
public double getMovingSpeed() {
return Math.sqrt(Math.pow((float) (getChangeX()), 2) + Math.pow((float) (getChangeY()), 2));
}
public MNetwork getNetwork() {
return mnetwork;
}
NInterface getInterface() {
return ninterface;
}
public int getSpeciesId() {
return genome.getSpeciesId();
}
public int getAge() {
return this.age;
}
public int getType(){
return Collision.TYPE_AGENT;
}
}
|
src/main/java/group7/anemone/Agent.java
|
package group7.anemone;
import group7.anemone.Genetics.Genome;
import group7.anemone.Genetics.NeatEdge;
import group7.anemone.Genetics.NeatNode;
import group7.anemone.MNetwork.MFactory;
import group7.anemone.MNetwork.MNetwork;
import group7.anemone.MNetwork.MNeuron;
import group7.anemone.MNetwork.MNeuronParams;
import group7.anemone.MNetwork.MNeuronState;
import group7.anemone.MNetwork.MSimulation;
import group7.anemone.MNetwork.MSimulationConfig;
import group7.anemone.MNetwork.MSynapse;
import group7.anemone.MNetwork.MVec3f;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
import processing.core.PApplet;
public class Agent extends SimulationObject implements Serializable {
private static final long serialVersionUID = -6755516656827008579L;
transient PApplet parent;
/* Anatomical parameters. */
public static int configNumSegments = 7;
final double visionRange = 100;
final double fov = 90;
/* Physics state. */
private final Point2D.Double speed = new Point2D.Double(0, 0);
private double viewHeading = 0; // in degrees 0-360
/* The agent's genome (from which the brain is generated). */
private final Genome genome;
/* Brain state. */
private MNetwork mnetwork;
/* Brain simulation instance. */
private MSimulation msimulation;
/* Interface between the world and the brain. */
private final NInterface ninterface = new NInterface(configNumSegments);
/* Health state and stats. */
private double fitness = 2;
private double health = 1;
private int numFoodsEaten = 0;
private int numWallsHit = 0;
private int age = 0; // Age of agent in number of updates.
//JBox2D variables
private transient World world;
protected transient Body body;
/* Objects of interest within the agent's visual field. */
private ArrayList<SightInformation> canSee
= new ArrayList<SightInformation>();
/**
* Instanciates an agent at a given coordinate in the simulation, with a
* given orientation and genome.
*
* The constructor uses genome to construct the neural network which is
* simulated in order to influence the physical state of the agent.
*
* @param coords initial agent position within the world
* @param viewHeading initial orientation of the agent
* @param p
* @param genome the genome to be used to construct the brain
*/
public Agent(Point2D.Double coords, double viewHeading, PApplet p,
Genome genome, World world) {
super(coords);
this.parent = p;
this.viewHeading = viewHeading;
this.genome = genome;
createNeuralNet();
calculateNetworkPositions(false);
this.world = world;
setupBox2d();
thrust(1);
}
public Agent(Point2D.Double coords){
super(coords);
this.genome = null;
}
private void setupBox2d(){
float box2Dx = (float) (coords.x/Simulation.meterToPixel);
float box2Dy = (float) (coords.y/Simulation.meterToPixel);
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(box2Dx,box2Dy);
CircleShape cs = new CircleShape();
cs.m_radius = 10.0f/Simulation.meterToPixel;
FixtureDef fd = new FixtureDef();
fd.shape = cs;
fd.density = 0.6f;
fd.friction = 0.3f;
fd.restitution = 0.5f;
fd.filter.categoryBits = Collision.TYPE_AGENT;
if(this instanceof Enemy){
fd.filter.maskBits = Collision.TYPE_AGENT | Collision.TYPE_WALL | Collision.TYPE_WALL_AGENT;
}else{
fd.filter.maskBits = Collision.TYPE_AGENT | Collision.TYPE_WALL | Collision.TYPE_WALL_ENEMY;
}
fd.userData = this;
body = world.createBody(bd);
body.createFixture(fd);
}
/**
* Uses the agent's genome to construct a neural network.
*/
private void createNeuralNet() {
MSimulationConfig simConfig;
HashMap<Integer, MNeuron> neuronMap
= new HashMap<Integer, MNeuron>();
ArrayList<MNeuron> neurons = new ArrayList<MNeuron>();
ArrayList<MSynapse> synapses = new ArrayList<MSynapse>();
/* Create neurons. */
for (NeatNode nn : genome.getNodes()) {
int id = nn.getId();
MNeuronParams params = nn.getParams();
MNeuronState state =
MFactory.createInitialRSNeuronState();
/* Create a neuron. */
MNeuron neuron = new MNeuron(params, state, id);
/* Add it to temporary NID->Neuron map. */
neuronMap.put(id, neuron);
/* Add neuron to the list. */
neurons.add(neuron);
}
/* Create synapses. */
for (NeatEdge g : genome.getGene()) {
/* Get the synapse information. */
NeatNode preNode = g.getIn();
NeatNode postNode = g.getOut();
double weight = g.getWeight();
int delay = g.getDelay();
Integer preNid = new Integer(preNode.getId());
Integer postNid = new Integer(postNode.getId());
/* Find the pre and post neurons. */
MNeuron preNeuron = neuronMap.get(preNid);
MNeuron postNeuron = neuronMap.get(postNid);
/* Create the synapse. */
MSynapse synapse = new MSynapse(preNeuron, postNeuron,
weight, delay);
/*
Add the synapse to the pre and post neuron synapse list
*/
ArrayList<MSynapse> postSynapses
= preNeuron.getPostSynapses();
ArrayList<MSynapse> preSynapses
= postNeuron.getPreSynapses();
postSynapses.add(synapse);
preSynapses.add(synapse);
preNeuron.setPostSynapses(postSynapses);
postNeuron.setPreSynapses(preSynapses);
/* Add the synapse to the list. */
synapses.add(synapse);
}
/* Create the network. */
this.mnetwork = new MNetwork(neurons, synapses);
/* Create and set the simulation configuration parameters. */
simConfig = new MSimulationConfig(20);
/* Create the simulation instance with our network. */
this.msimulation = new MSimulation(this.mnetwork, simConfig);
}
/**
* Uses the sensory components of the interface to provide sensory input
* current to the brain.
*/
private void applySensoryInputToBrain() {
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
/* Temporarily hardcode id's of neurons of interest. */
int numVSegs = Agent.configNumSegments;
int firstVFoodNid = 3;
int lastVFoodNid = firstVFoodNid + numVSegs - 1;
int firstVWallNid = lastVFoodNid + 1;
int lastVWallNid = firstVWallNid + numVSegs - 1;
int firstVEnemyNid = lastVWallNid + 1;
int lastVEnemyNid = firstVEnemyNid + numVSegs - 1;
/*
Provide input current the network using the sensory
components of the interface.
*/
for (MNeuron n : neurons) {
double current;
int index;
int id = n.getID();
/* If the neuron is a food visual neuron. */
if (id >= firstVFoodNid && id <= lastVFoodNid) {
index = id - 3;
current = ninterface.affectors.vFood[index];
n.addCurrent(60.0*current);
} /* If the neuron is a wall visual neuron. */ else if (id >= firstVWallNid && id <= lastVWallNid) {
index = id - numVSegs - 3;
current = ninterface.affectors.vWall[index];
n.addCurrent(60.0*current);
} /* If the neuron is an enemy visual neuron. */ else if (id >= firstVEnemyNid && id <= lastVEnemyNid) {
index = id - 2 * numVSegs - 3;
current = ninterface.affectors.vEnemy[index];
n.addCurrent(60.0*current);
}
}
}
/**
* Applies sensory input from the interface to the brain and steps the
* brain simulation.
*/
private void updateMNetwork() {
/*
Having applied the network inputs, update the brain simulation.
*/
msimulation.step();
}
/**
* Inspects the brain's motor neurons for activity and performs motor
* actions accordingly (thrust and turning).
*/
private void applyMotorOutputs() {
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
int thrustNeuronID = 0;
int turnNegativeNeuronID = 1;
int turnPositiveNeuronID = 2;
for (MNeuron n : neurons) {
/*
Perform physical actions if effector neurons are firing.
*/
if (n.getID() == thrustNeuronID) {
if (n.isFiring()) {
thrust(2);
}
}
if (n.getID() == turnNegativeNeuronID) {
if (n.isFiring()) {
changeViewHeading(-20.0);
}
}
if (n.getID() == turnPositiveNeuronID) {
if (n.isFiring()) {
changeViewHeading(20.0);
}
}
}
}
public Genome getStringRep() {
return this.genome;
}
public double getFitness() {
return this.fitness;
}
//Use meter/pixel ratio to convert to draw coords
void updatePosition() {
coords.x = body.getPosition().x*Simulation.meterToPixel;
coords.y = body.getPosition().y*Simulation.meterToPixel;
//System.out.println("Box2D coords: "+body.getPosition().x+" , "+body.getPosition().y+" Pixel coords: "+coords.x+" , "+coords.y);
}
/**
* Updates the sensory components of neural interface.
*/
void updateSensors() {
int visionDim = ninterface.affectors.getVisionDim();
double distance;
/* Update food vision variables. */
for (int i = 0; i < visionDim; i++) {
/* Food sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_FOOD);
ninterface.affectors.vFood[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Ally sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_AGENT);
ninterface.affectors.vAlly[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Enemy sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_ENEMY);
ninterface.affectors.vEnemy[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
/* Wall sensory neurons. */
distance = viewingObjectOfTypeInSegment(i,
Collision.TYPE_WALL);
ninterface.affectors.vWall[i]
= distance < 0.0 ? 1.0 : 1.0 - distance;
}
}
void update() {
updateSensors();
applySensoryInputToBrain();
for (int i = 0; i < 4; i++) {
updateMNetwork();
}
applyMotorOutputs();
updatePosition();
age++;
health -= 0.001;
fitness = (1.0 + numFoodsEaten) / (1.0 + numWallsHit);
}
public void updateBrainOnly() {
updateSensors();
applySensoryInputToBrain();
for (int i = 0; i < 4; i++) {
updateMNetwork();
}
applyMotorOutputs();
}
protected void ateFood() {
numFoodsEaten++;
}
protected void hitWall() {
numWallsHit++;
System.out.println("Numwalls hit is "+numWallsHit);
}
//Pre-calculates the coordinates of each neuron in the network
private ArrayList<MNeuron> placed;
private HashMap<Integer, Integer> maxInLevel;
private int maxLevel = 0;
private int maxHeight = 0;
public void calculateNetworkPositions(boolean useLayered) {
placed = new ArrayList<MNeuron>(); //store coordinates of placed neurons
maxInLevel = new HashMap<Integer, Integer>(); //store max y coordinate at each level of tree
maxInLevel.put(0, 0);
maxLevel = 0;
maxHeight = 0;
ArrayList<MNeuron> neurons = mnetwork.getNeurons();
ArrayList<MSynapse> synapses = mnetwork.getSynapses();
//TODO: place nodes in set position then spread out using algorithm below
//TODO: normalise to -125 to 125
if(useLayered){
for(MSynapse s : mnetwork.getSynapses()){ //determine the x, y coordinates for each node based on links
MNeuron pre = s.getPreNeuron();
MNeuron post = s.getPostNeuron();
int level = 0;
if(!placed.contains(pre)){
if(placed.contains(post)){ //pre node not placed but post is, place at level - 1
level = (int) (post.params.spatialCoords.x / 20.0) - 1;
}
int max = maxValue(level);
addNode(level, max, pre);
}
if(!placed.contains(post)){
if(placed.contains(pre)){ //post node not placed but pre is, place at level + 1
level = (int) (pre.params.spatialCoords.x / 20.0);
}
level++;
int max = maxValue(level);
addNode(level, max, post);
}
if(pre.params.spatialCoords.x == post.params.spatialCoords.x) pre.params.spatialCoords.z += 20;
}
//offset nodes centrally
int offsetX = -maxLevel * 10;
int offsetY = -maxHeight * 10;
for(MNeuron n : mnetwork.getNeurons()){
n.params.spatialCoords.x += offsetX;
n.params.spatialCoords.y += offsetY;
}
mnetwork.setNeurons(neurons);
return;
}
//Force directed graph drawing
float area = 250 * 250 * 250; //The size of the area
//float C = 2;
float k = (float) Math.sqrt(area / mnetwork.getVertexNumber());
int setIterations = 250;
double temp = 25;
float kPow = (float) Math.pow(k, 2);
for (int x = 0; x < neurons.size(); x++) {
Random generator = new Random();
int xAx = 125 - generator.nextInt(250);
int yAx = 125 - generator.nextInt(250);
int zAx = 125 - generator.nextInt(250);
neurons.get(x).params.spatialCoords = new MVec3f(xAx, yAx, zAx);
}
//For a pre set number of iterations
for (int i = 0; i < setIterations; i++) {
//Calculate the repulsive force between neurons
for (MNeuron v : neurons) {
v.disp = MVec3f.zero();
for (MNeuron u : neurons) {
if (v != u) {
//Calculate delta, the difference in position between the two neurons
MVec3f delta = v.getCoords().subtract(u.getCoords());
MVec3f absDelta = delta.abs();
if (delta.x != 0) {
v.disp.x += delta.x / absDelta.x * kPow / absDelta.x;
}
if (delta.y != 0) {
v.disp.y += delta.y / absDelta.y * kPow / absDelta.y;
}
if (delta.z != 0) {
v.disp.z += delta.z / absDelta.z * kPow / absDelta.z;
}
}
}
}
//Calculate the attractive forces
for (MSynapse e : synapses) {
MNeuron v = e.getPreNeuron();
MNeuron u = e.getPostNeuron();
//Calculate delta, the difference in position between the two neurons
MVec3f delta = v.getCoords().subtract(u.getCoords());
MVec3f deltaPow = delta.pow(2);
MVec3f absDelta = delta.abs();
if (delta.x != 0) {
v.disp.x -= delta.x / absDelta.x * deltaPow.x / k;
}
if (delta.y != 0) {
v.disp.y -= delta.y / absDelta.y * deltaPow.y / k;
}
if (delta.z != 0) {
v.disp.z -= delta.z / absDelta.z * deltaPow.z / k;
}
if (delta.x != 0) {
u.disp.x += delta.x / absDelta.x * deltaPow.x / k;
}
if (delta.y != 0) {
u.disp.y += delta.y / absDelta.y * deltaPow.y / k;
}
if (delta.z != 0) {
u.disp.z += delta.z / absDelta.z * deltaPow.z / k;
}
}
//Limit maximum displacement by the temperature
//Also prevent the thing from being displaced outside the frame
for (MNeuron v : neurons) {
if (v.disp.x != 0) {
v.getCoords().x += v.disp.x / Math.abs(v.disp.x) * Math.min(Math.abs(v.disp.x), temp);
}
if (v.disp.y != 0) {
v.getCoords().y += v.disp.y / Math.abs(v.disp.y) * Math.min(Math.abs(v.disp.y), temp);
}
if (v.disp.z != 0) {
v.getCoords().z += v.disp.z / Math.abs(v.disp.z) * Math.min(Math.abs(v.disp.z), temp);
}
v.getCoords().x = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().x));
v.getCoords().y = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().y));
v.getCoords().z = Math.min(250 / 2, Math.max(-250 / 2, v.getCoords().z));
}
//Reduce temperature
temp = temp - 0.5;
if (temp == 0) {
temp = 1;
}
}
mnetwork.setNeurons(neurons);
}
private void addNode(int level, int max, MNeuron node) {
node.params.spatialCoords.x = level * 20;
node.params.spatialCoords.y = max;
node.params.spatialCoords.z = 0;
maxInLevel.put(level, max + 20);
placed.add(node);
}
private int maxValue(int level) {
int max = 0;
if (!maxInLevel.containsKey(level)) {
maxInLevel.put(level, 0);
maxLevel++;
} else {
max = maxInLevel.get(level);
}
maxHeight = Math.max(maxHeight, (max / 20));
return max;
}
public void updateCanSee(ArrayList<SightInformation> see) {
canSee = see;
}
public ArrayList<SightInformation> getCanSee() {
return canSee;
}
protected void thrust(double strength) {
double x = strength * Math.cos(viewHeading * Math.PI / 180) * 400;
double y = strength * Math.sin(viewHeading * Math.PI / 180) * 400;
float box2Dx = (float) (x/Simulation.meterToPixel);
float box2Dy = (float) (y/Simulation.meterToPixel);
if(body != null){
Vec2 force = new Vec2(box2Dx,box2Dy);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body.applyLinearImpulse(force, point);
}
}
protected void changeViewHeading(double h) {
viewHeading += h;
}
protected void updateHealth(double h) {
health += h;
health = Math.min(1, health);
}
protected void updateFitness(double value) {
fitness += value;
}
//returns the distance of the closest object in a specified segment, -1 if none found.
public double viewingObjectOfTypeInSegment(int segment, int type) {
ArrayList<SightInformation> filtered = new ArrayList<SightInformation>();
for (SightInformation si : canSee) { //filter out those objects of type that are in the specified segment
if (si.getType() == type && si.getDistanceFromLower() >= ((double) segment / configNumSegments) && si.getDistanceFromLower() < ((segment + 1.0) / configNumSegments)) {
filtered.add(si);
}
}
if (filtered.size() == 0) {
return -1;
}
double dist = Double.MAX_VALUE;
for (SightInformation si : filtered) {
dist = Math.min(dist, si.getDistance());
}
return dist / visionRange;
}
public void stop() {
speed.x = 0;
speed.y = 0;
}
public void setX(int x) {
coords.x = x;
}
public void setY(int y) {
coords.y = y;
}
public double getHealth() {
return health;
}
public double getViewHeading() {
return viewHeading;
}
public double getVisionRange() {
return visionRange;
}
public ArrayList<SightInformation> getAllViewingObjects() {
return canSee;
}
int getNumSegments() {
return configNumSegments;
}
public double getFOV() {
return fov;
}
public double getChangeX() {
return speed.x;
}
public double getChangeY() {
return speed.y;
}
public double getMovingAngle() {
double angle = 0;
if (getChangeX() == 0) {
if (getChangeY() < 0) {
angle = -90;
} else {
angle = 90;
}
} else {
angle = Math.atan((getChangeY()) / (getChangeX())) * 180.0 / Math.PI;
}
if (getChangeX() > 0) {
if (getChangeY() < 0) {
angle = 360 + angle;
}
} else {
if (getChangeY() >= 0) {
angle = 180 + angle;
} else {
angle += 180;
}
}
return angle;
}
public double getMovingSpeed() {
return Math.sqrt(Math.pow((float) (getChangeX()), 2) + Math.pow((float) (getChangeY()), 2));
}
public MNetwork getNetwork() {
return mnetwork;
}
NInterface getInterface() {
return ninterface;
}
public int getSpeciesId() {
return genome.getSpeciesId();
}
public int getAge() {
return this.age;
}
public int getType(){
return Collision.TYPE_AGENT;
}
}
|
Removed debug print statement
|
src/main/java/group7/anemone/Agent.java
|
Removed debug print statement
|
|
Java
|
apache-2.0
|
31d01562571b7d009d34cd568cf3505c56617984
| 0
|
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.maddyhome.idea.copyright.pattern;
import com.intellij.openapi.fileTypes.FileTypeExtension;
public class CopyrightVariablesProviders extends FileTypeExtension<CopyrightVariablesProvider> {
public final static CopyrightVariablesProviders INSTANCE = new CopyrightVariablesProviders();
private CopyrightVariablesProviders() {
super("com.intellij.copyright.variablesProvider");
}
}
|
plugins/copyright/src/com/maddyhome/idea/copyright/pattern/CopyrightVariablesProviders.java
|
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.maddyhome.idea.copyright.pattern;
import com.intellij.openapi.fileTypes.FileTypeExtension;
public class CopyrightVariablesProviders extends FileTypeExtension<CopyrightVariablesProvider> {
public static CopyrightVariablesProviders INSTANCE = new CopyrightVariablesProviders();
private CopyrightVariablesProviders() {
super("com.intellij.copyright.variablesProvider");
}
}
|
cleanup: make field final
GitOrigin-RevId: c394f002c56642d8e8aeaf80d0feed4a24531311
|
plugins/copyright/src/com/maddyhome/idea/copyright/pattern/CopyrightVariablesProviders.java
|
cleanup: make field final
|
|
Java
|
apache-2.0
|
e0806d62248e7c55a18d60af68d748819bb6eca7
| 0
|
pyamsoft/pydroid
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.model;
import android.content.Context;
import android.support.annotation.CheckResult;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
public final class AsyncDrawable {
@NonNull private final Context context;
@DrawableRes private final int icon;
public AsyncDrawable(@NonNull Context context, @DrawableRes int icon) {
this.context = context.getApplicationContext();
this.icon = icon;
}
@NonNull @CheckResult public final Context context() {
return context;
}
@CheckResult public final int icon() {
return icon;
}
}
|
src/main/java/com/pyamsoft/pydroid/model/AsyncDrawable.java
|
/*
* Copyright 2016 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.model;
import android.content.Context;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
public final class AsyncDrawable {
@NonNull private final Context context;
private final int icon;
public AsyncDrawable(@NonNull Context context, int icon) {
this.context = context.getApplicationContext();
this.icon = icon;
}
@NonNull @CheckResult public final Context context() {
return context;
}
@CheckResult public final int icon() {
return icon;
}
}
|
Annotate drawable
|
src/main/java/com/pyamsoft/pydroid/model/AsyncDrawable.java
|
Annotate drawable
|
|
Java
|
apache-2.0
|
695666acdbef7b979d2cd64dd96d1808d7241fc0
| 0
|
YaroslavLitvinov/sqoop,pkit/sqoop,apache/sqoop,icoding/sqoop,YaroslavLitvinov/sqoop,dlanza1/sqoop,apache/sqoop,dlanza1/parquet-mr,bonnetb/sqoop,dlanza1/parquet-mr,dlanza1/sqoop,unicredit/sqoop,apache/sqoop,baifendian/sqoop,pkit/sqoop,baifendian/sqoop,unicredit/sqoop,icoding/sqoop,YaroslavLitvinov/sqoop,pkit/sqoop,unicredit/sqoop,bonnetb/sqoop,rekhajoshm/sqoopfork,baifendian/sqoop,dlanza1/sqoop,dlanza1/parquet-mr,bonnetb/sqoop,icoding/sqoop,rekhajoshm/sqoopfork,rekhajoshm/sqoopfork
|
/**
* 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 com.cloudera.sqoop.testutil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.cloudera.sqoop.SqoopOptions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.StringUtils;
import org.junit.Before;
import com.cloudera.sqoop.Sqoop;
import com.cloudera.sqoop.mapreduce.ExportOutputFormat;
import com.cloudera.sqoop.tool.ExportTool;
/**
* Class that implements common methods required for tests which export data
* from HDFS to databases, to verify correct export.
*/
public abstract class ExportJobTestCase extends BaseSqoopTestCase {
public static final Log LOG = LogFactory.getLog(
ExportJobTestCase.class.getName());
@Before
public void setUp() {
// start the server
super.setUp();
if (useHsqldbTestServer()) {
// throw away any existing data that might be in the database.
try {
this.getTestServer().dropExistingSchema();
} catch (SQLException sqlE) {
fail(sqlE.toString());
}
}
}
protected String getTablePrefix() {
return "EXPORT_TABLE_";
}
/**
* @return the maximum rows to fold into an INSERT statement.
* HSQLDB can only support the single-row INSERT syntax. Other databases
* can support greater numbers of rows per statement.
*/
protected int getMaxRowsPerStatement() {
return 1;
}
/**
* Create the argv to pass to Sqoop.
* @param includeHadoopFlags if true, then include -D various.settings=values
* @param rowsPerStmt number of rows to export in a single INSERT statement.
* @param statementsPerTx ## of statements to use in a transaction.
* @return the argv as an array of strings.
*/
protected String [] getArgv(boolean includeHadoopFlags,
int rowsPerStmt, int statementsPerTx, String... additionalArgv) {
ArrayList<String> args = new ArrayList<String>();
if (includeHadoopFlags) {
CommonArgs.addHadoopFlags(args);
args.add("-D");
int realRowsPerStmt = Math.min(rowsPerStmt, getMaxRowsPerStatement());
if (realRowsPerStmt != rowsPerStmt) {
LOG.warn("Rows per statement set to " + realRowsPerStmt
+ " by getMaxRowsPerStatement() limit.");
}
args.add(ExportOutputFormat.RECORDS_PER_STATEMENT_KEY + "="
+ realRowsPerStmt);
args.add("-D");
args.add(ExportOutputFormat.STATEMENTS_PER_TRANSACTION_KEY + "="
+ statementsPerTx);
}
// Any additional Hadoop flags (-D foo=bar) are prepended.
if (null != additionalArgv) {
boolean prevIsFlag = false;
for (String arg : additionalArgv) {
if (arg.equals("-D")) {
args.add(arg);
prevIsFlag = true;
} else if (prevIsFlag) {
args.add(arg);
prevIsFlag = false;
}
}
}
// The sqoop-specific additional args are then added.
if (null != additionalArgv) {
boolean prevIsFlag = false;
for (String arg : additionalArgv) {
if (arg.equals("-D")) {
prevIsFlag = true;
continue;
} else if (prevIsFlag) {
prevIsFlag = false;
continue;
} else {
// normal argument.
args.add(arg);
}
}
}
args.add("--table");
args.add(getTableName());
args.add("--export-dir");
args.add(getTablePath().toString());
args.add("--connect");
args.add(getConnectString());
args.add("--fields-terminated-by");
args.add("\\t");
args.add("--lines-terminated-by");
args.add("\\n");
args.add("-m");
args.add("1");
LOG.debug("args:");
for (String a : args) {
LOG.debug(" " + a);
}
return args.toArray(new String[0]);
}
/** When exporting text columns, what should the text contain? */
protected String getMsgPrefix() {
return "textfield";
}
/** @return the minimum 'id' value in the table */
protected int getMinRowId(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement(
"SELECT MIN(id) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int minVal = 0;
try {
ResultSet rs = statement.executeQuery();
try {
rs.next();
minVal = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
return minVal;
}
/** @return the maximum 'id' value in the table */
protected int getMaxRowId(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement(
"SELECT MAX(id) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int maxVal = 0;
try {
ResultSet rs = statement.executeQuery();
try {
rs.next();
maxVal = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
return maxVal;
}
/**
* Check that we got back the expected row set.
* @param expectedNumRecords The number of records we expected to load
* into the database.
*/
protected void verifyExport(int expectedNumRecords)
throws IOException, SQLException {
Connection conn = getConnection();
verifyExport(expectedNumRecords, conn);
}
/**
* Check that we got back the expected row set.
* @param expectedNumRecords The number of records we expected to load
* into the database.
* @param conn the db connection to use.
*/
protected void verifyExport(int expectedNumRecords, Connection conn)
throws IOException, SQLException {
LOG.info("Verifying export: " + getTableName());
// Check that we got back the correct number of records.
PreparedStatement statement = conn.prepareStatement(
"SELECT COUNT(*) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int actualNumRecords = 0;
ResultSet rs = null;
try {
rs = statement.executeQuery();
try {
rs.next();
actualNumRecords = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Got back unexpected row count", expectedNumRecords,
actualNumRecords);
if (expectedNumRecords == 0) {
return; // Nothing more to verify.
}
// Check that we start with row 0.
int minVal = getMinRowId(conn);
assertEquals("Minimum row was not zero", 0, minVal);
// Check that the last row we loaded is numRows - 1
int maxVal = getMaxRowId(conn);
assertEquals("Maximum row had invalid id", expectedNumRecords - 1, maxVal);
// Check that the string values associated with these points match up.
statement = conn.prepareStatement("SELECT msg FROM " + getTableName()
+ " WHERE id = " + minVal,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
String minMsg = "";
try {
rs = statement.executeQuery();
try {
rs.next();
minMsg = rs.getString(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Invalid msg field for min value", getMsgPrefix() + minVal,
minMsg);
statement = conn.prepareStatement("SELECT msg FROM " + getTableName()
+ " WHERE id = " + maxVal,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
String maxMsg = "";
try {
rs = statement.executeQuery();
try {
rs.next();
maxMsg = rs.getString(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Invalid msg field for min value", getMsgPrefix() + maxVal,
maxMsg);
}
/**
* Run a MapReduce-based export (using the argv provided to control
* execution).
* @return the generated jar filename
*/
protected List<String> runExport(String [] argv) throws IOException {
// run the tool through the normal entry-point.
int ret;
List<String> generatedJars = null;
try {
ExportTool exporter = new ExportTool();
Configuration conf = getConf();
SqoopOptions opts = getSqoopOptions(conf);
Sqoop sqoop = new Sqoop(exporter, conf, opts);
ret = Sqoop.runSqoop(sqoop, argv);
generatedJars = exporter.getGeneratedJarFiles();
} catch (Exception e) {
LOG.error("Got exception running Sqoop: "
+ StringUtils.stringifyException(e));
ret = 1;
}
// expect a successful return.
if (0 != ret) {
throw new IOException("Failure during job; return status " + ret);
}
return generatedJars;
}
}
|
src/test/com/cloudera/sqoop/testutil/ExportJobTestCase.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.sqoop.testutil;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.util.StringUtils;
import org.junit.Before;
import com.cloudera.sqoop.Sqoop;
import com.cloudera.sqoop.mapreduce.ExportOutputFormat;
import com.cloudera.sqoop.tool.ExportTool;
/**
* Class that implements common methods required for tests which export data
* from HDFS to databases, to verify correct export.
*/
public abstract class ExportJobTestCase extends BaseSqoopTestCase {
public static final Log LOG = LogFactory.getLog(
ExportJobTestCase.class.getName());
@Before
public void setUp() {
// start the server
super.setUp();
if (useHsqldbTestServer()) {
// throw away any existing data that might be in the database.
try {
this.getTestServer().dropExistingSchema();
} catch (SQLException sqlE) {
fail(sqlE.toString());
}
}
}
protected String getTablePrefix() {
return "EXPORT_TABLE_";
}
/**
* @return the maximum rows to fold into an INSERT statement.
* HSQLDB can only support the single-row INSERT syntax. Other databases
* can support greater numbers of rows per statement.
*/
protected int getMaxRowsPerStatement() {
return 1;
}
/**
* Create the argv to pass to Sqoop.
* @param includeHadoopFlags if true, then include -D various.settings=values
* @param rowsPerStmt number of rows to export in a single INSERT statement.
* @param statementsPerTx ## of statements to use in a transaction.
* @return the argv as an array of strings.
*/
protected String [] getArgv(boolean includeHadoopFlags,
int rowsPerStmt, int statementsPerTx, String... additionalArgv) {
ArrayList<String> args = new ArrayList<String>();
if (includeHadoopFlags) {
CommonArgs.addHadoopFlags(args);
args.add("-D");
int realRowsPerStmt = Math.min(rowsPerStmt, getMaxRowsPerStatement());
if (realRowsPerStmt != rowsPerStmt) {
LOG.warn("Rows per statement set to " + realRowsPerStmt
+ " by getMaxRowsPerStatement() limit.");
}
args.add(ExportOutputFormat.RECORDS_PER_STATEMENT_KEY + "="
+ realRowsPerStmt);
args.add("-D");
args.add(ExportOutputFormat.STATEMENTS_PER_TRANSACTION_KEY + "="
+ statementsPerTx);
}
// Any additional Hadoop flags (-D foo=bar) are prepended.
if (null != additionalArgv) {
boolean prevIsFlag = false;
for (String arg : additionalArgv) {
if (arg.equals("-D")) {
args.add(arg);
prevIsFlag = true;
} else if (prevIsFlag) {
args.add(arg);
prevIsFlag = false;
}
}
}
// The sqoop-specific additional args are then added.
if (null != additionalArgv) {
boolean prevIsFlag = false;
for (String arg : additionalArgv) {
if (arg.equals("-D")) {
prevIsFlag = true;
continue;
} else if (prevIsFlag) {
prevIsFlag = false;
continue;
} else {
// normal argument.
args.add(arg);
}
}
}
args.add("--table");
args.add(getTableName());
args.add("--export-dir");
args.add(getTablePath().toString());
args.add("--connect");
args.add(getConnectString());
args.add("--fields-terminated-by");
args.add("\\t");
args.add("--lines-terminated-by");
args.add("\\n");
args.add("-m");
args.add("1");
LOG.debug("args:");
for (String a : args) {
LOG.debug(" " + a);
}
return args.toArray(new String[0]);
}
/** When exporting text columns, what should the text contain? */
protected String getMsgPrefix() {
return "textfield";
}
/** @return the minimum 'id' value in the table */
protected int getMinRowId(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement(
"SELECT MIN(id) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int minVal = 0;
try {
ResultSet rs = statement.executeQuery();
try {
rs.next();
minVal = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
return minVal;
}
/** @return the maximum 'id' value in the table */
protected int getMaxRowId(Connection conn) throws SQLException {
PreparedStatement statement = conn.prepareStatement(
"SELECT MAX(id) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int maxVal = 0;
try {
ResultSet rs = statement.executeQuery();
try {
rs.next();
maxVal = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
return maxVal;
}
/**
* Check that we got back the expected row set.
* @param expectedNumRecords The number of records we expected to load
* into the database.
*/
protected void verifyExport(int expectedNumRecords)
throws IOException, SQLException {
Connection conn = getConnection();
verifyExport(expectedNumRecords, conn);
}
/**
* Check that we got back the expected row set.
* @param expectedNumRecords The number of records we expected to load
* into the database.
* @param conn the db connection to use.
*/
protected void verifyExport(int expectedNumRecords, Connection conn)
throws IOException, SQLException {
LOG.info("Verifying export: " + getTableName());
// Check that we got back the correct number of records.
PreparedStatement statement = conn.prepareStatement(
"SELECT COUNT(*) FROM " + getTableName(),
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
int actualNumRecords = 0;
ResultSet rs = null;
try {
rs = statement.executeQuery();
try {
rs.next();
actualNumRecords = rs.getInt(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Got back unexpected row count", expectedNumRecords,
actualNumRecords);
if (expectedNumRecords == 0) {
return; // Nothing more to verify.
}
// Check that we start with row 0.
int minVal = getMinRowId(conn);
assertEquals("Minimum row was not zero", 0, minVal);
// Check that the last row we loaded is numRows - 1
int maxVal = getMaxRowId(conn);
assertEquals("Maximum row had invalid id", expectedNumRecords - 1, maxVal);
// Check that the string values associated with these points match up.
statement = conn.prepareStatement("SELECT msg FROM " + getTableName()
+ " WHERE id = " + minVal,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
String minMsg = "";
try {
rs = statement.executeQuery();
try {
rs.next();
minMsg = rs.getString(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Invalid msg field for min value", getMsgPrefix() + minVal,
minMsg);
statement = conn.prepareStatement("SELECT msg FROM " + getTableName()
+ " WHERE id = " + maxVal,
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
String maxMsg = "";
try {
rs = statement.executeQuery();
try {
rs.next();
maxMsg = rs.getString(1);
} finally {
rs.close();
}
} finally {
statement.close();
}
assertEquals("Invalid msg field for min value", getMsgPrefix() + maxVal,
maxMsg);
}
/**
* Run a MapReduce-based export (using the argv provided to control
* execution).
* @return the generated jar filename
*/
protected List<String> runExport(String [] argv) throws IOException {
// run the tool through the normal entry-point.
int ret;
List<String> generatedJars = null;
try {
ExportTool exporter = new ExportTool();
Sqoop sqoop = new Sqoop(exporter);
ret = Sqoop.runSqoop(sqoop, argv);
generatedJars = exporter.getGeneratedJarFiles();
} catch (Exception e) {
LOG.error("Got exception running Sqoop: "
+ StringUtils.stringifyException(e));
ret = 1;
}
// expect a successful return.
if (0 != ret) {
throw new IOException("Failure during job; return status " + ret);
}
return generatedJars;
}
}
|
SQOOP-636: ExportJobTestCase.runExport method does not reuse the existing Configuration and SqoopOptions
(Venkatesh Seetharam via Jarek Jarcec Cecho)
|
src/test/com/cloudera/sqoop/testutil/ExportJobTestCase.java
|
SQOOP-636: ExportJobTestCase.runExport method does not reuse the existing Configuration and SqoopOptions
|
|
Java
|
apache-2.0
|
4ad2482a908f5be28ba659511247483617419127
| 0
|
OpenWinCon/OpenWinNet,OpenWinCon/OpenWinNet,OpenWinCon/OpenWinNet,OpenWinCon/OpenWinNet,OpenWinCon/OpenWinNet,OpenWinCon/OpenWinNet
|
/*
* Copyright 2016 Open Networking Laboratory
*
* 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 mclab;
import java.net.*;
import java.sql.*;
import java.io.*;
import java.util.concurrent.*;
import mclab.*;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Skeletal ONOS application component.
*/
@Component(immediate = true)
public class AppComponent {
private final Logger log = LoggerFactory.getLogger(getClass());
protected final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
protected final String MYSQL_URL = "jdbc:mysql://localhost:3306/AP_Information?" +
"user=root&password=mclab1";
protected final String MYSQL_USER = "root";
protected final String MYSQL_PASSWORD = "mclab1";
protected MySQLdb db = null;
protected HeartbeatThread ht = null;
protected ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
protected ThreadPoolExecutor conExecutor;
protected ServerSocket ls;
@Activate
protected void activate() {
try {
db = new MySQLdb(MYSQL_DRIVER,MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);
System.out.println("makedb");
//ls = new ServerSocket(12015);
//print("serverSocket");
ht = new HeartbeatThread(db);
executor.scheduleAtFixedRate(ht, 1, 5, TimeUnit.SECONDS);
conExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool();
conExecutor.execute(new DBThread(db, conExecutor, ls));
//print("ddd");
/*****************************
* TODO:
* 1. make db thread - done
* 2. make db command - done
* 3. make heartbeat - done
* 4. make show command
* ***************************/
log.info("Started");
}
catch(Exception e)
{e.printStackTrace();}
}
@Deactivate
protected void deactivate() {
try {
log.info("Stopped");
ls.close();
executor.shutdown();
conExecutor.shutdown();
}catch(Exception e) {
e.printStackTrace();
}
}
}
|
agent/onosAPcontroller/src/main/java/mclab/AppComponent.java
|
/*
* Copyright 2016 Open Networking Laboratory
*
* 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 mclab;
import java.net.*;
import java.sql.*;
import java.io.*;
import java.util.concurrent.*;
import mclab.*;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Skeletal ONOS application component.
*/
@Component(immediate = true)
public class AppComponent {
private final Logger log = LoggerFactory.getLogger(getClass());
protected final String MYSQL_DRIVER = "com.mysql.jdbc.Driver";
protected final String MYSQL_URL = "jdbc:mysql://localhost:3306/AP_Information?" +
"user=root&password=mclab1";
protected final String MYSQL_USER = "root";
protected final String MYSQL_PASSWORD = "mclab1";
protected MySQLdb db = null;
protected ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
protected ThreadPoolExecutor conExecutor;
protected ServerSocket ls;
protected void heartbeatThread() {
db.heartbeat();
//onos.print("heartbeat");
}
@Activate
protected void activate() {
try {
db = new MySQLdb(MYSQL_DRIVER,MYSQL_URL, MYSQL_USER, MYSQL_PASSWORD);
System.out.println("makedb");
//ls = new ServerSocket(12015);
//print("serverSocket");
executor.scheduleAtFixedRate(this::heartbeatThread, 1, 5, TimeUnit.SECONDS);
conExecutor = (ThreadPoolExecutor)Executors.newCachedThreadPool();
conExecutor.execute(new DBThread(db, conExecutor, ls));
//print("ddd");
/*****************************
* TODO:
* 1. make db thread
* 2. make db command
* 3. make heartbeat
* 4. make show command
* ***************************/
log.info("Started");
}
catch(Exception e)
{e.printStackTrace();}
}
@Deactivate
protected void deactivate() {
try {
log.info("Stopped");
ls.close();
executor.shutdown();
conExecutor.shutdown();
}catch(Exception e) {
e.printStackTrace();
}
}
}
|
add heatbeatthread
|
agent/onosAPcontroller/src/main/java/mclab/AppComponent.java
|
add heatbeatthread
|
|
Java
|
apache-2.0
|
fee0d4c27cdc159a1b4a0fa5883ddf562a696d00
| 0
|
openhab/jmdns,jmdns/jmdns,jmdns/jmdns,openhab/jmdns
|
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceInfo.Fields;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
import javax.jmdns.impl.ListenerStatus.ServiceListenerStatus;
import javax.jmdns.impl.ListenerStatus.ServiceTypeListenerStatus;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
import javax.jmdns.impl.constants.DNSState;
import javax.jmdns.impl.tasks.DNSTask;
import javax.jmdns.impl.tasks.RecordReaper;
import javax.jmdns.impl.util.NamedThreadFactory;
// REMIND: multiple IP addresses
/**
* mDNS implementation in Java.
*
* @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis, Kai Kreuzer, Victor Toni
*/
public class JmDNSImpl extends JmDNS implements DNSStatefulObject, DNSTaskStarter {
private static Logger logger = LoggerFactory.getLogger(JmDNSImpl.class.getName());
public enum Operation {
Remove, Update, Add, RegisterServiceType, Noop
}
/**
* This is the multicast group, we are listening to for multicast DNS messages.
*/
private volatile InetAddress _group;
/**
* This is our multicast socket.
*/
private volatile MulticastSocket _socket;
/**
* Holds instances of JmDNS.DNSListener. Must by a synchronized collection, because it is updated from concurrent threads.
*/
private final List<DNSListener> _listeners;
/**
* Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's.
*/
/* default */ final ConcurrentMap<String, List<ServiceListenerStatus>> _serviceListeners;
/**
* Holds instances of ServiceTypeListener's.
*/
private final Set<ServiceTypeListenerStatus> _typeListeners;
/**
* Cache for DNSEntry's.
*/
private final DNSCache _cache;
/**
* This hashtable holds the services that have been registered. Keys are instances of String which hold an all lower-case version of the fully qualified service name. Values are instances of ServiceInfo.
*/
private final ConcurrentMap<String, ServiceInfo> _services;
/**
* This hashtable holds the service types that have been registered or that have been received in an incoming datagram.<br/>
* Keys are instances of String which hold an all lower-case version of the fully qualified service type.<br/>
* Values hold the fully qualified service type.
*/
private final ConcurrentMap<String, ServiceTypeEntry> _serviceTypes;
private volatile Delegate _delegate;
/**
* This is used to store type entries. The type is stored as a call variable and the map support the subtypes.
* <p>
* The key is the lowercase version as the value is the case preserved version.
* </p>
*/
public static class ServiceTypeEntry extends AbstractMap<String, String>implements Cloneable {
private final Set<Map.Entry<String, String>> _entrySet;
private final String _type;
private static class SubTypeEntry implements Entry<String, String>, java.io.Serializable, Cloneable {
private static final long serialVersionUID = 9188503522395855322L;
private final String _key;
private final String _value;
public SubTypeEntry(String subtype) {
super();
_value = (subtype != null ? subtype : "");
_key = _value.toLowerCase();
}
/**
* {@inheritDoc}
*/
@Override
public String getKey() {
return _key;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
return _value;
}
/**
* Replaces the value corresponding to this entry with the specified value (optional operation). This implementation simply throws <tt>UnsupportedOperationException</tt>, as this class implements an <i>immutable</i> map entry.
*
* @param value
* new value to be stored in this entry
* @return (Does not return)
* @exception UnsupportedOperationException
* always
*/
@Override
public String setValue(String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object entry) {
if (!(entry instanceof Map.Entry)) {
return false;
}
return this.getKey().equals(((Map.Entry<?, ?>) entry).getKey()) && this.getValue().equals(((Map.Entry<?, ?>) entry).getValue());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return (_key == null ? 0 : _key.hashCode()) ^ (_value == null ? 0 : _value.hashCode());
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public SubTypeEntry clone() {
// Immutable object
return this;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return _key + "=" + _value;
}
}
public ServiceTypeEntry(String type) {
super();
this._type = type;
this._entrySet = new HashSet<Map.Entry<String, String>>();
}
/**
* The type associated with this entry.
*
* @return the type
*/
public String getType() {
return _type;
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#entrySet()
*/
@Override
public Set<Map.Entry<String, String>> entrySet() {
return _entrySet;
}
/**
* Returns <code>true</code> if this set contains the specified element. More formally, returns <code>true</code> if and only if this set contains an element <code>e</code> such that
* <code>(o==null ? e==null : o.equals(e))</code>.
*
* @param subtype
* element whose presence in this set is to be tested
* @return <code>true</code> if this set contains the specified element
*/
public boolean contains(String subtype) {
return subtype != null && this.containsKey(subtype.toLowerCase());
}
/**
* Adds the specified element to this set if it is not already present. More formally, adds the specified element <code>e</code> to this set if this set contains no element <code>e2</code> such that
* <code>(e==null ? e2==null : e.equals(e2))</code>. If this set already contains the element, the call leaves the set unchanged and returns <code>false</code>.
*
* @param subtype
* element to be added to this set
* @return <code>true</code> if this set did not already contain the specified element
*/
public boolean add(String subtype) {
if (subtype == null || this.contains(subtype)) {
return false;
}
_entrySet.add(new SubTypeEntry(subtype));
return true;
}
/**
* Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
*
* @return an iterator over the elements in this set
*/
public Iterator<String> iterator() {
return this.keySet().iterator();
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#clone()
*/
@Override
public ServiceTypeEntry clone() {
ServiceTypeEntry entry = new ServiceTypeEntry(this.getType());
for (Map.Entry<String, String> subTypeEntry : this.entrySet()) {
entry.add(subTypeEntry.getValue());
}
return entry;
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#toString()
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(200);
if (this.isEmpty()) {
sb.append("empty");
} else {
for (String value : this.values()) {
sb.append(value);
sb.append(", ");
}
sb.setLength(sb.length() - 2);
}
return sb.toString();
}
}
/**
* This is the shutdown hook, we registered with the java runtime.
*/
protected Thread _shutdown;
/**
* Handle on the local host
*/
private HostInfo _localHost;
private Thread _incomingListener;
/**
* Throttle count. This is used to count the overall number of probes sent by JmDNS. When the last throttle increment happened .
*/
private int _throttle;
/**
* Last throttle increment.
*/
private long _lastThrottleIncrement;
private final ExecutorService _executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmDNS"));
//
// 2009-09-16 ldeck: adding docbug patch with slight ammendments
// 'Fixes two deadlock conditions involving JmDNS.close() - ID: 1473279'
//
// ---------------------------------------------------
/**
* The timer that triggers our announcements. We can't use the main timer object, because that could cause a deadlock where Prober waits on JmDNS.this lock held by close(), close() waits for us to finish, and we wait for Prober to give us back
* the timer thread so we can announce. (Patch from docbug in 2006-04-19 still wasn't patched .. so I'm doing it!)
*/
// private final Timer _cancelerTimer;
// ---------------------------------------------------
/**
* The source for random values. This is used to introduce random delays in responses. This reduces the potential for collisions on the network.
*/
private final static Random _random = new Random();
/**
* This lock is used to coordinate processing of incoming and outgoing messages. This is needed, because the Rendezvous Conformance Test does not forgive race conditions.
*/
private final ReentrantLock _ioLock = new ReentrantLock();
/**
* If an incoming package which needs an answer is truncated, we store it here. We add more incoming DNSRecords to it, until the JmDNS.Responder timer picks it up.<br/>
* FIXME [PJYF June 8 2010]: This does not work well with multiple planned answers for packages that came in from different clients.
*/
private DNSIncoming _plannedAnswer;
// State machine
/**
* This hashtable is used to maintain a list of service types being collected by this JmDNS instance. The key of the hashtable is a service type name, the value is an instance of JmDNS.ServiceCollector.
*
* @see #list
*/
private final ConcurrentMap<String, ServiceCollector> _serviceCollectors;
private final String _name;
/**
* Main method to display API information if run from java -jar
*
* @param argv
* the command line arguments
*/
public static void main(String[] argv) {
String version = null;
try {
final Properties pomProperties = new Properties();
pomProperties.load(JmDNSImpl.class.getResourceAsStream("/META-INF/maven/javax.jmdns/jmdns/pom.properties"));
version = pomProperties.getProperty("version");
} catch (Exception e) {
version = "RUNNING.IN.IDE.FULL";
}
System.out.println("JmDNS version \"" + version + "\"");
System.out.println(" ");
System.out.println("Running on java version \"" + System.getProperty("java.version") + "\"" + " (build " + System.getProperty("java.runtime.version") + ")" + " from " + System.getProperty("java.vendor"));
System.out.println("Operating environment \"" + System.getProperty("os.name") + "\"" + " version " + System.getProperty("os.version") + " on " + System.getProperty("os.arch"));
System.out.println("For more information on JmDNS please visit http://jmdns.org");
}
/**
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
*
* @param address
* IP address to bind to.
* @param name
* name of the newly created JmDNS
* @exception IOException
*/
public JmDNSImpl(InetAddress address, String name) throws IOException {
super();
logger.debug("JmDNS instance created");
_cache = new DNSCache(100);
_listeners = Collections.synchronizedList(new ArrayList<DNSListener>());
_serviceListeners = new ConcurrentHashMap<String, List<ServiceListenerStatus>>();
_typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListenerStatus>());
_serviceCollectors = new ConcurrentHashMap<String, ServiceCollector>();
_services = new ConcurrentHashMap<String, ServiceInfo>(20);
_serviceTypes = new ConcurrentHashMap<String, ServiceTypeEntry>(20);
_localHost = HostInfo.newHostInfo(address, this, name);
_name = (name != null ? name : _localHost.getName());
// _cancelerTimer = new Timer("JmDNS.cancelerTimer");
// (ldeck 2.1.1) preventing shutdown blocking thread
// -------------------------------------------------
// _shutdown = new Thread(new Shutdown(), "JmDNS.Shutdown");
// Runtime.getRuntime().addShutdownHook(_shutdown);
// -------------------------------------------------
// Bind to multicast socket
this.openMulticastSocket(this.getLocalHost());
this.start(this.getServices().values());
this.startReaper();
}
private void start(Collection<? extends ServiceInfo> serviceInfos) {
if (_incomingListener == null) {
_incomingListener = new SocketListener(this);
_incomingListener.start();
}
this.startProber();
for (ServiceInfo info : serviceInfos) {
try {
this.registerService(new ServiceInfoImpl(info));
} catch (final Exception exception) {
logger.warn("start() Registration exception ", exception);
}
}
}
private void openMulticastSocket(HostInfo hostInfo) throws IOException {
if (_group == null) {
if (hostInfo.getInetAddress() instanceof Inet6Address) {
_group = InetAddress.getByName(DNSConstants.MDNS_GROUP_IPV6);
} else {
_group = InetAddress.getByName(DNSConstants.MDNS_GROUP);
}
}
if (_socket != null) {
this.closeMulticastSocket();
}
// SocketAddress address = new InetSocketAddress((hostInfo != null ? hostInfo.getInetAddress() : null), DNSConstants.MDNS_PORT);
// System.out.println("Socket Address: " + address);
// try {
// _socket = new MulticastSocket(address);
// } catch (Exception exception) {
// logger.warn("openMulticastSocket() Open socket exception Address: " + address + ", ", exception);
// // The most likely cause is a duplicate address lets open without specifying the address
// _socket = new MulticastSocket(DNSConstants.MDNS_PORT);
// }
_socket = new MulticastSocket(DNSConstants.MDNS_PORT);
if ((hostInfo != null) && (hostInfo.getInterface() != null)) {
final SocketAddress multicastAddr = new InetSocketAddress(_group, DNSConstants.MDNS_PORT);
_socket.setNetworkInterface(hostInfo.getInterface());
logger.trace("Trying to joinGroup({}, {})", multicastAddr, hostInfo.getInterface());
// this joinGroup() might be less surprisingly so this is the default
_socket.joinGroup(multicastAddr, hostInfo.getInterface());
} else {
logger.trace("Trying to joinGroup({})", _group);
_socket.joinGroup(_group);
}
_socket.setTimeToLive(255);
}
private void closeMulticastSocket() {
// jP: 20010-01-18. See below. We'll need this monitor...
// assert (Thread.holdsLock(this));
logger.debug("closeMulticastSocket()");
if (_socket != null) {
// close socket
try {
try {
_socket.leaveGroup(_group);
} catch (SocketException exception) {
//
}
_socket.close();
// jP: 20010-01-18. It isn't safe to join() on the listener
// thread - it attempts to lock the IoLock object, and deadlock
// ensues. Per issue #2933183, changed this to wait on the JmDNS
// monitor, checking on each notify (or timeout) that the
// listener thread has stopped.
//
while (_incomingListener != null && _incomingListener.isAlive()) {
synchronized (this) {
try {
if (_incomingListener != null && _incomingListener.isAlive()) {
// wait time is arbitrary, we're really expecting notification.
logger.debug("closeMulticastSocket(): waiting for jmDNS monitor");
this.wait(1000);
}
} catch (InterruptedException ignored) {
// Ignored
}
}
}
_incomingListener = null;
} catch (final Exception exception) {
logger.warn("closeMulticastSocket() Close socket exception ", exception);
}
_socket = null;
}
}
// State machine
/**
* {@inheritDoc}
*/
@Override
public boolean advanceState(DNSTask task) {
return this._localHost.advanceState(task);
}
/**
* {@inheritDoc}
*/
@Override
public boolean revertState() {
return this._localHost.revertState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancelState() {
return this._localHost.cancelState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean closeState() {
return this._localHost.closeState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean recoverState() {
return this._localHost.recoverState();
}
/**
* {@inheritDoc}
*/
@Override
public JmDNSImpl getDns() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void associateWithTask(DNSTask task, DNSState state) {
this._localHost.associateWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public void removeAssociationWithTask(DNSTask task) {
this._localHost.removeAssociationWithTask(task);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
return this._localHost.isAssociatedWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isProbing() {
return this._localHost.isProbing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnouncing() {
return this._localHost.isAnnouncing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnounced() {
return this._localHost.isAnnounced();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceling() {
return this._localHost.isCanceling();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceled() {
return this._localHost.isCanceled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosing() {
return this._localHost.isClosing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return this._localHost.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForAnnounced(long timeout) {
return this._localHost.waitForAnnounced(timeout);
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForCanceled(long timeout) {
return this._localHost.waitForCanceled(timeout);
}
/**
* Return the DNSCache associated with the cache variable
*
* @return DNS cache
*/
public DNSCache getCache() {
return _cache;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return _name;
}
/**
* {@inheritDoc}
*/
@Override
public String getHostName() {
return _localHost.getName();
}
/**
* Returns the local host info
*
* @return local host info
*/
public HostInfo getLocalHost() {
return _localHost;
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getInetAddress() throws IOException {
return _localHost.getInetAddress();
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public InetAddress getInterface() throws IOException {
return _socket.getInterface();
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name) {
return this.getServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, long timeout) {
return this.getServiceInfo(type, name, false, timeout);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, boolean persistent) {
return this.getServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, boolean persistent, long timeout) {
final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent);
this.waitForInfoData(info, timeout);
return (info.hasData() ? info : null);
}
ServiceInfoImpl resolveServiceInfo(String type, String name, String subtype, boolean persistent) {
this.cleanCache();
String loType = type.toLowerCase();
this.registerServiceType(type);
if (_serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null) {
this.addServiceListener(loType, _serviceCollectors.get(loType), ListenerStatus.SYNCHRONOUS);
}
// Check if the answer is in the cache.
final ServiceInfoImpl info = this.getServiceInfoFromCache(type, name, subtype, persistent);
// We still run the resolver to do the dispatch but if the info is already there it will quit immediately
this.startServiceInfoResolver(info);
return info;
}
ServiceInfoImpl getServiceInfoFromCache(String type, String name, String subtype, boolean persistent) {
// Check if the answer is in the cache.
ServiceInfoImpl info = new ServiceInfoImpl(type, name, subtype, 0, 0, 0, persistent, (byte[]) null);
DNSEntry pointerEntry = this.getCache().getDNSEntry(new DNSRecord.Pointer(type, DNSRecordClass.CLASS_ANY, false, 0, info.getQualifiedName()));
if (pointerEntry instanceof DNSRecord) {
ServiceInfoImpl cachedInfo = (ServiceInfoImpl) ((DNSRecord) pointerEntry).getServiceInfo(persistent);
if (cachedInfo != null) {
// To get a complete info record we need to retrieve the service, address and the text bytes.
Map<Fields, String> map = cachedInfo.getQualifiedNameMap();
byte[] srvBytes = null;
String server = "";
DNSEntry serviceEntry = this.getCache().getDNSEntry(info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_ANY);
if (serviceEntry instanceof DNSRecord) {
ServiceInfo cachedServiceEntryInfo = ((DNSRecord) serviceEntry).getServiceInfo(persistent);
if (cachedServiceEntryInfo != null) {
cachedInfo = new ServiceInfoImpl(map, cachedServiceEntryInfo.getPort(), cachedServiceEntryInfo.getWeight(), cachedServiceEntryInfo.getPriority(), persistent, (byte[]) null);
srvBytes = cachedServiceEntryInfo.getTextBytes();
server = cachedServiceEntryInfo.getServer();
}
}
for (DNSEntry addressEntry : this.getCache().getDNSEntryList(server, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_ANY)) {
if (addressEntry instanceof DNSRecord) {
ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent);
if (cachedAddressInfo != null) {
for (Inet4Address address : cachedAddressInfo.getInet4Addresses()) {
cachedInfo.addAddress(address);
}
cachedInfo._setText(cachedAddressInfo.getTextBytes());
}
}
}
for (DNSEntry addressEntry : this.getCache().getDNSEntryList(server, DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_ANY)) {
if (addressEntry instanceof DNSRecord) {
ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent);
if (cachedAddressInfo != null) {
for (Inet6Address address : cachedAddressInfo.getInet6Addresses()) {
cachedInfo.addAddress(address);
}
cachedInfo._setText(cachedAddressInfo.getTextBytes());
}
}
}
DNSEntry textEntry = this.getCache().getDNSEntry(cachedInfo.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_ANY);
if (textEntry instanceof DNSRecord) {
ServiceInfo cachedTextInfo = ((DNSRecord) textEntry).getServiceInfo(persistent);
if (cachedTextInfo != null) {
cachedInfo._setText(cachedTextInfo.getTextBytes());
}
}
if (cachedInfo.getTextBytes().length == 0) {
cachedInfo._setText(srvBytes);
}
if (cachedInfo.hasData()) {
info = cachedInfo;
}
}
}
return info;
}
private void waitForInfoData(ServiceInfo info, long timeout) {
synchronized (info) {
long loops = (timeout / 200L);
if (loops < 1) {
loops = 1;
}
for (int i = 0; i < loops; i++) {
if (info.hasData()) {
break;
}
try {
info.wait(200);
} catch (final InterruptedException e) {
/* Stub */
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name) {
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, boolean persistent) {
this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, long timeout) {
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, boolean persistent, long timeout) {
final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent);
this.waitForInfoData(info, timeout);
}
void handleServiceResolved(ServiceEvent event) {
List<ServiceListenerStatus> list = _serviceListeners.get(event.getType().toLowerCase());
final List<ServiceListenerStatus> listCopy;
if ((list != null) && (!list.isEmpty())) {
if ((event.getInfo() != null) && event.getInfo().hasData()) {
final ServiceEvent localEvent = event;
synchronized (list) {
listCopy = new ArrayList<ServiceListenerStatus>(list);
}
for (final ServiceListenerStatus listener : listCopy) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceResolved(localEvent);
}
});
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void addServiceTypeListener(ServiceTypeListener listener) throws IOException {
ServiceTypeListenerStatus status = new ServiceTypeListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
_typeListeners.add(status);
// report cached service types
for (String type : _serviceTypes.keySet()) {
status.serviceTypeAdded(new ServiceEventImpl(this, type, "", null));
}
this.startTypeResolver();
}
/**
* {@inheritDoc}
*/
@Override
public void removeServiceTypeListener(ServiceTypeListener listener) {
ServiceTypeListenerStatus status = new ServiceTypeListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
_typeListeners.remove(status);
}
/**
* {@inheritDoc}
*/
@Override
public void addServiceListener(String type, ServiceListener listener) {
this.addServiceListener(type, listener, ListenerStatus.ASYNCHRONOUS);
}
private void addServiceListener(String type, ServiceListener listener, boolean synch) {
ServiceListenerStatus status = new ServiceListenerStatus(listener, synch);
final String loType = type.toLowerCase();
List<ServiceListenerStatus> list = _serviceListeners.get(loType);
if (list == null) {
if (_serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListenerStatus>()) == null) {
if (_serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null) {
// We have a problem here. The service collectors must be called synchronously so that their cache get cleaned up immediately or we will report .
this.addServiceListener(loType, _serviceCollectors.get(loType), ListenerStatus.SYNCHRONOUS);
}
}
list = _serviceListeners.get(loType);
}
if (list != null) {
synchronized (list) {
if (!list.contains(status)) {
list.add(status);
}
}
}
// report cached service types
final List<ServiceEvent> serviceEvents = new ArrayList<ServiceEvent>();
Collection<DNSEntry> dnsEntryLits = this.getCache().allValues();
for (DNSEntry entry : dnsEntryLits) {
final DNSRecord record = (DNSRecord) entry;
if (record.getRecordType() == DNSRecordType.TYPE_SRV) {
if (record.getKey().endsWith(loType)) {
// Do not used the record embedded method for generating event this will not work.
// serviceEvents.add(record.getServiceEvent(this));
serviceEvents.add(new ServiceEventImpl(this, record.getType(), toUnqualifiedName(record.getType(), record.getName()), record.getServiceInfo()));
}
}
}
// Actually call listener with all service events added above
for (ServiceEvent serviceEvent : serviceEvents) {
status.serviceAdded(serviceEvent);
}
// Create/start ServiceResolver
this.startServiceResolver(type);
}
/**
* {@inheritDoc}
*/
@Override
public void removeServiceListener(String type, ServiceListener listener) {
String loType = type.toLowerCase();
List<ServiceListenerStatus> list = _serviceListeners.get(loType);
if (list != null) {
synchronized (list) {
ServiceListenerStatus status = new ServiceListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
list.remove(status);
if (list.isEmpty()) {
_serviceListeners.remove(loType, list);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerService(ServiceInfo infoAbstract) throws IOException {
if (this.isClosing() || this.isClosed()) {
throw new IllegalStateException("This DNS is closed.");
}
final ServiceInfoImpl info = (ServiceInfoImpl) infoAbstract;
if (info.getDns() != null) {
if (info.getDns() != this) {
throw new IllegalStateException("A service information can only be registered with a single instamce of JmDNS.");
} else if (_services.get(info.getKey()) != null) {
throw new IllegalStateException("A service information can only be registered once.");
}
}
info.setDns(this);
this.registerServiceType(info.getTypeWithSubtype());
// bind the service to this address
info.recoverState();
info.setServer(_localHost.getName());
info.addAddress(_localHost.getInet4Address());
info.addAddress(_localHost.getInet6Address());
this.makeServiceNameUnique(info);
while (_services.putIfAbsent(info.getKey(), info) != null) {
this.makeServiceNameUnique(info);
}
this.startProber();
logger.debug("registerService() JmDNS registered service as {}", info);
}
/**
* {@inheritDoc}
*/
@Override
public void unregisterService(ServiceInfo infoAbstract) {
final ServiceInfoImpl info = (ServiceInfoImpl) _services.get(infoAbstract.getKey());
if (info != null) {
info.cancelState();
this.startCanceler();
info.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
_services.remove(info.getKey(), info);
logger.debug("unregisterService() JmDNS {} unregistered service as {}", this.getName(), info);
} else {
logger.warn("{} removing unregistered service info: {}", this.getName(), infoAbstract.getKey());
}
}
/**
* {@inheritDoc}
*/
@Override
public void unregisterAllServices() {
logger.debug("unregisterAllServices()");
for (final ServiceInfo info : _services.values()) {
if (info != null) {
final ServiceInfoImpl infoImpl = (ServiceInfoImpl) info;
logger.debug("Cancelling service info: {}", info);
infoImpl.cancelState();
}
}
this.startCanceler();
for (final Map.Entry<String, ServiceInfo> entry : _services.entrySet()) {
final ServiceInfo info = entry.getValue();
if (info != null) {
final ServiceInfoImpl infoImpl = (ServiceInfoImpl) info;
final String name = entry.getKey();
logger.debug("Wait for service info cancel: {}", info);
infoImpl.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
_services.remove(name, info);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean registerServiceType(String type) {
boolean typeAdded = false;
Map<Fields, String> map = ServiceInfoImpl.decodeQualifiedNameMapForType(type);
String domain = map.get(Fields.Domain);
String protocol = map.get(Fields.Protocol);
String application = map.get(Fields.Application);
String subtype = map.get(Fields.Subtype);
final String name = (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + ".";
final String loname = name.toLowerCase();
logger.debug("{} registering service type: {} as: {}{}{}",
this.getName(),
type,
name,
(subtype.length() > 0 ? " subtype: " : ""),
(subtype.length() > 0 ? subtype : "")
);
if (!_serviceTypes.containsKey(loname) && !application.toLowerCase().equals("dns-sd") && !domain.toLowerCase().endsWith("in-addr.arpa") && !domain.toLowerCase().endsWith("ip6.arpa")) {
typeAdded = _serviceTypes.putIfAbsent(loname, new ServiceTypeEntry(name)) == null;
if (typeAdded) {
final ServiceTypeListenerStatus[] list = _typeListeners.toArray(new ServiceTypeListenerStatus[_typeListeners.size()]);
final ServiceEvent event = new ServiceEventImpl(this, name, "", null);
for (final ServiceTypeListenerStatus status : list) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
status.serviceTypeAdded(event);
}
});
}
}
}
if (subtype.length() > 0) {
ServiceTypeEntry subtypes = _serviceTypes.get(loname);
if ((subtypes != null) && (!subtypes.contains(subtype))) {
synchronized (subtypes) {
if (!subtypes.contains(subtype)) {
typeAdded = true;
subtypes.add(subtype);
final ServiceTypeListenerStatus[] list = _typeListeners.toArray(new ServiceTypeListenerStatus[_typeListeners.size()]);
final ServiceEvent event = new ServiceEventImpl(this, "_" + subtype + "._sub." + name, "", null);
for (final ServiceTypeListenerStatus status : list) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
status.subTypeForServiceTypeAdded(event);
}
});
}
}
}
}
}
return typeAdded;
}
/**
* Generate a possibly unique name for a service using the information we have in the cache.
*
* @return returns true, if the name of the service info had to be changed.
*/
private boolean makeServiceNameUnique(ServiceInfoImpl info) {
final String originalQualifiedName = info.getKey();
final long now = System.currentTimeMillis();
boolean collision;
do {
collision = false;
// Check for collision in cache
for (DNSEntry dnsEntry : this.getCache().getDNSEntryList(info.getKey())) {
if (DNSRecordType.TYPE_SRV.equals(dnsEntry.getRecordType()) && !dnsEntry.isExpired(now)) {
final DNSRecord.Service s = (DNSRecord.Service) dnsEntry;
if (s.getPort() != info.getPort() || !s.getServer().equals(_localHost.getName())) {
logger.debug("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:{} s.server={} {} equals:{}",
dnsEntry,
s.getServer(),
_localHost.getName(),
s.getServer().equals(_localHost.getName())
);
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(), info.getName(), NameRegister.NameType.SERVICE));
collision = true;
break;
}
}
}
// Check for collision with other service infos published by JmDNS
final ServiceInfo selfService = _services.get(info.getKey());
if (selfService != null && selfService != info) {
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(), info.getName(), NameRegister.NameType.SERVICE));
collision = true;
}
}
while (collision);
return !(originalQualifiedName.equals(info.getKey()));
}
/**
* Add a listener for a question. The listener will receive updates of answers to the question as they arrive, or from the cache if they are already available.
*
* @param listener
* DSN listener
* @param question
* DNS query
*/
public void addListener(DNSListener listener, DNSQuestion question) {
final long now = System.currentTimeMillis();
// add the new listener
_listeners.add(listener);
// report existing matched records
if (question != null) {
for (DNSEntry dnsEntry : this.getCache().getDNSEntryList(question.getName().toLowerCase())) {
if (question.answeredBy(dnsEntry) && !dnsEntry.isExpired(now)) {
listener.updateRecord(this.getCache(), now, dnsEntry);
}
}
}
}
/**
* Remove a listener from all outstanding questions. The listener will no longer receive any updates.
*
* @param listener
* DSN listener
*/
public void removeListener(DNSListener listener) {
_listeners.remove(listener);
}
/**
* Renew a service when the record become stale. If there is no service collector for the type this method does nothing.
*
* @param type
* Service Type
*/
public void renewServiceCollector(String type) {
if (_serviceCollectors.containsKey(type.toLowerCase())) {
// Create/start ServiceResolver
this.startServiceResolver(type);
}
}
// Remind: Method updateRecord should receive a better name.
/**
* Notify all listeners that a record was updated.
*
* @param now
* update date
* @param rec
* DNS record
* @param operation
* DNS cache operation
*/
public void updateRecord(long now, DNSRecord rec, Operation operation) {
// We do not want to block the entire DNS while we are updating the record for each listener (service info)
{
List<DNSListener> listenerList = null;
synchronized (_listeners) {
listenerList = new ArrayList<DNSListener>(_listeners);
}
for (DNSListener listener : listenerList) {
listener.updateRecord(this.getCache(), now, rec);
}
}
/**
* This is the place where we actually add & remove services.
* - For adding we need a PTR record.
* - For removing we want also to consider expired SRV records because this means the service hasn't been updated
* and is probably not reachable anymore.
*
* For details see also RFC 6762 / Section 10.4:
* @see https://tools.ietf.org/html/rfc6762#section-10.4
*/
if (
DNSRecordType.TYPE_PTR.equals(rec.getRecordType())
|| ( DNSRecordType.TYPE_SRV.equals(rec.getRecordType()) && Operation.Remove.equals(operation))
)
{
ServiceEvent event = rec.getServiceEvent(this);
if ((event.getInfo() == null) || !event.getInfo().hasData()) {
// We do not care about the subtype because the info is only used if complete and the subtype will then be included.
ServiceInfo info = this.getServiceInfoFromCache(event.getType(), event.getName(), "", false);
if (info.hasData()) {
event = new ServiceEventImpl(this, event.getType(), event.getName(), info);
}
}
List<ServiceListenerStatus> list = _serviceListeners.get(event.getType().toLowerCase());
final List<ServiceListenerStatus> serviceListenerList;
if (list != null) {
synchronized (list) {
serviceListenerList = new ArrayList<ServiceListenerStatus>(list);
}
} else {
serviceListenerList = Collections.emptyList();
}
logger.trace("{}.updating record for event: {} list {} operation: {}",
this.getName(),
event,
serviceListenerList,
operation
);
if (!serviceListenerList.isEmpty()) {
final ServiceEvent localEvent = event;
switch (operation) {
case Add:
for (final ServiceListenerStatus listener : serviceListenerList) {
if (listener.isSynchronous()) {
listener.serviceAdded(localEvent);
} else {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceAdded(localEvent);
}
});
}
}
break;
case Remove:
for (final ServiceListenerStatus listener : serviceListenerList) {
if (listener.isSynchronous()) {
listener.serviceRemoved(localEvent);
} else {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceRemoved(localEvent);
}
});
}
}
break;
default:
break;
}
}
}
}
void handleRecord(DNSRecord record, long now) {
DNSRecord newRecord = record;
Operation cacheOperation = Operation.Noop;
final boolean expired = newRecord.isExpired(now);
logger.debug("{} handle response: {}", this.getName(), newRecord);
// update the cache
if (!newRecord.isServicesDiscoveryMetaQuery() && !newRecord.isDomainDiscoveryQuery()) {
final boolean unique = newRecord.isUnique();
final DNSRecord cachedRecord = (DNSRecord) this.getCache().getDNSEntry(newRecord);
logger.debug("{} handle response cached record: {}", this.getName(), cachedRecord);
// RFC 6762, section 10.2 Announcements to Flush Outdated Cache Entries
// https://tools.ietf.org/html/rfc6762#section-10.2
// if (cache-flush a.k.a unique), remove all existing records matching these criterias :--
// 1. same name
// 2. same record type
// 3. same record class
// 4. record is older than 1 second.
if (unique) {
for (DNSEntry entry : this.getCache().getDNSEntryList(newRecord.getKey())) {
if ( newRecord.getRecordType().equals(entry.getRecordType()) &&
newRecord.getRecordClass().equals(entry.getRecordClass()) &&
isOlderThanOneSecond( (DNSRecord)entry, now )
) {
logger.trace("setWillExpireSoon() on: {}", entry);
// this set ttl to 1 second,
((DNSRecord) entry).setWillExpireSoon(now);
}
}
}
if (cachedRecord != null) {
if (expired) {
// if the record has a 0 ttl that means we have a cancel record we need to delay the removal by 1s
if (newRecord.getTTL() == 0) {
cacheOperation = Operation.Noop;
logger.trace("Record is expired - setWillExpireSoon() on:\n\t{}", cachedRecord);
cachedRecord.setWillExpireSoon(now);
// the actual record will be disposed of by the record reaper.
} else {
cacheOperation = Operation.Remove;
logger.trace("Record is expired - removeDNSEntry() on:\n\t{}", cachedRecord);
this.getCache().removeDNSEntry(cachedRecord);
}
} else {
// If the record content has changed we need to inform our listeners.
if ( !newRecord.sameValue(cachedRecord) ||
(
!newRecord.sameSubtype(cachedRecord) &&
(newRecord.getSubtype().length() > 0)
)
) {
if (newRecord.isSingleValued()) {
cacheOperation = Operation.Update;
logger.trace("Record (singleValued) has changed - replaceDNSEntry() on:\n\t{}\n\t{}", newRecord, cachedRecord);
this.getCache().replaceDNSEntry(newRecord, cachedRecord);
} else {
// Address record can have more than one value on multi-homed machines
cacheOperation = Operation.Add;
logger.trace("Record (multiValue) has changed - addDNSEntry on:\n\t{}", newRecord);
this.getCache().addDNSEntry(newRecord);
}
} else {
cachedRecord.resetTTL(newRecord);
newRecord = cachedRecord;
}
}
} else {
if (!expired) {
cacheOperation = Operation.Add;
logger.trace("Record not cached - addDNSEntry on:\n\t{}", newRecord);
this.getCache().addDNSEntry(newRecord);
}
}
}
// Register new service types
if (newRecord.getRecordType() == DNSRecordType.TYPE_PTR) {
// handle DNSConstants.DNS_META_QUERY records
boolean typeAdded = false;
if (newRecord.isServicesDiscoveryMetaQuery()) {
// The service names are in the alias.
if (!expired) {
typeAdded = this.registerServiceType(((DNSRecord.Pointer) newRecord).getAlias());
}
return;
}
typeAdded |= this.registerServiceType(newRecord.getName());
if (typeAdded && (cacheOperation == Operation.Noop)) {
cacheOperation = Operation.RegisterServiceType;
}
}
// notify the listeners
if (cacheOperation != Operation.Noop) {
this.updateRecord(now, newRecord, cacheOperation);
}
}
/**
*
* @param dnsRecord
* @param timeToCompare a given times for comparison
* @return true if dnsRecord create time is older than 1 second, relative to the given time; false otherwise
*/
private boolean isOlderThanOneSecond(DNSRecord dnsRecord, long timeToCompare) {
return (dnsRecord.getCreated() < (timeToCompare - DNSConstants.FLUSH_RECORD_OLDER_THAN_1_SECOND*1000));
}
/**
* Handle an incoming response. Cache answers, and pass them on to the appropriate questions.
*
* @exception IOException
*/
void handleResponse(DNSIncoming msg) throws IOException {
final long now = System.currentTimeMillis();
boolean hostConflictDetected = false;
boolean serviceConflictDetected = false;
List<DNSRecord> allAnswers = msg.getAllAnswers();
allAnswers = aRecordsLast(allAnswers);
for (DNSRecord newRecord : allAnswers) {
this.handleRecord(newRecord, now);
if (DNSRecordType.TYPE_A.equals(newRecord.getRecordType()) || DNSRecordType.TYPE_AAAA.equals(newRecord.getRecordType())) {
hostConflictDetected |= newRecord.handleResponse(this);
} else {
serviceConflictDetected |= newRecord.handleResponse(this);
}
}
if (hostConflictDetected || serviceConflictDetected) {
this.startProber();
}
}
/**
* In case the a record is received before the srv record the ip address would not be set.
* <p>
* Wireshark record: see also file a_record_before_srv.pcapng and {@link ServiceInfoImplTest#test_ip_address_is_set()}
* <p>
* Multicast Domain Name System (response)
* Transaction ID: 0x0000
* Flags: 0x8400 Standard query response, No error
* Questions: 0
* Answer RRs: 2
* Authority RRs: 0
* Additional RRs: 8
* Answers
* _ibisip_http._tcp.local: type PTR, class IN, DeviceManagementService._ibisip_http._tcp.local
* _ibisip_http._tcp.local: type PTR, class IN, PassengerCountingService._ibisip_http._tcp.local
* Additional records
* DeviceManagementService._ibisip_http._tcp.local: type TXT, class IN, cache flush
* PassengerCountingService._ibisip_http._tcp.local: type TXT, class IN, cache flush
* DIST500_7-F07_OC030_05_03941.local: type A, class IN, cache flush, addr 192.168.88.236
* DeviceManagementService._ibisip_http._tcp.local: type SRV, class IN, cache flush, priority 0, weight 0, port 5000, target DIST500_7-F07_OC030_05_03941.local
* PassengerCountingService._ibisip_http._tcp.local: type SRV, class IN, cache flush, priority 0, weight 0, port 5001, target DIST500_7-F07_OC030_05_03941.local
* DeviceManagementService._ibisip_http._tcp.local: type NSEC, class IN, cache flush, next domain name DeviceManagementService._ibisip_http._tcp.local
* PassengerCountingService._ibisip_http._tcp.local: type NSEC, class IN, cache flush, next domain name PassengerCountingService._ibisip_http._tcp.local
* DIST500_7-F07_OC030_05_03941.local: type NSEC, class IN, cache flush, next domain name DIST500_7-F07_OC030_05_03941.local
*/
private List<DNSRecord> aRecordsLast(List<DNSRecord> allAnswers) {
ArrayList<DNSRecord> ret = new ArrayList<DNSRecord>(allAnswers.size());
ArrayList<DNSRecord> arecords = new ArrayList<DNSRecord>();
// filter all a records and move them to the end of the list
// we do not change der order of the order records
for (DNSRecord answer : allAnswers) {
if (answer.getRecordType().equals(DNSRecordType.TYPE_A) || answer.getRecordType().equals(DNSRecordType.TYPE_AAAA)) {
arecords.add(answer);
} else {
ret.add(answer);
}
}
ret.addAll(arecords);
return ret;
}
/**
* Handle an incoming query. See if we can answer any part of it given our service infos.
*
* @param in
* @param addr
* @param port
* @exception IOException
*/
void handleQuery(DNSIncoming in, InetAddress addr, int port) throws IOException {
logger.debug("{} handle query: {}", this.getName(), in);
// Track known answers
boolean conflictDetected = false;
final long expirationTime = System.currentTimeMillis() + DNSConstants.KNOWN_ANSWER_TTL;
for (DNSRecord answer : in.getAllAnswers()) {
conflictDetected |= answer.handleQuery(this, expirationTime);
}
this.ioLock();
try {
if (_plannedAnswer != null) {
_plannedAnswer.append(in);
} else {
DNSIncoming plannedAnswer = in.clone();
if (in.isTruncated()) {
_plannedAnswer = plannedAnswer;
}
this.startResponder(plannedAnswer, addr, port);
}
} finally {
this.ioUnlock();
}
final long now = System.currentTimeMillis();
for (DNSRecord answer : in.getAnswers()) {
this.handleRecord(answer, now);
}
if (conflictDetected) {
this.startProber();
}
}
public void respondToQuery(DNSIncoming in) {
this.ioLock();
try {
if (_plannedAnswer == in) {
_plannedAnswer = null;
}
} finally {
this.ioUnlock();
}
}
/**
* Add an answer to a question. Deal with the case when the outgoing packet overflows
*
* @param in
* @param addr
* @param port
* @param out
* @param rec
* @return outgoing answer
* @exception IOException
*/
public DNSOutgoing addAnswer(DNSIncoming in, InetAddress addr, int port, DNSOutgoing out, DNSRecord rec) throws IOException {
DNSOutgoing newOut = out;
if (newOut == null) {
newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload());
}
try {
newOut.addAnswer(in, rec);
} catch (final IOException e) {
newOut.setFlags(newOut.getFlags() | DNSConstants.FLAGS_TC);
newOut.setId(in.getId());
send(newOut);
newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload());
newOut.addAnswer(in, rec);
}
return newOut;
}
/**
* Send an outgoing multicast DNS message.
*
* @param out
* @exception IOException
*/
public void send(DNSOutgoing out) throws IOException {
if (!out.isEmpty()) {
final InetAddress addr;
final int port;
if (out.getDestination() != null) {
addr = out.getDestination().getAddress();
port = out.getDestination().getPort();
} else {
addr = _group;
port = DNSConstants.MDNS_PORT;
}
byte[] message = out.data();
final DatagramPacket packet = new DatagramPacket(message, message.length, addr, port);
if (logger.isTraceEnabled()) {
try {
final DNSIncoming msg = new DNSIncoming(packet);
if (logger.isTraceEnabled()) {
logger.trace("send({}) JmDNS out:{}", this.getName(), msg.print(true));
}
} catch (final IOException e) {
logger.debug(getClass().toString(), ".send(" + this.getName() + ") - JmDNS can not parse what it sends!!!", e);
}
}
final MulticastSocket ms = _socket;
if (ms != null && !ms.isClosed()) {
ms.send(packet);
}
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeTimer()
*/
@Override
public void purgeTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).purgeTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeStateTimer()
*/
@Override
public void purgeStateTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).purgeStateTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelTimer()
*/
@Override
public void cancelTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).cancelTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelStateTimer()
*/
@Override
public void cancelStateTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).cancelStateTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startProber()
*/
@Override
public void startProber() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startProber();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startAnnouncer()
*/
@Override
public void startAnnouncer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startAnnouncer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startRenewer()
*/
@Override
public void startRenewer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startRenewer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startCanceler()
*/
@Override
public void startCanceler() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startCanceler();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startReaper()
*/
@Override
public void startReaper() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startReaper();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceInfoResolver(javax.jmdns.impl.ServiceInfoImpl)
*/
@Override
public void startServiceInfoResolver(ServiceInfoImpl info) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startServiceInfoResolver(info);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startTypeResolver()
*/
@Override
public void startTypeResolver() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startTypeResolver();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceResolver(java.lang.String)
*/
@Override
public void startServiceResolver(String type) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startServiceResolver(type);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startResponder(javax.jmdns.impl.DNSIncoming, int)
*/
@Override
public void startResponder(DNSIncoming in, InetAddress addr, int port) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startResponder(in, addr, port);
}
// REMIND: Why is this not an anonymous inner class?
/**
* Shutdown operations.
*/
protected class Shutdown implements Runnable {
/** {@inheritDoc} */
@Override
public void run() {
try {
_shutdown = null;
close();
} catch (Throwable exception) {
System.err.println("Error while shuting down. " + exception);
}
}
}
private final Object _recoverLock = new Object();
/**
* Recover jmDNS when there is an error.
*/
public void recover() {
logger.debug("{}.recover()", this.getName());
// We have an IO error so lets try to recover if anything happens lets close it.
// This should cover the case of the IP address changing under our feet
if (this.isClosing() || this.isClosed() || this.isCanceling() || this.isCanceled()) {
return;
}
// We need some definite lock here as we may have multiple timer running in the same thread that will not be stopped by the reentrant lock
// in the state object. This is only a problem in this case as we are going to execute in seperate thread so that the timer can clear.
synchronized (_recoverLock) {
// Stop JmDNS
// This protects against recursive calls
if (this.cancelState()) {
final String newThreadName = this.getName() + ".recover()";
logger.debug("{} thread {}", newThreadName, Thread.currentThread().getName());
Thread recover = new Thread(newThreadName) {
/**
* {@inheritDoc}
*/
@Override
public void run() {
__recover();
}
};
recover.start();
}
}
}
void __recover() {
// Synchronize only if we are not already in process to prevent dead locks
//
logger.debug("{}.recover() Cleanning up", this.getName());
logger.warn("RECOVERING");
// Purge the timer
this.purgeTimer();
// We need to keep a copy for reregistration
final Collection<ServiceInfo> oldServiceInfos = new ArrayList<ServiceInfo>(getServices().values());
// Cancel all services
this.unregisterAllServices();
this.disposeServiceCollectors();
this.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
// Purge the canceler timer
this.purgeStateTimer();
//
// close multicast socket
this.closeMulticastSocket();
//
this.getCache().clear();
logger.debug("{}.recover() All is clean", this.getName());
if (this.isCanceled()) {
//
// All is clear now start the services
//
for (ServiceInfo info : oldServiceInfos) {
((ServiceInfoImpl) info).recoverState();
}
this.recoverState();
try {
this.openMulticastSocket(this.getLocalHost());
this.start(oldServiceInfos);
} catch (final Exception exception) {
logger.warn(this.getName() + ".recover() Start services exception ", exception);
}
logger.warn("{}.recover() We are back!", this.getName());
} else {
// We have a problem. We could not clear the state.
logger.warn("{}.recover() Could not recover we are Down!", this.getName());
if (this.getDelegate() != null) {
this.getDelegate().cannotRecoverFromIOError(this.getDns(), oldServiceInfos);
}
}
}
/**
* Checks the cache of expired records and removes them.
* If any records are about to expire it tries to get them refreshed.
*
* <p>
* Implementation note:<br />
* This method is called by the {@link RecordReaper} every {@link DNSConstants#RECORD_REAPER_INTERVAL} milliseconds.
* </p>
* @see DNSRecord
* @see RecordReaper
*/
public void cleanCache() {
this.getCache().logCachedContent();
final long now = System.currentTimeMillis();
final Set<String> staleServiceTypesForRefresh = new HashSet<String>();
for (final DNSEntry entry : this.getCache().allValues()) {
try {
final DNSRecord record = (DNSRecord) entry;
if (record.isExpired(now)) {
this.updateRecord(now, record, Operation.Remove);
logger.trace("Removing DNSEntry from cache: {}", entry);
this.getCache().removeDNSEntry(record);
} else if (record.isStaleAndShouldBeRefreshed(now)) {
record.incrementRefreshPercentage();
String type = record.getServiceInfo().getType().toLowerCase();
// only query every service type once per refresh
if (staleServiceTypesForRefresh.add(type)) {
// we should query for the record we care about i.e. those in the service collectors
this.renewServiceCollector(type);
}
}
} catch (Exception exception) {
logger.warn(this.getName() + ".Error while reaping records: " + entry, exception);
logger.warn(this.toString());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() {
if (this.isClosing()) {
return;
}
logger.debug("Cancelling JmDNS: {}", this);
// Stop JmDNS
// This protects against recursive calls
if (this.cancelState()) {
// We got the tie break now clean up
// Stop the timer
logger.debug("Canceling the timer");
this.cancelTimer();
// Cancel all services
this.unregisterAllServices();
this.disposeServiceCollectors();
logger.debug("Wait for JmDNS cancel: {}", this);
this.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
// Stop the canceler timer
logger.debug("Canceling the state timer");
this.cancelStateTimer();
// Stop the executor
_executor.shutdown();
// close socket
this.closeMulticastSocket();
// remove the shutdown hook
if (_shutdown != null) {
Runtime.getRuntime().removeShutdownHook(_shutdown);
}
// earlier we did a DNSTaskStarter.Factory.getInstance().getStarter(this.getDns())
// now we must release the resources associated with the starter for this JmDNS instance
DNSTaskStarter.Factory.getInstance().disposeStarter(this.getDns());
logger.debug("JmDNS closed.");
}
advanceState(null);
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public void printServices() {
System.err.println(toString());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(2048);
sb.append("\n");
sb.append("\t---- Local Host -----");
sb.append("\n\t");
sb.append(_localHost);
sb.append("\n\t---- Services -----");
for (final Map.Entry<String, ServiceInfo> entry : _services.entrySet()) {
sb.append("\n\t\tService: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\n");
sb.append("\t---- Types ----");
for (final ServiceTypeEntry subtypes : _serviceTypes.values()) {
sb.append("\n\t\tType: ");
sb.append(subtypes.getType());
sb.append(": ");
sb.append(subtypes.isEmpty() ? "no subtypes" : subtypes);
}
sb.append("\n");
sb.append(_cache.toString());
sb.append("\n");
sb.append("\t---- Service Collectors ----");
for (final Map.Entry<String, ServiceCollector> entry : _serviceCollectors.entrySet()) {
sb.append("\n\t\tService Collector: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\n");
sb.append("\t---- Service Listeners ----");
for (final Map.Entry<String, List<ListenerStatus.ServiceListenerStatus>> entry : _serviceListeners.entrySet()) {
sb.append("\n\t\tService Listener: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo[] list(String type) {
return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo[] list(String type, long timeout) {
this.cleanCache();
// Implementation note: The first time a list for a given type is
// requested, a ServiceCollector is created which collects service
// infos. This greatly speeds up the performance of subsequent calls
// to this method. The caveats are, that 1) the first call to this
// method for a given type is slow, and 2) we spawn a ServiceCollector
// instance for each service type which increases network traffic a
// little.
String loType = type.toLowerCase();
boolean newCollectorCreated = false;
if (this.isCanceling() || this.isCanceled()) {
return new ServiceInfo[0];
}
ServiceCollector collector = _serviceCollectors.get(loType);
if (collector == null) {
newCollectorCreated = _serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null;
collector = _serviceCollectors.get(loType);
if (newCollectorCreated) {
this.addServiceListener(type, collector, ListenerStatus.SYNCHRONOUS);
}
}
logger.debug("{}-collector: {}", this.getName(), collector);
// At this stage the collector should never be null but it keeps findbugs happy.
return (collector != null ? collector.list(timeout) : new ServiceInfo[0]);
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(String type) {
return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(String type, long timeout) {
Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5);
for (ServiceInfo info : this.list(type, timeout)) {
String subtype = info.getSubtype().toLowerCase();
if (!map.containsKey(subtype)) {
map.put(subtype, new ArrayList<ServiceInfo>(10));
}
map.get(subtype).add(info);
}
Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size());
for (final Map.Entry<String, List<ServiceInfo>> entry : map.entrySet()) {
final String subtype = entry.getKey();
final List<ServiceInfo> infoForSubType = entry.getValue();
result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()]));
}
return result;
}
/**
* This method disposes all ServiceCollector instances which have been created by calls to method <code>list(type)</code>.
*
* @see #list
*/
private void disposeServiceCollectors() {
logger.debug("disposeServiceCollectors()");
for (final Map.Entry<String, ServiceCollector> entry : _serviceCollectors.entrySet()) {
final ServiceCollector collector = entry.getValue();
if (collector != null) {
final String type = entry.getKey();
this.removeServiceListener(type, collector);
_serviceCollectors.remove(type, collector);
}
}
}
/**
* Instances of ServiceCollector are used internally to speed up the performance of method <code>list(type)</code>.
*
* @see #list
*/
private static class ServiceCollector implements ServiceListener {
// private static Logger logger = LoggerFactory.getLogger(ServiceCollector.class.getName());
/**
* A set of collected service instance names.
*/
private final ConcurrentMap<String, ServiceInfo> _infos;
/**
* A set of collected service event waiting to be resolved.
*/
private final ConcurrentMap<String, ServiceEvent> _events;
/**
* This is the type we are listening for (only used for debugging).
*/
private final String _type;
/**
* This is used to force a wait on the first invocation of list.
*/
private volatile boolean _needToWaitForInfos;
public ServiceCollector(String type) {
super();
_infos = new ConcurrentHashMap<String, ServiceInfo>();
_events = new ConcurrentHashMap<String, ServiceEvent>();
_type = type;
_needToWaitForInfos = true;
}
/**
* A service has been added.
*
* @param event
* service event
*/
@Override
public void serviceAdded(ServiceEvent event) {
synchronized (this) {
ServiceInfo info = event.getInfo();
if ((info != null) && (info.hasData())) {
_infos.put(event.getName(), info);
} else {
String subtype = (info != null ? info.getSubtype() : "");
info = ((JmDNSImpl) event.getDNS()).resolveServiceInfo(event.getType(), event.getName(), subtype, true);
if (info != null) {
_infos.put(event.getName(), info);
} else {
_events.put(event.getName(), event);
}
}
}
}
/**
* A service has been removed.
*
* @param event
* service event
*/
@Override
public void serviceRemoved(ServiceEvent event) {
synchronized (this) {
_infos.remove(event.getName());
_events.remove(event.getName());
}
}
/**
* A service has been resolved. Its details are now available in the ServiceInfo record.
*
* @param event
* service event
*/
@Override
public void serviceResolved(ServiceEvent event) {
synchronized (this) {
_infos.put(event.getName(), event.getInfo());
_events.remove(event.getName());
}
}
/**
* Returns an array of all service infos which have been collected by this ServiceCollector.
*
* @param timeout
* timeout if the info list is empty.
* @return Service Info array
*/
public ServiceInfo[] list(long timeout) {
if (_infos.isEmpty() || !_events.isEmpty() || _needToWaitForInfos) {
long loops = (timeout / 200L);
if (loops < 1) {
loops = 1;
}
for (int i = 0; i < loops; i++) {
try {
Thread.sleep(200);
} catch (final InterruptedException e) {
/* Stub */
}
if (_events.isEmpty() && !_infos.isEmpty() && !_needToWaitForInfos) {
break;
}
}
}
_needToWaitForInfos = false;
return _infos.values().toArray(new ServiceInfo[_infos.size()]);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("\n\tType: ");
sb.append(_type);
if (_infos.isEmpty()) {
sb.append("\n\tNo services collected.");
} else {
sb.append("\n\tServices");
for (final Map.Entry<String, ServiceInfo> entry : _infos.entrySet()) {
sb.append("\n\t\tService: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
}
if (_events.isEmpty()) {
sb.append("\n\tNo event queued.");
} else {
sb.append("\n\tEvents");
for (final Map.Entry<String, ServiceEvent> entry : _events.entrySet()) {
sb.append("\n\t\tEvent: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
}
return sb.toString();
}
}
static String toUnqualifiedName(String type, String qualifiedName) {
String loType = type.toLowerCase();
String loQualifiedName = qualifiedName.toLowerCase();
if (loQualifiedName.endsWith(loType) && !(loQualifiedName.equals(loType))) {
return qualifiedName.substring(0, qualifiedName.length() - type.length() - 1);
}
return qualifiedName;
}
public Map<String, ServiceInfo> getServices() {
return _services;
}
public void setLastThrottleIncrement(long lastThrottleIncrement) {
this._lastThrottleIncrement = lastThrottleIncrement;
}
public long getLastThrottleIncrement() {
return _lastThrottleIncrement;
}
public void setThrottle(int throttle) {
this._throttle = throttle;
}
public int getThrottle() {
return _throttle;
}
public static Random getRandom() {
return _random;
}
public void ioLock() {
_ioLock.lock();
}
public void ioUnlock() {
_ioLock.unlock();
}
public void setPlannedAnswer(DNSIncoming plannedAnswer) {
this._plannedAnswer = plannedAnswer;
}
public DNSIncoming getPlannedAnswer() {
return _plannedAnswer;
}
void setLocalHost(HostInfo localHost) {
this._localHost = localHost;
}
public Map<String, ServiceTypeEntry> getServiceTypes() {
return _serviceTypes;
}
public MulticastSocket getSocket() {
return _socket;
}
public InetAddress getGroup() {
return _group;
}
@Override
public Delegate getDelegate() {
return this._delegate;
}
@Override
public Delegate setDelegate(Delegate delegate) {
Delegate previous = this._delegate;
this._delegate = delegate;
return previous;
}
}
|
src/main/java/javax/jmdns/impl/JmDNSImpl.java
|
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceInfo.Fields;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
import javax.jmdns.impl.ListenerStatus.ServiceListenerStatus;
import javax.jmdns.impl.ListenerStatus.ServiceTypeListenerStatus;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
import javax.jmdns.impl.constants.DNSState;
import javax.jmdns.impl.tasks.DNSTask;
import javax.jmdns.impl.tasks.RecordReaper;
import javax.jmdns.impl.util.NamedThreadFactory;
// REMIND: multiple IP addresses
/**
* mDNS implementation in Java.
*
* @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis, Kai Kreuzer, Victor Toni
*/
public class JmDNSImpl extends JmDNS implements DNSStatefulObject, DNSTaskStarter {
private static Logger logger = LoggerFactory.getLogger(JmDNSImpl.class.getName());
public enum Operation {
Remove, Update, Add, RegisterServiceType, Noop
}
/**
* This is the multicast group, we are listening to for multicast DNS messages.
*/
private volatile InetAddress _group;
/**
* This is our multicast socket.
*/
private volatile MulticastSocket _socket;
/**
* Holds instances of JmDNS.DNSListener. Must by a synchronized collection, because it is updated from concurrent threads.
*/
private final List<DNSListener> _listeners;
/**
* Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's.
*/
/* default */ final ConcurrentMap<String, List<ServiceListenerStatus>> _serviceListeners;
/**
* Holds instances of ServiceTypeListener's.
*/
private final Set<ServiceTypeListenerStatus> _typeListeners;
/**
* Cache for DNSEntry's.
*/
private final DNSCache _cache;
/**
* This hashtable holds the services that have been registered. Keys are instances of String which hold an all lower-case version of the fully qualified service name. Values are instances of ServiceInfo.
*/
private final ConcurrentMap<String, ServiceInfo> _services;
/**
* This hashtable holds the service types that have been registered or that have been received in an incoming datagram.<br/>
* Keys are instances of String which hold an all lower-case version of the fully qualified service type.<br/>
* Values hold the fully qualified service type.
*/
private final ConcurrentMap<String, ServiceTypeEntry> _serviceTypes;
private volatile Delegate _delegate;
/**
* This is used to store type entries. The type is stored as a call variable and the map support the subtypes.
* <p>
* The key is the lowercase version as the value is the case preserved version.
* </p>
*/
public static class ServiceTypeEntry extends AbstractMap<String, String>implements Cloneable {
private final Set<Map.Entry<String, String>> _entrySet;
private final String _type;
private static class SubTypeEntry implements Entry<String, String>, java.io.Serializable, Cloneable {
private static final long serialVersionUID = 9188503522395855322L;
private final String _key;
private final String _value;
public SubTypeEntry(String subtype) {
super();
_value = (subtype != null ? subtype : "");
_key = _value.toLowerCase();
}
/**
* {@inheritDoc}
*/
@Override
public String getKey() {
return _key;
}
/**
* {@inheritDoc}
*/
@Override
public String getValue() {
return _value;
}
/**
* Replaces the value corresponding to this entry with the specified value (optional operation). This implementation simply throws <tt>UnsupportedOperationException</tt>, as this class implements an <i>immutable</i> map entry.
*
* @param value
* new value to be stored in this entry
* @return (Does not return)
* @exception UnsupportedOperationException
* always
*/
@Override
public String setValue(String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object entry) {
if (!(entry instanceof Map.Entry)) {
return false;
}
return this.getKey().equals(((Map.Entry<?, ?>) entry).getKey()) && this.getValue().equals(((Map.Entry<?, ?>) entry).getValue());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return (_key == null ? 0 : _key.hashCode()) ^ (_value == null ? 0 : _value.hashCode());
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public SubTypeEntry clone() {
// Immutable object
return this;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return _key + "=" + _value;
}
}
public ServiceTypeEntry(String type) {
super();
this._type = type;
this._entrySet = new HashSet<Map.Entry<String, String>>();
}
/**
* The type associated with this entry.
*
* @return the type
*/
public String getType() {
return _type;
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#entrySet()
*/
@Override
public Set<Map.Entry<String, String>> entrySet() {
return _entrySet;
}
/**
* Returns <code>true</code> if this set contains the specified element. More formally, returns <code>true</code> if and only if this set contains an element <code>e</code> such that
* <code>(o==null ? e==null : o.equals(e))</code>.
*
* @param subtype
* element whose presence in this set is to be tested
* @return <code>true</code> if this set contains the specified element
*/
public boolean contains(String subtype) {
return subtype != null && this.containsKey(subtype.toLowerCase());
}
/**
* Adds the specified element to this set if it is not already present. More formally, adds the specified element <code>e</code> to this set if this set contains no element <code>e2</code> such that
* <code>(e==null ? e2==null : e.equals(e2))</code>. If this set already contains the element, the call leaves the set unchanged and returns <code>false</code>.
*
* @param subtype
* element to be added to this set
* @return <code>true</code> if this set did not already contain the specified element
*/
public boolean add(String subtype) {
if (subtype == null || this.contains(subtype)) {
return false;
}
_entrySet.add(new SubTypeEntry(subtype));
return true;
}
/**
* Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).
*
* @return an iterator over the elements in this set
*/
public Iterator<String> iterator() {
return this.keySet().iterator();
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#clone()
*/
@Override
public ServiceTypeEntry clone() {
ServiceTypeEntry entry = new ServiceTypeEntry(this.getType());
for (Map.Entry<String, String> subTypeEntry : this.entrySet()) {
entry.add(subTypeEntry.getValue());
}
return entry;
}
/*
* (non-Javadoc)
* @see java.util.AbstractMap#toString()
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(200);
if (this.isEmpty()) {
sb.append("empty");
} else {
for (String value : this.values()) {
sb.append(value);
sb.append(", ");
}
sb.setLength(sb.length() - 2);
}
return sb.toString();
}
}
/**
* This is the shutdown hook, we registered with the java runtime.
*/
protected Thread _shutdown;
/**
* Handle on the local host
*/
private HostInfo _localHost;
private Thread _incomingListener;
/**
* Throttle count. This is used to count the overall number of probes sent by JmDNS. When the last throttle increment happened .
*/
private int _throttle;
/**
* Last throttle increment.
*/
private long _lastThrottleIncrement;
private final ExecutorService _executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmDNS"));
//
// 2009-09-16 ldeck: adding docbug patch with slight ammendments
// 'Fixes two deadlock conditions involving JmDNS.close() - ID: 1473279'
//
// ---------------------------------------------------
/**
* The timer that triggers our announcements. We can't use the main timer object, because that could cause a deadlock where Prober waits on JmDNS.this lock held by close(), close() waits for us to finish, and we wait for Prober to give us back
* the timer thread so we can announce. (Patch from docbug in 2006-04-19 still wasn't patched .. so I'm doing it!)
*/
// private final Timer _cancelerTimer;
// ---------------------------------------------------
/**
* The source for random values. This is used to introduce random delays in responses. This reduces the potential for collisions on the network.
*/
private final static Random _random = new Random();
/**
* This lock is used to coordinate processing of incoming and outgoing messages. This is needed, because the Rendezvous Conformance Test does not forgive race conditions.
*/
private final ReentrantLock _ioLock = new ReentrantLock();
/**
* If an incoming package which needs an answer is truncated, we store it here. We add more incoming DNSRecords to it, until the JmDNS.Responder timer picks it up.<br/>
* FIXME [PJYF June 8 2010]: This does not work well with multiple planned answers for packages that came in from different clients.
*/
private DNSIncoming _plannedAnswer;
// State machine
/**
* This hashtable is used to maintain a list of service types being collected by this JmDNS instance. The key of the hashtable is a service type name, the value is an instance of JmDNS.ServiceCollector.
*
* @see #list
*/
private final ConcurrentMap<String, ServiceCollector> _serviceCollectors;
private final String _name;
/**
* Main method to display API information if run from java -jar
*
* @param argv
* the command line arguments
*/
public static void main(String[] argv) {
String version = null;
try {
final Properties pomProperties = new Properties();
pomProperties.load(JmDNSImpl.class.getResourceAsStream("/META-INF/maven/javax.jmdns/jmdns/pom.properties"));
version = pomProperties.getProperty("version");
} catch (Exception e) {
version = "RUNNING.IN.IDE.FULL";
}
System.out.println("JmDNS version \"" + version + "\"");
System.out.println(" ");
System.out.println("Running on java version \"" + System.getProperty("java.version") + "\"" + " (build " + System.getProperty("java.runtime.version") + ")" + " from " + System.getProperty("java.vendor"));
System.out.println("Operating environment \"" + System.getProperty("os.name") + "\"" + " version " + System.getProperty("os.version") + " on " + System.getProperty("os.arch"));
System.out.println("For more information on JmDNS please visit http://jmdns.org");
}
/**
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
*
* @param address
* IP address to bind to.
* @param name
* name of the newly created JmDNS
* @exception IOException
*/
public JmDNSImpl(InetAddress address, String name) throws IOException {
super();
logger.debug("JmDNS instance created");
_cache = new DNSCache(100);
_listeners = Collections.synchronizedList(new ArrayList<DNSListener>());
_serviceListeners = new ConcurrentHashMap<String, List<ServiceListenerStatus>>();
_typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListenerStatus>());
_serviceCollectors = new ConcurrentHashMap<String, ServiceCollector>();
_services = new ConcurrentHashMap<String, ServiceInfo>(20);
_serviceTypes = new ConcurrentHashMap<String, ServiceTypeEntry>(20);
_localHost = HostInfo.newHostInfo(address, this, name);
_name = (name != null ? name : _localHost.getName());
// _cancelerTimer = new Timer("JmDNS.cancelerTimer");
// (ldeck 2.1.1) preventing shutdown blocking thread
// -------------------------------------------------
// _shutdown = new Thread(new Shutdown(), "JmDNS.Shutdown");
// Runtime.getRuntime().addShutdownHook(_shutdown);
// -------------------------------------------------
// Bind to multicast socket
this.openMulticastSocket(this.getLocalHost());
this.start(this.getServices().values());
this.startReaper();
}
private void start(Collection<? extends ServiceInfo> serviceInfos) {
if (_incomingListener == null) {
_incomingListener = new SocketListener(this);
_incomingListener.start();
}
this.startProber();
for (ServiceInfo info : serviceInfos) {
try {
this.registerService(new ServiceInfoImpl(info));
} catch (final Exception exception) {
logger.warn("start() Registration exception ", exception);
}
}
}
private void openMulticastSocket(HostInfo hostInfo) throws IOException {
if (_group == null) {
if (hostInfo.getInetAddress() instanceof Inet6Address) {
_group = InetAddress.getByName(DNSConstants.MDNS_GROUP_IPV6);
} else {
_group = InetAddress.getByName(DNSConstants.MDNS_GROUP);
}
}
if (_socket != null) {
this.closeMulticastSocket();
}
// SocketAddress address = new InetSocketAddress((hostInfo != null ? hostInfo.getInetAddress() : null), DNSConstants.MDNS_PORT);
// System.out.println("Socket Address: " + address);
// try {
// _socket = new MulticastSocket(address);
// } catch (Exception exception) {
// logger.warn("openMulticastSocket() Open socket exception Address: " + address + ", ", exception);
// // The most likely cause is a duplicate address lets open without specifying the address
// _socket = new MulticastSocket(DNSConstants.MDNS_PORT);
// }
_socket = new MulticastSocket(DNSConstants.MDNS_PORT);
if ((hostInfo != null) && (hostInfo.getInterface() != null)) {
final SocketAddress multicastAddr = new InetSocketAddress(_group, DNSConstants.MDNS_PORT);
_socket.setNetworkInterface(hostInfo.getInterface());
logger.trace("Trying to joinGroup({}, {})", multicastAddr, hostInfo.getInterface());
// this joinGroup() might be less surprisingly so this is the default
_socket.joinGroup(multicastAddr, hostInfo.getInterface());
} else {
logger.trace("Trying to joinGroup({})", _group);
_socket.joinGroup(_group);
}
_socket.setTimeToLive(255);
}
private void closeMulticastSocket() {
// jP: 20010-01-18. See below. We'll need this monitor...
// assert (Thread.holdsLock(this));
logger.debug("closeMulticastSocket()");
if (_socket != null) {
// close socket
try {
try {
_socket.leaveGroup(_group);
} catch (SocketException exception) {
//
}
_socket.close();
// jP: 20010-01-18. It isn't safe to join() on the listener
// thread - it attempts to lock the IoLock object, and deadlock
// ensues. Per issue #2933183, changed this to wait on the JmDNS
// monitor, checking on each notify (or timeout) that the
// listener thread has stopped.
//
while (_incomingListener != null && _incomingListener.isAlive()) {
synchronized (this) {
try {
if (_incomingListener != null && _incomingListener.isAlive()) {
// wait time is arbitrary, we're really expecting notification.
logger.debug("closeMulticastSocket(): waiting for jmDNS monitor");
this.wait(1000);
}
} catch (InterruptedException ignored) {
// Ignored
}
}
}
_incomingListener = null;
} catch (final Exception exception) {
logger.warn("closeMulticastSocket() Close socket exception ", exception);
}
_socket = null;
}
}
// State machine
/**
* {@inheritDoc}
*/
@Override
public boolean advanceState(DNSTask task) {
return this._localHost.advanceState(task);
}
/**
* {@inheritDoc}
*/
@Override
public boolean revertState() {
return this._localHost.revertState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancelState() {
return this._localHost.cancelState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean closeState() {
return this._localHost.closeState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean recoverState() {
return this._localHost.recoverState();
}
/**
* {@inheritDoc}
*/
@Override
public JmDNSImpl getDns() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void associateWithTask(DNSTask task, DNSState state) {
this._localHost.associateWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public void removeAssociationWithTask(DNSTask task) {
this._localHost.removeAssociationWithTask(task);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
return this._localHost.isAssociatedWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isProbing() {
return this._localHost.isProbing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnouncing() {
return this._localHost.isAnnouncing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnounced() {
return this._localHost.isAnnounced();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceling() {
return this._localHost.isCanceling();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceled() {
return this._localHost.isCanceled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosing() {
return this._localHost.isClosing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return this._localHost.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForAnnounced(long timeout) {
return this._localHost.waitForAnnounced(timeout);
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForCanceled(long timeout) {
return this._localHost.waitForCanceled(timeout);
}
/**
* Return the DNSCache associated with the cache variable
*
* @return DNS cache
*/
public DNSCache getCache() {
return _cache;
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return _name;
}
/**
* {@inheritDoc}
*/
@Override
public String getHostName() {
return _localHost.getName();
}
/**
* Returns the local host info
*
* @return local host info
*/
public HostInfo getLocalHost() {
return _localHost;
}
/**
* {@inheritDoc}
*/
@Override
public InetAddress getInetAddress() throws IOException {
return _localHost.getInetAddress();
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public InetAddress getInterface() throws IOException {
return _socket.getInterface();
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name) {
return this.getServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, long timeout) {
return this.getServiceInfo(type, name, false, timeout);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, boolean persistent) {
return this.getServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo getServiceInfo(String type, String name, boolean persistent, long timeout) {
final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent);
this.waitForInfoData(info, timeout);
return (info.hasData() ? info : null);
}
ServiceInfoImpl resolveServiceInfo(String type, String name, String subtype, boolean persistent) {
this.cleanCache();
String loType = type.toLowerCase();
this.registerServiceType(type);
if (_serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null) {
this.addServiceListener(loType, _serviceCollectors.get(loType), ListenerStatus.SYNCHRONOUS);
}
// Check if the answer is in the cache.
final ServiceInfoImpl info = this.getServiceInfoFromCache(type, name, subtype, persistent);
// We still run the resolver to do the dispatch but if the info is already there it will quit immediately
this.startServiceInfoResolver(info);
return info;
}
ServiceInfoImpl getServiceInfoFromCache(String type, String name, String subtype, boolean persistent) {
// Check if the answer is in the cache.
ServiceInfoImpl info = new ServiceInfoImpl(type, name, subtype, 0, 0, 0, persistent, (byte[]) null);
DNSEntry pointerEntry = this.getCache().getDNSEntry(new DNSRecord.Pointer(type, DNSRecordClass.CLASS_ANY, false, 0, info.getQualifiedName()));
if (pointerEntry instanceof DNSRecord) {
ServiceInfoImpl cachedInfo = (ServiceInfoImpl) ((DNSRecord) pointerEntry).getServiceInfo(persistent);
if (cachedInfo != null) {
// To get a complete info record we need to retrieve the service, address and the text bytes.
Map<Fields, String> map = cachedInfo.getQualifiedNameMap();
byte[] srvBytes = null;
String server = "";
DNSEntry serviceEntry = this.getCache().getDNSEntry(info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_ANY);
if (serviceEntry instanceof DNSRecord) {
ServiceInfo cachedServiceEntryInfo = ((DNSRecord) serviceEntry).getServiceInfo(persistent);
if (cachedServiceEntryInfo != null) {
cachedInfo = new ServiceInfoImpl(map, cachedServiceEntryInfo.getPort(), cachedServiceEntryInfo.getWeight(), cachedServiceEntryInfo.getPriority(), persistent, (byte[]) null);
srvBytes = cachedServiceEntryInfo.getTextBytes();
server = cachedServiceEntryInfo.getServer();
}
}
for (DNSEntry addressEntry : this.getCache().getDNSEntryList(server, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_ANY)) {
if (addressEntry instanceof DNSRecord) {
ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent);
if (cachedAddressInfo != null) {
for (Inet4Address address : cachedAddressInfo.getInet4Addresses()) {
cachedInfo.addAddress(address);
}
cachedInfo._setText(cachedAddressInfo.getTextBytes());
}
}
}
for (DNSEntry addressEntry : this.getCache().getDNSEntryList(server, DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_ANY)) {
if (addressEntry instanceof DNSRecord) {
ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent);
if (cachedAddressInfo != null) {
for (Inet6Address address : cachedAddressInfo.getInet6Addresses()) {
cachedInfo.addAddress(address);
}
cachedInfo._setText(cachedAddressInfo.getTextBytes());
}
}
}
DNSEntry textEntry = this.getCache().getDNSEntry(cachedInfo.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_ANY);
if (textEntry instanceof DNSRecord) {
ServiceInfo cachedTextInfo = ((DNSRecord) textEntry).getServiceInfo(persistent);
if (cachedTextInfo != null) {
cachedInfo._setText(cachedTextInfo.getTextBytes());
}
}
if (cachedInfo.getTextBytes().length == 0) {
cachedInfo._setText(srvBytes);
}
if (cachedInfo.hasData()) {
info = cachedInfo;
}
}
}
return info;
}
private void waitForInfoData(ServiceInfo info, long timeout) {
synchronized (info) {
long loops = (timeout / 200L);
if (loops < 1) {
loops = 1;
}
for (int i = 0; i < loops; i++) {
if (info.hasData()) {
break;
}
try {
info.wait(200);
} catch (final InterruptedException e) {
/* Stub */
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name) {
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, boolean persistent) {
this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, long timeout) {
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public void requestServiceInfo(String type, String name, boolean persistent, long timeout) {
final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent);
this.waitForInfoData(info, timeout);
}
void handleServiceResolved(ServiceEvent event) {
List<ServiceListenerStatus> list = _serviceListeners.get(event.getType().toLowerCase());
final List<ServiceListenerStatus> listCopy;
if ((list != null) && (!list.isEmpty())) {
if ((event.getInfo() != null) && event.getInfo().hasData()) {
final ServiceEvent localEvent = event;
synchronized (list) {
listCopy = new ArrayList<ServiceListenerStatus>(list);
}
for (final ServiceListenerStatus listener : listCopy) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceResolved(localEvent);
}
});
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void addServiceTypeListener(ServiceTypeListener listener) throws IOException {
ServiceTypeListenerStatus status = new ServiceTypeListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
_typeListeners.add(status);
// report cached service types
for (String type : _serviceTypes.keySet()) {
status.serviceTypeAdded(new ServiceEventImpl(this, type, "", null));
}
this.startTypeResolver();
}
/**
* {@inheritDoc}
*/
@Override
public void removeServiceTypeListener(ServiceTypeListener listener) {
ServiceTypeListenerStatus status = new ServiceTypeListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
_typeListeners.remove(status);
}
/**
* {@inheritDoc}
*/
@Override
public void addServiceListener(String type, ServiceListener listener) {
this.addServiceListener(type, listener, ListenerStatus.ASYNCHRONOUS);
}
private void addServiceListener(String type, ServiceListener listener, boolean synch) {
ServiceListenerStatus status = new ServiceListenerStatus(listener, synch);
final String loType = type.toLowerCase();
List<ServiceListenerStatus> list = _serviceListeners.get(loType);
if (list == null) {
if (_serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListenerStatus>()) == null) {
if (_serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null) {
// We have a problem here. The service collectors must be called synchronously so that their cache get cleaned up immediately or we will report .
this.addServiceListener(loType, _serviceCollectors.get(loType), ListenerStatus.SYNCHRONOUS);
}
}
list = _serviceListeners.get(loType);
}
if (list != null) {
synchronized (list) {
if (!list.contains(status)) {
list.add(status);
}
}
}
// report cached service types
final List<ServiceEvent> serviceEvents = new ArrayList<ServiceEvent>();
Collection<DNSEntry> dnsEntryLits = this.getCache().allValues();
for (DNSEntry entry : dnsEntryLits) {
final DNSRecord record = (DNSRecord) entry;
if (record.getRecordType() == DNSRecordType.TYPE_SRV) {
if (record.getKey().endsWith(loType)) {
// Do not used the record embedded method for generating event this will not work.
// serviceEvents.add(record.getServiceEvent(this));
serviceEvents.add(new ServiceEventImpl(this, record.getType(), toUnqualifiedName(record.getType(), record.getName()), record.getServiceInfo()));
}
}
}
// Actually call listener with all service events added above
for (ServiceEvent serviceEvent : serviceEvents) {
status.serviceAdded(serviceEvent);
}
// Create/start ServiceResolver
this.startServiceResolver(type);
}
/**
* {@inheritDoc}
*/
@Override
public void removeServiceListener(String type, ServiceListener listener) {
String loType = type.toLowerCase();
List<ServiceListenerStatus> list = _serviceListeners.get(loType);
if (list != null) {
synchronized (list) {
ServiceListenerStatus status = new ServiceListenerStatus(listener, ListenerStatus.ASYNCHRONOUS);
list.remove(status);
if (list.isEmpty()) {
_serviceListeners.remove(loType, list);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerService(ServiceInfo infoAbstract) throws IOException {
if (this.isClosing() || this.isClosed()) {
throw new IllegalStateException("This DNS is closed.");
}
final ServiceInfoImpl info = (ServiceInfoImpl) infoAbstract;
if (info.getDns() != null) {
if (info.getDns() != this) {
throw new IllegalStateException("A service information can only be registered with a single instamce of JmDNS.");
} else if (_services.get(info.getKey()) != null) {
throw new IllegalStateException("A service information can only be registered once.");
}
}
info.setDns(this);
this.registerServiceType(info.getTypeWithSubtype());
// bind the service to this address
info.recoverState();
info.setServer(_localHost.getName());
info.addAddress(_localHost.getInet4Address());
info.addAddress(_localHost.getInet6Address());
this.waitForAnnounced(DNSConstants.SERVICE_INFO_TIMEOUT);
this.makeServiceNameUnique(info);
while (_services.putIfAbsent(info.getKey(), info) != null) {
this.makeServiceNameUnique(info);
}
this.startProber();
info.waitForAnnounced(DNSConstants.SERVICE_INFO_TIMEOUT);
logger.debug("registerService() JmDNS registered service as {}", info);
}
/**
* {@inheritDoc}
*/
@Override
public void unregisterService(ServiceInfo infoAbstract) {
final ServiceInfoImpl info = (ServiceInfoImpl) _services.get(infoAbstract.getKey());
if (info != null) {
info.cancelState();
this.startCanceler();
info.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
_services.remove(info.getKey(), info);
logger.debug("unregisterService() JmDNS {} unregistered service as {}", this.getName(), info);
} else {
logger.warn("{} removing unregistered service info: {}", this.getName(), infoAbstract.getKey());
}
}
/**
* {@inheritDoc}
*/
@Override
public void unregisterAllServices() {
logger.debug("unregisterAllServices()");
for (final ServiceInfo info : _services.values()) {
if (info != null) {
final ServiceInfoImpl infoImpl = (ServiceInfoImpl) info;
logger.debug("Cancelling service info: {}", info);
infoImpl.cancelState();
}
}
this.startCanceler();
for (final Map.Entry<String, ServiceInfo> entry : _services.entrySet()) {
final ServiceInfo info = entry.getValue();
if (info != null) {
final ServiceInfoImpl infoImpl = (ServiceInfoImpl) info;
final String name = entry.getKey();
logger.debug("Wait for service info cancel: {}", info);
infoImpl.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
_services.remove(name, info);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean registerServiceType(String type) {
boolean typeAdded = false;
Map<Fields, String> map = ServiceInfoImpl.decodeQualifiedNameMapForType(type);
String domain = map.get(Fields.Domain);
String protocol = map.get(Fields.Protocol);
String application = map.get(Fields.Application);
String subtype = map.get(Fields.Subtype);
final String name = (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + ".";
final String loname = name.toLowerCase();
logger.debug("{} registering service type: {} as: {}{}{}",
this.getName(),
type,
name,
(subtype.length() > 0 ? " subtype: " : ""),
(subtype.length() > 0 ? subtype : "")
);
if (!_serviceTypes.containsKey(loname) && !application.toLowerCase().equals("dns-sd") && !domain.toLowerCase().endsWith("in-addr.arpa") && !domain.toLowerCase().endsWith("ip6.arpa")) {
typeAdded = _serviceTypes.putIfAbsent(loname, new ServiceTypeEntry(name)) == null;
if (typeAdded) {
final ServiceTypeListenerStatus[] list = _typeListeners.toArray(new ServiceTypeListenerStatus[_typeListeners.size()]);
final ServiceEvent event = new ServiceEventImpl(this, name, "", null);
for (final ServiceTypeListenerStatus status : list) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
status.serviceTypeAdded(event);
}
});
}
}
}
if (subtype.length() > 0) {
ServiceTypeEntry subtypes = _serviceTypes.get(loname);
if ((subtypes != null) && (!subtypes.contains(subtype))) {
synchronized (subtypes) {
if (!subtypes.contains(subtype)) {
typeAdded = true;
subtypes.add(subtype);
final ServiceTypeListenerStatus[] list = _typeListeners.toArray(new ServiceTypeListenerStatus[_typeListeners.size()]);
final ServiceEvent event = new ServiceEventImpl(this, "_" + subtype + "._sub." + name, "", null);
for (final ServiceTypeListenerStatus status : list) {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
status.subTypeForServiceTypeAdded(event);
}
});
}
}
}
}
}
return typeAdded;
}
/**
* Generate a possibly unique name for a service using the information we have in the cache.
*
* @return returns true, if the name of the service info had to be changed.
*/
private boolean makeServiceNameUnique(ServiceInfoImpl info) {
final String originalQualifiedName = info.getKey();
final long now = System.currentTimeMillis();
boolean collision;
do {
collision = false;
// Check for collision in cache
for (DNSEntry dnsEntry : this.getCache().getDNSEntryList(info.getKey())) {
if (DNSRecordType.TYPE_SRV.equals(dnsEntry.getRecordType()) && !dnsEntry.isExpired(now)) {
final DNSRecord.Service s = (DNSRecord.Service) dnsEntry;
if (s.getPort() != info.getPort() || !s.getServer().equals(_localHost.getName())) {
logger.debug("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:{} s.server={} {} equals:{}",
dnsEntry,
s.getServer(),
_localHost.getName(),
s.getServer().equals(_localHost.getName())
);
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(), info.getName(), NameRegister.NameType.SERVICE));
collision = true;
break;
}
}
}
// Check for collision with other service infos published by JmDNS
final ServiceInfo selfService = _services.get(info.getKey());
if (selfService != null && selfService != info) {
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(), info.getName(), NameRegister.NameType.SERVICE));
collision = true;
}
}
while (collision);
return !(originalQualifiedName.equals(info.getKey()));
}
/**
* Add a listener for a question. The listener will receive updates of answers to the question as they arrive, or from the cache if they are already available.
*
* @param listener
* DSN listener
* @param question
* DNS query
*/
public void addListener(DNSListener listener, DNSQuestion question) {
final long now = System.currentTimeMillis();
// add the new listener
_listeners.add(listener);
// report existing matched records
if (question != null) {
for (DNSEntry dnsEntry : this.getCache().getDNSEntryList(question.getName().toLowerCase())) {
if (question.answeredBy(dnsEntry) && !dnsEntry.isExpired(now)) {
listener.updateRecord(this.getCache(), now, dnsEntry);
}
}
}
}
/**
* Remove a listener from all outstanding questions. The listener will no longer receive any updates.
*
* @param listener
* DSN listener
*/
public void removeListener(DNSListener listener) {
_listeners.remove(listener);
}
/**
* Renew a service when the record become stale. If there is no service collector for the type this method does nothing.
*
* @param type
* Service Type
*/
public void renewServiceCollector(String type) {
if (_serviceCollectors.containsKey(type.toLowerCase())) {
// Create/start ServiceResolver
this.startServiceResolver(type);
}
}
// Remind: Method updateRecord should receive a better name.
/**
* Notify all listeners that a record was updated.
*
* @param now
* update date
* @param rec
* DNS record
* @param operation
* DNS cache operation
*/
public void updateRecord(long now, DNSRecord rec, Operation operation) {
// We do not want to block the entire DNS while we are updating the record for each listener (service info)
{
List<DNSListener> listenerList = null;
synchronized (_listeners) {
listenerList = new ArrayList<DNSListener>(_listeners);
}
for (DNSListener listener : listenerList) {
listener.updateRecord(this.getCache(), now, rec);
}
}
/**
* This is the place where we actually add & remove services.
* - For adding we need a PTR record.
* - For removing we want also to consider expired SRV records because this means the service hasn't been updated
* and is probably not reachable anymore.
*
* For details see also RFC 6762 / Section 10.4:
* @see https://tools.ietf.org/html/rfc6762#section-10.4
*/
if (
DNSRecordType.TYPE_PTR.equals(rec.getRecordType())
|| ( DNSRecordType.TYPE_SRV.equals(rec.getRecordType()) && Operation.Remove.equals(operation))
)
{
ServiceEvent event = rec.getServiceEvent(this);
if ((event.getInfo() == null) || !event.getInfo().hasData()) {
// We do not care about the subtype because the info is only used if complete and the subtype will then be included.
ServiceInfo info = this.getServiceInfoFromCache(event.getType(), event.getName(), "", false);
if (info.hasData()) {
event = new ServiceEventImpl(this, event.getType(), event.getName(), info);
}
}
List<ServiceListenerStatus> list = _serviceListeners.get(event.getType().toLowerCase());
final List<ServiceListenerStatus> serviceListenerList;
if (list != null) {
synchronized (list) {
serviceListenerList = new ArrayList<ServiceListenerStatus>(list);
}
} else {
serviceListenerList = Collections.emptyList();
}
logger.trace("{}.updating record for event: {} list {} operation: {}",
this.getName(),
event,
serviceListenerList,
operation
);
if (!serviceListenerList.isEmpty()) {
final ServiceEvent localEvent = event;
switch (operation) {
case Add:
for (final ServiceListenerStatus listener : serviceListenerList) {
if (listener.isSynchronous()) {
listener.serviceAdded(localEvent);
} else {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceAdded(localEvent);
}
});
}
}
break;
case Remove:
for (final ServiceListenerStatus listener : serviceListenerList) {
if (listener.isSynchronous()) {
listener.serviceRemoved(localEvent);
} else {
_executor.submit(new Runnable() {
/** {@inheritDoc} */
@Override
public void run() {
listener.serviceRemoved(localEvent);
}
});
}
}
break;
default:
break;
}
}
}
}
void handleRecord(DNSRecord record, long now) {
DNSRecord newRecord = record;
Operation cacheOperation = Operation.Noop;
final boolean expired = newRecord.isExpired(now);
logger.debug("{} handle response: {}", this.getName(), newRecord);
// update the cache
if (!newRecord.isServicesDiscoveryMetaQuery() && !newRecord.isDomainDiscoveryQuery()) {
final boolean unique = newRecord.isUnique();
final DNSRecord cachedRecord = (DNSRecord) this.getCache().getDNSEntry(newRecord);
logger.debug("{} handle response cached record: {}", this.getName(), cachedRecord);
// RFC 6762, section 10.2 Announcements to Flush Outdated Cache Entries
// https://tools.ietf.org/html/rfc6762#section-10.2
// if (cache-flush a.k.a unique), remove all existing records matching these criterias :--
// 1. same name
// 2. same record type
// 3. same record class
// 4. record is older than 1 second.
if (unique) {
for (DNSEntry entry : this.getCache().getDNSEntryList(newRecord.getKey())) {
if ( newRecord.getRecordType().equals(entry.getRecordType()) &&
newRecord.getRecordClass().equals(entry.getRecordClass()) &&
isOlderThanOneSecond( (DNSRecord)entry, now )
) {
logger.trace("setWillExpireSoon() on: {}", entry);
// this set ttl to 1 second,
((DNSRecord) entry).setWillExpireSoon(now);
}
}
}
if (cachedRecord != null) {
if (expired) {
// if the record has a 0 ttl that means we have a cancel record we need to delay the removal by 1s
if (newRecord.getTTL() == 0) {
cacheOperation = Operation.Noop;
logger.trace("Record is expired - setWillExpireSoon() on:\n\t{}", cachedRecord);
cachedRecord.setWillExpireSoon(now);
// the actual record will be disposed of by the record reaper.
} else {
cacheOperation = Operation.Remove;
logger.trace("Record is expired - removeDNSEntry() on:\n\t{}", cachedRecord);
this.getCache().removeDNSEntry(cachedRecord);
}
} else {
// If the record content has changed we need to inform our listeners.
if ( !newRecord.sameValue(cachedRecord) ||
(
!newRecord.sameSubtype(cachedRecord) &&
(newRecord.getSubtype().length() > 0)
)
) {
if (newRecord.isSingleValued()) {
cacheOperation = Operation.Update;
logger.trace("Record (singleValued) has changed - replaceDNSEntry() on:\n\t{}\n\t{}", newRecord, cachedRecord);
this.getCache().replaceDNSEntry(newRecord, cachedRecord);
} else {
// Address record can have more than one value on multi-homed machines
cacheOperation = Operation.Add;
logger.trace("Record (multiValue) has changed - addDNSEntry on:\n\t{}", newRecord);
this.getCache().addDNSEntry(newRecord);
}
} else {
cachedRecord.resetTTL(newRecord);
newRecord = cachedRecord;
}
}
} else {
if (!expired) {
cacheOperation = Operation.Add;
logger.trace("Record not cached - addDNSEntry on:\n\t{}", newRecord);
this.getCache().addDNSEntry(newRecord);
}
}
}
// Register new service types
if (newRecord.getRecordType() == DNSRecordType.TYPE_PTR) {
// handle DNSConstants.DNS_META_QUERY records
boolean typeAdded = false;
if (newRecord.isServicesDiscoveryMetaQuery()) {
// The service names are in the alias.
if (!expired) {
typeAdded = this.registerServiceType(((DNSRecord.Pointer) newRecord).getAlias());
}
return;
}
typeAdded |= this.registerServiceType(newRecord.getName());
if (typeAdded && (cacheOperation == Operation.Noop)) {
cacheOperation = Operation.RegisterServiceType;
}
}
// notify the listeners
if (cacheOperation != Operation.Noop) {
this.updateRecord(now, newRecord, cacheOperation);
}
}
/**
*
* @param dnsRecord
* @param timeToCompare a given times for comparison
* @return true if dnsRecord create time is older than 1 second, relative to the given time; false otherwise
*/
private boolean isOlderThanOneSecond(DNSRecord dnsRecord, long timeToCompare) {
return (dnsRecord.getCreated() < (timeToCompare - DNSConstants.FLUSH_RECORD_OLDER_THAN_1_SECOND*1000));
}
/**
* Handle an incoming response. Cache answers, and pass them on to the appropriate questions.
*
* @exception IOException
*/
void handleResponse(DNSIncoming msg) throws IOException {
final long now = System.currentTimeMillis();
boolean hostConflictDetected = false;
boolean serviceConflictDetected = false;
List<DNSRecord> allAnswers = msg.getAllAnswers();
allAnswers = aRecordsLast(allAnswers);
for (DNSRecord newRecord : allAnswers) {
this.handleRecord(newRecord, now);
if (DNSRecordType.TYPE_A.equals(newRecord.getRecordType()) || DNSRecordType.TYPE_AAAA.equals(newRecord.getRecordType())) {
hostConflictDetected |= newRecord.handleResponse(this);
} else {
serviceConflictDetected |= newRecord.handleResponse(this);
}
}
if (hostConflictDetected || serviceConflictDetected) {
this.startProber();
}
}
/**
* In case the a record is received before the srv record the ip address would not be set.
* <p>
* Wireshark record: see also file a_record_before_srv.pcapng and {@link ServiceInfoImplTest#test_ip_address_is_set()}
* <p>
* Multicast Domain Name System (response)
* Transaction ID: 0x0000
* Flags: 0x8400 Standard query response, No error
* Questions: 0
* Answer RRs: 2
* Authority RRs: 0
* Additional RRs: 8
* Answers
* _ibisip_http._tcp.local: type PTR, class IN, DeviceManagementService._ibisip_http._tcp.local
* _ibisip_http._tcp.local: type PTR, class IN, PassengerCountingService._ibisip_http._tcp.local
* Additional records
* DeviceManagementService._ibisip_http._tcp.local: type TXT, class IN, cache flush
* PassengerCountingService._ibisip_http._tcp.local: type TXT, class IN, cache flush
* DIST500_7-F07_OC030_05_03941.local: type A, class IN, cache flush, addr 192.168.88.236
* DeviceManagementService._ibisip_http._tcp.local: type SRV, class IN, cache flush, priority 0, weight 0, port 5000, target DIST500_7-F07_OC030_05_03941.local
* PassengerCountingService._ibisip_http._tcp.local: type SRV, class IN, cache flush, priority 0, weight 0, port 5001, target DIST500_7-F07_OC030_05_03941.local
* DeviceManagementService._ibisip_http._tcp.local: type NSEC, class IN, cache flush, next domain name DeviceManagementService._ibisip_http._tcp.local
* PassengerCountingService._ibisip_http._tcp.local: type NSEC, class IN, cache flush, next domain name PassengerCountingService._ibisip_http._tcp.local
* DIST500_7-F07_OC030_05_03941.local: type NSEC, class IN, cache flush, next domain name DIST500_7-F07_OC030_05_03941.local
*/
private List<DNSRecord> aRecordsLast(List<DNSRecord> allAnswers) {
ArrayList<DNSRecord> ret = new ArrayList<DNSRecord>(allAnswers.size());
ArrayList<DNSRecord> arecords = new ArrayList<DNSRecord>();
// filter all a records and move them to the end of the list
// we do not change der order of the order records
for (DNSRecord answer : allAnswers) {
if (answer.getRecordType().equals(DNSRecordType.TYPE_A) || answer.getRecordType().equals(DNSRecordType.TYPE_AAAA)) {
arecords.add(answer);
} else {
ret.add(answer);
}
}
ret.addAll(arecords);
return ret;
}
/**
* Handle an incoming query. See if we can answer any part of it given our service infos.
*
* @param in
* @param addr
* @param port
* @exception IOException
*/
void handleQuery(DNSIncoming in, InetAddress addr, int port) throws IOException {
logger.debug("{} handle query: {}", this.getName(), in);
// Track known answers
boolean conflictDetected = false;
final long expirationTime = System.currentTimeMillis() + DNSConstants.KNOWN_ANSWER_TTL;
for (DNSRecord answer : in.getAllAnswers()) {
conflictDetected |= answer.handleQuery(this, expirationTime);
}
this.ioLock();
try {
if (_plannedAnswer != null) {
_plannedAnswer.append(in);
} else {
DNSIncoming plannedAnswer = in.clone();
if (in.isTruncated()) {
_plannedAnswer = plannedAnswer;
}
this.startResponder(plannedAnswer, addr, port);
}
} finally {
this.ioUnlock();
}
final long now = System.currentTimeMillis();
for (DNSRecord answer : in.getAnswers()) {
this.handleRecord(answer, now);
}
if (conflictDetected) {
this.startProber();
}
}
public void respondToQuery(DNSIncoming in) {
this.ioLock();
try {
if (_plannedAnswer == in) {
_plannedAnswer = null;
}
} finally {
this.ioUnlock();
}
}
/**
* Add an answer to a question. Deal with the case when the outgoing packet overflows
*
* @param in
* @param addr
* @param port
* @param out
* @param rec
* @return outgoing answer
* @exception IOException
*/
public DNSOutgoing addAnswer(DNSIncoming in, InetAddress addr, int port, DNSOutgoing out, DNSRecord rec) throws IOException {
DNSOutgoing newOut = out;
if (newOut == null) {
newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload());
}
try {
newOut.addAnswer(in, rec);
} catch (final IOException e) {
newOut.setFlags(newOut.getFlags() | DNSConstants.FLAGS_TC);
newOut.setId(in.getId());
send(newOut);
newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload());
newOut.addAnswer(in, rec);
}
return newOut;
}
/**
* Send an outgoing multicast DNS message.
*
* @param out
* @exception IOException
*/
public void send(DNSOutgoing out) throws IOException {
if (!out.isEmpty()) {
final InetAddress addr;
final int port;
if (out.getDestination() != null) {
addr = out.getDestination().getAddress();
port = out.getDestination().getPort();
} else {
addr = _group;
port = DNSConstants.MDNS_PORT;
}
byte[] message = out.data();
final DatagramPacket packet = new DatagramPacket(message, message.length, addr, port);
if (logger.isTraceEnabled()) {
try {
final DNSIncoming msg = new DNSIncoming(packet);
if (logger.isTraceEnabled()) {
logger.trace("send({}) JmDNS out:{}", this.getName(), msg.print(true));
}
} catch (final IOException e) {
logger.debug(getClass().toString(), ".send(" + this.getName() + ") - JmDNS can not parse what it sends!!!", e);
}
}
final MulticastSocket ms = _socket;
if (ms != null && !ms.isClosed()) {
ms.send(packet);
}
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeTimer()
*/
@Override
public void purgeTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).purgeTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeStateTimer()
*/
@Override
public void purgeStateTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).purgeStateTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelTimer()
*/
@Override
public void cancelTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).cancelTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelStateTimer()
*/
@Override
public void cancelStateTimer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).cancelStateTimer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startProber()
*/
@Override
public void startProber() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startProber();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startAnnouncer()
*/
@Override
public void startAnnouncer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startAnnouncer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startRenewer()
*/
@Override
public void startRenewer() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startRenewer();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startCanceler()
*/
@Override
public void startCanceler() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startCanceler();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startReaper()
*/
@Override
public void startReaper() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startReaper();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceInfoResolver(javax.jmdns.impl.ServiceInfoImpl)
*/
@Override
public void startServiceInfoResolver(ServiceInfoImpl info) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startServiceInfoResolver(info);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startTypeResolver()
*/
@Override
public void startTypeResolver() {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startTypeResolver();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceResolver(java.lang.String)
*/
@Override
public void startServiceResolver(String type) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startServiceResolver(type);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startResponder(javax.jmdns.impl.DNSIncoming, int)
*/
@Override
public void startResponder(DNSIncoming in, InetAddress addr, int port) {
DNSTaskStarter.Factory.getInstance().getStarter(this.getDns()).startResponder(in, addr, port);
}
// REMIND: Why is this not an anonymous inner class?
/**
* Shutdown operations.
*/
protected class Shutdown implements Runnable {
/** {@inheritDoc} */
@Override
public void run() {
try {
_shutdown = null;
close();
} catch (Throwable exception) {
System.err.println("Error while shuting down. " + exception);
}
}
}
private final Object _recoverLock = new Object();
/**
* Recover jmDNS when there is an error.
*/
public void recover() {
logger.debug("{}.recover()", this.getName());
// We have an IO error so lets try to recover if anything happens lets close it.
// This should cover the case of the IP address changing under our feet
if (this.isClosing() || this.isClosed() || this.isCanceling() || this.isCanceled()) {
return;
}
// We need some definite lock here as we may have multiple timer running in the same thread that will not be stopped by the reentrant lock
// in the state object. This is only a problem in this case as we are going to execute in seperate thread so that the timer can clear.
synchronized (_recoverLock) {
// Stop JmDNS
// This protects against recursive calls
if (this.cancelState()) {
final String newThreadName = this.getName() + ".recover()";
logger.debug("{} thread {}", newThreadName, Thread.currentThread().getName());
Thread recover = new Thread(newThreadName) {
/**
* {@inheritDoc}
*/
@Override
public void run() {
__recover();
}
};
recover.start();
}
}
}
void __recover() {
// Synchronize only if we are not already in process to prevent dead locks
//
logger.debug("{}.recover() Cleanning up", this.getName());
logger.warn("RECOVERING");
// Purge the timer
this.purgeTimer();
// We need to keep a copy for reregistration
final Collection<ServiceInfo> oldServiceInfos = new ArrayList<ServiceInfo>(getServices().values());
// Cancel all services
this.unregisterAllServices();
this.disposeServiceCollectors();
this.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
// Purge the canceler timer
this.purgeStateTimer();
//
// close multicast socket
this.closeMulticastSocket();
//
this.getCache().clear();
logger.debug("{}.recover() All is clean", this.getName());
if (this.isCanceled()) {
//
// All is clear now start the services
//
for (ServiceInfo info : oldServiceInfos) {
((ServiceInfoImpl) info).recoverState();
}
this.recoverState();
try {
this.openMulticastSocket(this.getLocalHost());
this.start(oldServiceInfos);
} catch (final Exception exception) {
logger.warn(this.getName() + ".recover() Start services exception ", exception);
}
logger.warn("{}.recover() We are back!", this.getName());
} else {
// We have a problem. We could not clear the state.
logger.warn("{}.recover() Could not recover we are Down!", this.getName());
if (this.getDelegate() != null) {
this.getDelegate().cannotRecoverFromIOError(this.getDns(), oldServiceInfos);
}
}
}
/**
* Checks the cache of expired records and removes them.
* If any records are about to expire it tries to get them refreshed.
*
* <p>
* Implementation note:<br />
* This method is called by the {@link RecordReaper} every {@link DNSConstants#RECORD_REAPER_INTERVAL} milliseconds.
* </p>
* @see DNSRecord
* @see RecordReaper
*/
public void cleanCache() {
this.getCache().logCachedContent();
final long now = System.currentTimeMillis();
final Set<String> staleServiceTypesForRefresh = new HashSet<String>();
for (final DNSEntry entry : this.getCache().allValues()) {
try {
final DNSRecord record = (DNSRecord) entry;
if (record.isExpired(now)) {
this.updateRecord(now, record, Operation.Remove);
logger.trace("Removing DNSEntry from cache: {}", entry);
this.getCache().removeDNSEntry(record);
} else if (record.isStaleAndShouldBeRefreshed(now)) {
record.incrementRefreshPercentage();
String type = record.getServiceInfo().getType().toLowerCase();
// only query every service type once per refresh
if (staleServiceTypesForRefresh.add(type)) {
// we should query for the record we care about i.e. those in the service collectors
this.renewServiceCollector(type);
}
}
} catch (Exception exception) {
logger.warn(this.getName() + ".Error while reaping records: " + entry, exception);
logger.warn(this.toString());
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() {
if (this.isClosing()) {
return;
}
logger.debug("Cancelling JmDNS: {}", this);
// Stop JmDNS
// This protects against recursive calls
if (this.cancelState()) {
// We got the tie break now clean up
// Stop the timer
logger.debug("Canceling the timer");
this.cancelTimer();
// Cancel all services
this.unregisterAllServices();
this.disposeServiceCollectors();
logger.debug("Wait for JmDNS cancel: {}", this);
this.waitForCanceled(DNSConstants.CLOSE_TIMEOUT);
// Stop the canceler timer
logger.debug("Canceling the state timer");
this.cancelStateTimer();
// Stop the executor
_executor.shutdown();
// close socket
this.closeMulticastSocket();
// remove the shutdown hook
if (_shutdown != null) {
Runtime.getRuntime().removeShutdownHook(_shutdown);
}
// earlier we did a DNSTaskStarter.Factory.getInstance().getStarter(this.getDns())
// now we must release the resources associated with the starter for this JmDNS instance
DNSTaskStarter.Factory.getInstance().disposeStarter(this.getDns());
logger.debug("JmDNS closed.");
}
advanceState(null);
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public void printServices() {
System.err.println(toString());
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(2048);
sb.append("\n");
sb.append("\t---- Local Host -----");
sb.append("\n\t");
sb.append(_localHost);
sb.append("\n\t---- Services -----");
for (final Map.Entry<String, ServiceInfo> entry : _services.entrySet()) {
sb.append("\n\t\tService: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\n");
sb.append("\t---- Types ----");
for (final ServiceTypeEntry subtypes : _serviceTypes.values()) {
sb.append("\n\t\tType: ");
sb.append(subtypes.getType());
sb.append(": ");
sb.append(subtypes.isEmpty() ? "no subtypes" : subtypes);
}
sb.append("\n");
sb.append(_cache.toString());
sb.append("\n");
sb.append("\t---- Service Collectors ----");
for (final Map.Entry<String, ServiceCollector> entry : _serviceCollectors.entrySet()) {
sb.append("\n\t\tService Collector: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
sb.append("\n");
sb.append("\t---- Service Listeners ----");
for (final Map.Entry<String, List<ListenerStatus.ServiceListenerStatus>> entry : _serviceListeners.entrySet()) {
sb.append("\n\t\tService Listener: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo[] list(String type) {
return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public ServiceInfo[] list(String type, long timeout) {
this.cleanCache();
// Implementation note: The first time a list for a given type is
// requested, a ServiceCollector is created which collects service
// infos. This greatly speeds up the performance of subsequent calls
// to this method. The caveats are, that 1) the first call to this
// method for a given type is slow, and 2) we spawn a ServiceCollector
// instance for each service type which increases network traffic a
// little.
String loType = type.toLowerCase();
boolean newCollectorCreated = false;
if (this.isCanceling() || this.isCanceled()) {
return new ServiceInfo[0];
}
ServiceCollector collector = _serviceCollectors.get(loType);
if (collector == null) {
newCollectorCreated = _serviceCollectors.putIfAbsent(loType, new ServiceCollector(type)) == null;
collector = _serviceCollectors.get(loType);
if (newCollectorCreated) {
this.addServiceListener(type, collector, ListenerStatus.SYNCHRONOUS);
}
}
logger.debug("{}-collector: {}", this.getName(), collector);
// At this stage the collector should never be null but it keeps findbugs happy.
return (collector != null ? collector.list(timeout) : new ServiceInfo[0]);
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(String type) {
return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(String type, long timeout) {
Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5);
for (ServiceInfo info : this.list(type, timeout)) {
String subtype = info.getSubtype().toLowerCase();
if (!map.containsKey(subtype)) {
map.put(subtype, new ArrayList<ServiceInfo>(10));
}
map.get(subtype).add(info);
}
Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size());
for (final Map.Entry<String, List<ServiceInfo>> entry : map.entrySet()) {
final String subtype = entry.getKey();
final List<ServiceInfo> infoForSubType = entry.getValue();
result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()]));
}
return result;
}
/**
* This method disposes all ServiceCollector instances which have been created by calls to method <code>list(type)</code>.
*
* @see #list
*/
private void disposeServiceCollectors() {
logger.debug("disposeServiceCollectors()");
for (final Map.Entry<String, ServiceCollector> entry : _serviceCollectors.entrySet()) {
final ServiceCollector collector = entry.getValue();
if (collector != null) {
final String type = entry.getKey();
this.removeServiceListener(type, collector);
_serviceCollectors.remove(type, collector);
}
}
}
/**
* Instances of ServiceCollector are used internally to speed up the performance of method <code>list(type)</code>.
*
* @see #list
*/
private static class ServiceCollector implements ServiceListener {
// private static Logger logger = LoggerFactory.getLogger(ServiceCollector.class.getName());
/**
* A set of collected service instance names.
*/
private final ConcurrentMap<String, ServiceInfo> _infos;
/**
* A set of collected service event waiting to be resolved.
*/
private final ConcurrentMap<String, ServiceEvent> _events;
/**
* This is the type we are listening for (only used for debugging).
*/
private final String _type;
/**
* This is used to force a wait on the first invocation of list.
*/
private volatile boolean _needToWaitForInfos;
public ServiceCollector(String type) {
super();
_infos = new ConcurrentHashMap<String, ServiceInfo>();
_events = new ConcurrentHashMap<String, ServiceEvent>();
_type = type;
_needToWaitForInfos = true;
}
/**
* A service has been added.
*
* @param event
* service event
*/
@Override
public void serviceAdded(ServiceEvent event) {
synchronized (this) {
ServiceInfo info = event.getInfo();
if ((info != null) && (info.hasData())) {
_infos.put(event.getName(), info);
} else {
String subtype = (info != null ? info.getSubtype() : "");
info = ((JmDNSImpl) event.getDNS()).resolveServiceInfo(event.getType(), event.getName(), subtype, true);
if (info != null) {
_infos.put(event.getName(), info);
} else {
_events.put(event.getName(), event);
}
}
}
}
/**
* A service has been removed.
*
* @param event
* service event
*/
@Override
public void serviceRemoved(ServiceEvent event) {
synchronized (this) {
_infos.remove(event.getName());
_events.remove(event.getName());
}
}
/**
* A service has been resolved. Its details are now available in the ServiceInfo record.
*
* @param event
* service event
*/
@Override
public void serviceResolved(ServiceEvent event) {
synchronized (this) {
_infos.put(event.getName(), event.getInfo());
_events.remove(event.getName());
}
}
/**
* Returns an array of all service infos which have been collected by this ServiceCollector.
*
* @param timeout
* timeout if the info list is empty.
* @return Service Info array
*/
public ServiceInfo[] list(long timeout) {
if (_infos.isEmpty() || !_events.isEmpty() || _needToWaitForInfos) {
long loops = (timeout / 200L);
if (loops < 1) {
loops = 1;
}
for (int i = 0; i < loops; i++) {
try {
Thread.sleep(200);
} catch (final InterruptedException e) {
/* Stub */
}
if (_events.isEmpty() && !_infos.isEmpty() && !_needToWaitForInfos) {
break;
}
}
}
_needToWaitForInfos = false;
return _infos.values().toArray(new ServiceInfo[_infos.size()]);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("\n\tType: ");
sb.append(_type);
if (_infos.isEmpty()) {
sb.append("\n\tNo services collected.");
} else {
sb.append("\n\tServices");
for (final Map.Entry<String, ServiceInfo> entry : _infos.entrySet()) {
sb.append("\n\t\tService: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
}
if (_events.isEmpty()) {
sb.append("\n\tNo event queued.");
} else {
sb.append("\n\tEvents");
for (final Map.Entry<String, ServiceEvent> entry : _events.entrySet()) {
sb.append("\n\t\tEvent: ");
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
}
return sb.toString();
}
}
static String toUnqualifiedName(String type, String qualifiedName) {
String loType = type.toLowerCase();
String loQualifiedName = qualifiedName.toLowerCase();
if (loQualifiedName.endsWith(loType) && !(loQualifiedName.equals(loType))) {
return qualifiedName.substring(0, qualifiedName.length() - type.length() - 1);
}
return qualifiedName;
}
public Map<String, ServiceInfo> getServices() {
return _services;
}
public void setLastThrottleIncrement(long lastThrottleIncrement) {
this._lastThrottleIncrement = lastThrottleIncrement;
}
public long getLastThrottleIncrement() {
return _lastThrottleIncrement;
}
public void setThrottle(int throttle) {
this._throttle = throttle;
}
public int getThrottle() {
return _throttle;
}
public static Random getRandom() {
return _random;
}
public void ioLock() {
_ioLock.lock();
}
public void ioUnlock() {
_ioLock.unlock();
}
public void setPlannedAnswer(DNSIncoming plannedAnswer) {
this._plannedAnswer = plannedAnswer;
}
public DNSIncoming getPlannedAnswer() {
return _plannedAnswer;
}
void setLocalHost(HostInfo localHost) {
this._localHost = localHost;
}
public Map<String, ServiceTypeEntry> getServiceTypes() {
return _serviceTypes;
}
public MulticastSocket getSocket() {
return _socket;
}
public InetAddress getGroup() {
return _group;
}
@Override
public Delegate getDelegate() {
return this._delegate;
}
@Override
public Delegate setDelegate(Delegate delegate) {
Delegate previous = this._delegate;
this._delegate = delegate;
return previous;
}
}
|
Remove waits. Fixes #144 (#174)
Signed-off-by: Christian Schneider <b313e144657bb32e81e0f7b7f1fed2ff9252d6a8@adobe.com>
|
src/main/java/javax/jmdns/impl/JmDNSImpl.java
|
Remove waits. Fixes #144 (#174)
|
|
Java
|
apache-2.0
|
6d279cd2f35b0995addb172c72cd59db6a84b25f
| 0
|
CenterForOpenScience/cas-overlay,CenterForOpenScience/cas-overlay
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.cos.cas.web.flow;
import com.google.gson.Gson;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Open Science Framework Login Handler.
*
* @author Longze Chen
* @since 4.1.5
*/
public class OpenScienceFrameworkLoginHandler {
/**
* Open Science Framework Login Context.
*
* @author Longze chen
* @since 4.1.5
*/
public static final class OpenScienceFrameworkLoginContext {
/** The service URL in the context. */
private String serviceUrl;
/** The simple name of the authentication exception that just happened. */
private String handleErrorName;
/** The flag for institution login instead of normal OSF login. */
private boolean institutionLogin;
/** The flag for redirect to ORCiD login instead of normal OSF login. */
private boolean orcidRedirect;
/**
* Construct an instance with the service URL, the institution login and ORCiD redirect flags.
*
* @param serviceUrl the service URL
* @param institutionLogin the flag for institution login
* @param orcidRedirect the flag for ORCiD redirect
*/
private OpenScienceFrameworkLoginContext(
final String serviceUrl,
final boolean institutionLogin,
final boolean orcidRedirect
) {
this.serviceUrl = serviceUrl;
this.handleErrorName = null;
this.institutionLogin = institutionLogin;
this.orcidRedirect = orcidRedirect;
}
// Must be public to be accessible in the JSP page
public String getServiceUrl() {
return serviceUrl;
}
void setServiceUrl(final String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public String getHandleErrorName() {
return handleErrorName;
}
public void setHandleErrorName(final String handleErrorName) {
this.handleErrorName =handleErrorName;
}
// Must be public to be accessible in the JSP page
public boolean isInstitutionLogin() {
return institutionLogin;
}
void setInstitutionLogin(final boolean institutionLogin) {
this.institutionLogin = institutionLogin;
}
boolean isOrcidRedirect() {
return orcidRedirect;
}
void setOrcidRedirect(final boolean orcidRedirect) {
this.orcidRedirect = orcidRedirect;
}
/**
* Check if the service URL exists. Must be public to be accessible in the JSP page.
*
* @return true if service url exists, false otherwise
*/
public boolean isServiceUrl() {
return serviceUrl != null;
}
/**
* Convert the class instance to a JSON string, which will be passed to the flow context.
*
* @return JSON string
*/
public String toJson() {
final Gson gson = new Gson();
return gson.toJson(this);
}
/**
* Convert the JSON string to a class instance.
*
* @param jsonString a JSON string previously generated by the method .toJson()
* @return an reconstructed instance of OpenScienceFrameworkLoginContext
*/
public static OpenScienceFrameworkLoginContext fromJson(final String jsonString) {
final Gson gson = new Gson();
return gson.fromJson(jsonString, OpenScienceFrameworkLoginContext.class);
}
}
/**
* Prepare for the login request and make decisions for next steps.
*
* @param context the request context
* @return the next event to go to
*/
public Event beforeLogin(final RequestContext context) {
final OpenScienceFrameworkLoginContext osfLoginContext;
final String serviceUrl = getEncodedServiceUrl(context);
final boolean institutionLogin = isInstitutionLogin(context);
final boolean orcidRedirect = isOrcidRedirect(context);
String jsonLoginContext = (String) context.getFlowScope().get("jsonLoginContext");
if (jsonLoginContext == null) {
// Create a new login context with service URL, institution login and ORCiD redirect flags
osfLoginContext = new OpenScienceFrameworkLoginContext(serviceUrl, institutionLogin, orcidRedirect);
} else {
// If the login context already exists, update the service URL and the institution login flag while keeping
// the errors and disabling ORCiD login redirect
osfLoginContext = OpenScienceFrameworkLoginContext.fromJson(jsonLoginContext);
osfLoginContext.setServiceUrl(serviceUrl);
osfLoginContext.setInstitutionLogin(institutionLogin);
// Only allow ORCiD login redirect from a brand new login flow
osfLoginContext.setOrcidRedirect(false);
}
jsonLoginContext = osfLoginContext.toJson();
context.getFlowScope().put("jsonLoginContext", jsonLoginContext);
// Go to the institution login page. Note: the institution login flag rules over the ORCiD redirect flag
if (osfLoginContext.isInstitutionLogin()) {
return new Event(this, "institutionLogin");
}
// Go to the dedicated redirect view for ORCiD login
if (osfLoginContext.isOrcidRedirect()) {
return new Event(this, "orcidLoginRedirect");
}
// Go to the default username/ password login page
return new Event(this, "osfDefaultLogin");
}
/**
* Check if the request is institution login.
*
* @param context the request context
* @return true if `campaign=institution` is present in the request parameters
*/
private boolean isInstitutionLogin(final RequestContext context) {
final String campaign = context.getRequestParameters().get("campaign");
return campaign != null && "institution".equals(campaign.toLowerCase());
}
/**
* Check if the request is ORCiD login redirect.
*
* @param context the request context
* @return true if `redirectOrcid=true` is present in the request parameters
*/
private boolean isOrcidRedirect(final RequestContext context) {
final String orcidRedirect = context.getRequestParameters().get("redirectOrcid");
return orcidRedirect != null && "true".equals(orcidRedirect.toLowerCase());
}
/**
* Obtain the service URL in the request parameters.
*
* The service URL from the request context is decoded (one level from what is originally in the request URL). Must
* encode it before sending it to the page via the login context. If the service URL doesn't exist, return `null`.
*
* @param context the request context
* @return the encoded service url
* @throws AssertionError if encoding fails
*/
private String getEncodedServiceUrl(final RequestContext context) throws AssertionError {
final String serviceUrl = context.getRequestParameters().get("service");
if (serviceUrl == null || serviceUrl.isEmpty()) {
return null;
}
try {
return URLEncoder.encode(serviceUrl, "UTF-8");
} catch (final UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
}
}
|
cas-server-support-osf/src/main/java/io/cos/cas/web/flow/OpenScienceFrameworkLoginHandler.java
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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 the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.cos.cas.web.flow;
import com.google.gson.Gson;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Open Science Framework Login Handler.
*
* @author Longze Chen
* @since 4.1.5
*/
public class OpenScienceFrameworkLoginHandler {
/**
* Open Science Framework Login Context.
*
* @author Longze chen
* @since 4.1.5
*/
public static final class OpenScienceFrameworkLoginContext {
/** The service URL in the context. */
private String serviceUrl;
/** The simple name of the authentication exception that just happened. */
private String handleErrorName;
/** The flag for institution login instead of normal OSF login. */
private boolean institutionLogin;
/** The flag for redirect to ORCiD login instead of normal OSF login. */
private boolean orcidRedirect;
/**
* Construct an instance of `OpenScienceFrameworkLoginContext` with the given settings.
*
* @param serviceUrl the service URL
* @param institutionLogin the flag for institution login
*/
private OpenScienceFrameworkLoginContext(final String serviceUrl, final boolean institutionLogin) {
this.serviceUrl = serviceUrl;
this.handleErrorName = null;
this.institutionLogin = institutionLogin;
}
// Must be public to be accessible in the JSP page
public String getServiceUrl() {
return serviceUrl;
}
void setServiceUrl(final String serviceUrl) {
this.serviceUrl = serviceUrl;
}
public String getHandleErrorName() {
return handleErrorName;
}
public void setHandleErrorName(final String handleErrorName) {
this.handleErrorName =handleErrorName;
}
// Must be public to be accessible in the JSP page
public boolean isInstitutionLogin() {
return institutionLogin;
}
void setInstitutionLogin(final boolean institutionLogin) {
this.institutionLogin = institutionLogin;
}
boolean isOrcidRedirect() {
return orcidRedirect;
}
void setOrcidRedirect(final boolean orcidRedirect) {
this.orcidRedirect = orcidRedirect;
}
/**
* Check if the service URL exists. Must be public to be accessible in the JSP page.
*
* @return true if service url exists, false otherwise
*/
public boolean isServiceUrl() {
return serviceUrl != null;
}
/**
* Convert the class instance to a JSON string, which will be passed to the flow context.
*
* @return JSON string
*/
public String toJson() {
final Gson gson = new Gson();
return gson.toJson(this);
}
/**
* Convert the JSON string to a class instance.
*
* @param jsonString a JSON string previously generated by the method .toJson()
* @return an reconstructed instance of OpenScienceFrameworkLoginContext
*/
public static OpenScienceFrameworkLoginContext fromJson(final String jsonString) {
final Gson gson = new Gson();
return gson.fromJson(jsonString, OpenScienceFrameworkLoginContext.class);
}
}
/**
* Prepare for the login request and make decisions for next steps.
*
* @param context the request context
* @return the next event to go to
*/
public Event beforeLogin(final RequestContext context) {
final OpenScienceFrameworkLoginContext osfLoginContext;
final String serviceUrl = getEncodedServiceUrl(context);
final boolean institutionLogin = isInstitutionLogin(context);
final boolean orcidRedirect = isOrcidRedirect(context);
String jsonLoginContext = (String) context.getFlowScope().get("jsonLoginContext");
if (jsonLoginContext == null) {
// Create a new login context with service URL and institution login flag
osfLoginContext = new OpenScienceFrameworkLoginContext(serviceUrl, institutionLogin);
// Only allow ORCiD login redirect from a brand new login flow
osfLoginContext.setOrcidRedirect(orcidRedirect);
} else {
// If the login context already exists, update the service URL and the institution login flag while keeping
// the errors and disabling ORCiD login redirect
osfLoginContext = OpenScienceFrameworkLoginContext.fromJson(jsonLoginContext);
osfLoginContext.setServiceUrl(serviceUrl);
osfLoginContext.setInstitutionLogin(institutionLogin);
osfLoginContext.setOrcidRedirect(false);
}
jsonLoginContext = osfLoginContext.toJson();
context.getFlowScope().put("jsonLoginContext", jsonLoginContext);
if (osfLoginContext.isInstitutionLogin()) {
return new Event(this, "institutionLogin");
} else if (osfLoginContext.isOrcidRedirect()) {
return new Event(this, "orcidLoginRedirect");
} else {
return new Event(this, "osfDefaultLogin");
}
}
/**
* Check if the request is institution login.
*
* @param context the request context
* @return true if `campaign=institution` is present in the request parameters
*/
private boolean isInstitutionLogin(final RequestContext context) {
final String campaign = context.getRequestParameters().get("campaign");
return campaign != null && "institution".equals(campaign.toLowerCase());
}
/**
* Check if the request is ORCiD login redirect.
*
* @param context the request context
* @return true if `redirectOrcid=true` is present in the request parameters
*/
private boolean isOrcidRedirect(final RequestContext context) {
final String orcidRedirect = context.getRequestParameters().get("redirectOrcid");
return orcidRedirect != null && "true".equals(orcidRedirect.toLowerCase());
}
/**
* Obtain the service URL in the request parameters.
*
* The service URL from the request context is decoded (one level from what is originally in the request URL). Must
* encode it before sending it to the page via the login context. If the service URL doesn't exist, return `null`.
*
* @param context the request context
* @return the encoded service url
* @throws AssertionError if encoding fails
*/
private String getEncodedServiceUrl(final RequestContext context) throws AssertionError {
final String serviceUrl = context.getRequestParameters().get("service");
if (serviceUrl == null || serviceUrl.isEmpty()) {
return null;
}
try {
return URLEncoder.encode(serviceUrl, "UTF-8");
} catch (final UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
}
}
|
Update the login context's constructor and the "beforeLogin" event
|
cas-server-support-osf/src/main/java/io/cos/cas/web/flow/OpenScienceFrameworkLoginHandler.java
|
Update the login context's constructor and the "beforeLogin" event
|
|
Java
|
apache-2.0
|
6768d72bd5a386d9daba9b2968c88c1ecb9121f0
| 0
|
InformaticsMatters/squonk,InformaticsMatters/squonk,InformaticsMatters/squonk,InformaticsMatters/squonk
|
package org.squonk.camel.processor;
import groovy.lang.GroovyClassLoader;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.TypeConverter;
import org.squonk.dataset.Dataset;
import org.squonk.dataset.DatasetMetadata;
import org.squonk.dataset.transform.*;
import org.squonk.types.BasicObject;
import org.squonk.types.MoleculeObject;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
* Processor that handles transforming values of{@link BasicObject}s. Follows
* the fluent builder pattern.
*
* @author timbo
*/
public class ValueTransformerProcessor implements Processor {
private static final Logger LOG = Logger.getLogger(ValueTransformerProcessor.class.getName());
private static final String SOURCE = "Squonk assignment potion";
private int classCount = 0;
private final List<Conversion> conversions = new ArrayList<>();
private GroovyClassLoader groovyClassLoader;
private String errorFieldName = "TransformErrors";
private boolean hasErrorField = false;
private GroovyClassLoader getGroovyClassLoader() {
if (groovyClassLoader == null) {
groovyClassLoader = new GroovyClassLoader();
}
return groovyClassLoader;
}
@Override
public void process(Exchange exch) throws Exception {
TypeConverter typeConverter = exch.getContext().getTypeConverter();
Dataset ds = exch.getIn().getBody(Dataset.class);
Dataset neu = execute(typeConverter, ds);
exch.getIn().setBody(neu);
}
/**
* Add operations to perform the conversions, updating the dataset with the
* transformed stream, and adding appropriate field metadata. NOTE: this does NOT perform a terminal operation on
* the stream, so after calling this method the values are not yet transformed. The resulting stream must be processed
* by performing a terminal operation.
*
* @param typeConverter
* @param dataset
* @throws IOException
*/
public Dataset<? extends BasicObject> execute(TypeConverter typeConverter, Dataset<BasicObject> dataset) throws IOException {
DatasetMetadata oldMeta = dataset.getMetadata();
if (oldMeta != null) {
hasErrorField = oldMeta.getValueClassMappings().containsKey(errorFieldName);
}
Stream<BasicObject> stream = addConversions(typeConverter, dataset);
Class type = dataset.getType();
for (Conversion conversion : conversions) {
type = conversion.getObjectType(type);
}
DatasetMetadata newMeta = new DatasetMetadata(type, null, oldMeta == null ? null : oldMeta.getFieldMetaProps(), -1, oldMeta == null ? null : oldMeta.getProperties());
Dataset newData = new Dataset(type, stream, newMeta);
return newData;
}
public Stream<BasicObject> addConversions(TypeConverter typeConverter, Dataset<BasicObject> dataset) throws IOException {
Stream<BasicObject> stream = dataset.getStream();
DatasetMetadata meta = dataset.getMetadata();
for (Conversion conversion : conversions) {
LOG.info("Handling conversion: " + conversion);
stream = conversion.execute(typeConverter, stream);
if (meta!= null) {
conversion.updateMetadata(meta);
}
}
if (!hasErrorField && meta != null) {
meta.createField(errorFieldName, "Squonk potion", "Errors from data transforms", String.class);
}
return stream;
}
public static ValueTransformerProcessor create(TransformDefinitions txdefs) {
ValueTransformerProcessor vtp = new ValueTransformerProcessor();
for (AbstractTransform tx : txdefs.getTransforms()) {
if (tx instanceof DeleteRowTransform) {
DeleteRowTransform df = (DeleteRowTransform) tx;
vtp.deleteRow(df.getCondition());
} else if (tx instanceof DeleteFieldTransform) {
DeleteFieldTransform df = (DeleteFieldTransform) tx;
vtp.deleteValue(df.getFieldName(), df.getCondition());
} else if (tx instanceof RenameFieldTransform) {
RenameFieldTransform rf = (RenameFieldTransform) tx;
vtp.convertValueName(rf.getFieldName(), rf.getNewName());
} else if (tx instanceof ConvertFieldTransform) {
ConvertFieldTransform cf = (ConvertFieldTransform) tx;
vtp.convertValueType(cf.getFieldName(), cf.getNewType(), cf.getGenericType(), cf.getOnError());
} else if (tx instanceof ReplaceValueTransform) {
ReplaceValueTransform cf = (ReplaceValueTransform) tx;
vtp.replaceValue(cf.getFieldName(), cf.getMatch(), cf.getResult());
} else if (tx instanceof ConvertToMoleculeTransform) {
ConvertToMoleculeTransform cf = (ConvertToMoleculeTransform) tx;
vtp.convertToMolecule(cf.getStructureFieldName(), cf.getStructureFormat());
} else if (tx instanceof AssignValueTransform) {
AssignValueTransform cf = (AssignValueTransform) tx;
vtp.assignValue(cf.getFieldName(), cf.getExpression(), cf.getCondition(), cf.getOnError());
}
}
return vtp;
}
public ValueTransformerProcessor replaceValue(String fldName, Object match, Object result) {
conversions.add(new ReplaceValueConversion(fldName, match, result));
return this;
}
public ValueTransformerProcessor assignValue(String fldName, String expression, String condition, String onError) {
conversions.add(new AssignConversion(fldName, expression, condition, onError));
return this;
}
public ValueTransformerProcessor convertValueType(String fldName, Class newClass) {
return convertValueType(fldName, newClass, null, null);
}
public ValueTransformerProcessor convertValueType(String fldName, Class newClass, Class genericType, String onError) {
if (genericType != null) {
// check that its got the right constructor to save nasty exceptions later
try {
Constructor c = newClass.getConstructor(Object.class, Class.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Illegal conversion. Must have constructor that takes Object, Class");
}
}
conversions.add(new TypeConversion(fldName, newClass, genericType, onError));
return this;
}
public ValueTransformerProcessor convertValueName(String oldName, String newName) {
conversions.add(new RenameFieldConversion(oldName, newName));
return this;
}
public ValueTransformerProcessor deleteValue(String name, String condition) {
conversions.add(new DeleteFieldConversion(name, condition));
return this;
}
public ValueTransformerProcessor deleteRow(String condition) {
conversions.add(new DeleteRowConversion(condition));
return this;
}
public ValueTransformerProcessor convertToMolecule(String structureField, String sturctureFormat) {
conversions.add(new ConvertToMoleculeConversion(structureField, sturctureFormat));
return this;
}
private abstract class Conversion {
abstract Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream);
abstract void updateMetadata(DatasetMetadata meta);
Class getObjectType(Class input) {
return input;
}
}
class ReplaceValueConversion extends Conversion {
final String fldName;
final Object match;
final Object result;
ReplaceValueConversion(String fldName, Object match, Object result) {
this.fldName = fldName;
this.match = match;
this.result = result;
}
void updateMetadata(DatasetMetadata meta) {
meta.appendFieldHistory(fldName, "Value conversion: " +
(match == null ? "null" : match.toString()) + " -> " +
(result == null ? "null" : result.toString()));
}
@Override
Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object old = o.getValue(fldName);
if (old == null) {
if (match == null) {
// null matches null
o.putValue(fldName, result);
}
} else {
if (old.equals(match)) {
// old matches match
o.putValue(fldName, result);
}
}
});
}
@Override
public String toString() {
return "ReplaceValueConversion [fldName:" + fldName + " match: " + match + " result: " + result + "]";
}
}
class TypeConversion extends Conversion {
final String fldName;
final Class newClass;
final Class genericClass;
final String onError;
TypeConversion(String fldName, Class newClass, Class genericClass, String onError) {
validateOnError(onError);
this.fldName = fldName;
this.newClass = newClass;
this.genericClass = genericClass;
this.onError = onError;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (genericClass == null) {
meta.appendFieldHistory(fldName, "Type converted to " + newClass.getName());
} else {
meta.appendFieldHistory(fldName, "Type converted to " + newClass.getName() + "<" + genericClass.getName() + ">");
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object old = o.getValue(fldName);
if (old != null) {
try {
Object neu = null;
if (genericClass != null) {
neu = genericCreate(old, newClass, genericClass);
} else {
neu = converter.convertTo(newClass, old);
}
o.putValue(fldName, neu);
} catch (Exception e) {
if (onError == null || "fail".equals(onError)) {
throw e;
} else if ("continue".equals(onError)) {
o.getValues().remove(fldName);
String current = o.getValue(errorFieldName, String.class);
String msg = "Failed to convert " + old + " for field " + fldName + " to " + newClass.getSimpleName();
if (current == null) {
o.putValue(errorFieldName, msg);
} else {
o.putValue(errorFieldName, current + "\n" + msg);
}
}
}
}
});
}
private Object genericCreate(Object value, Class type, Class genericType) {
try {
Constructor c = type.getConstructor(Object.class, Class.class);
return c.newInstance(value, genericType);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Failed to instantiate value", e);
}
}
@Override
public String toString() {
return "TypeConversion [fldName:" + fldName + " newClass: " + newClass + " genericClass: " + genericClass + " onError: " + onError + "]";
}
}
class RenameFieldConversion extends Conversion {
final String oldName;
final String newName;
RenameFieldConversion(String oldName, String newName) {
this.oldName = oldName;
this.newName = newName;
}
@Override
void updateMetadata(DatasetMetadata meta) {
// transfer the old
Map<String, DatasetMetadata.PropertiesHolder> phs = meta.getFieldMetaPropsMap();
DatasetMetadata.PropertiesHolder ph = phs.get(oldName);
if (ph != null) {
for (Map.Entry<String, Object> e : ph.getValues().entrySet()) {
meta.putFieldMetaProp(newName, e.getKey(), e.getValue());
}
}
// add rename event to history
meta.appendFieldHistory(newName, "Renamed from " + oldName + " to " + newName);
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object value = o.getValue(oldName);
if (value != null) {
o.putValue(newName, value);
o.getValues().remove(oldName);
}
});
}
@Override
public String toString() {
return "RenameFieldConversion [oldName:" + oldName + " newName: " + newName + "]";
}
}
class DeleteFieldConversion extends Conversion {
final String fldName, condition;
DeleteFieldConversion(String fldName, String condition) {
this.fldName = fldName;
this.condition = condition;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (condition != null) {
meta.appendFieldHistory(fldName, "Deleted values matching condition: " + condition);
} else {
meta.appendDatasetHistory("Deleted field " + fldName);
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
if (condition == null) {
return stream.peek((o) -> {
o.getValues().remove(fldName);
});
} else {
try {
final Predicate predicate = createPredicteClass(condition);
return stream.peek((o) -> {
if (predicate.test(o)) {
o.getValues().remove(fldName);
}
});
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create filter", e);
}
}
}
@Override
public String toString() {
return "DeleteFieldConversion [fldName:" + fldName + " condition: " + condition + "]";
}
}
class AssignConversion extends Conversion {
final String fldName;
final String expression;
final String condition;
final String onError;
AssignConversion(String fldName, String expression, String condition, String onError) {
validateOnError(onError);
this.fldName = fldName;
this.expression = expression;
this.condition = condition;
this.onError = onError;
}
@Override
void updateMetadata(DatasetMetadata meta) {
String expr = formatExpression();
if (meta.getValueClassMappings().get(fldName) == null) {
// new field
meta.createField(fldName, SOURCE, "Assignment: " + expr, null);
} else {
meta.putFieldMetaProp(fldName, DatasetMetadata.PROP_SOURCE, SOURCE);
meta.appendFieldProperty(fldName, DatasetMetadata.PROP_DESCRIPTION, "Re-assigned: " + expr);
}
meta.appendFieldHistory(fldName, "Assignment: " + expr);
}
private String formatExpression() {
if (condition == null) {
return expression;
} else {
return expression + " IF " + condition;
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
Consumer c;
try {
c = createConsumer();
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create consumer", e);
}
return stream.peek(c);
}
private Consumer createConsumer() throws IllegalAccessException, InstantiationException {
String clsDef = createConsumerClassDefinition();
LOG.info("Built Consumer class:\n" + clsDef);
Class<Consumer> cls = getGroovyClassLoader().parseClass(clsDef);
Consumer consumer = cls.newInstance();
return consumer;
}
private String createConsumerClassDefinition() {
StringBuilder b1 = new StringBuilder();
b1.append("import static java.lang.Math.*\n")
.append("class MyConsumer").append(++classCount).append(" implements java.util.function.Consumer {\n")
.append(" void accept(def o) {\n")
.append(" o.values.with { ");
if (condition != null) {
b1.append("if ( ").append(condition).append(" ) { ");
}
StringBuilder b2 = new StringBuilder();
b2.append(fldName).append(" = ").append(expression);
if ("continue".equals(onError)) {
b1.append(wrapErrorHandler(b2.toString(), "Failed to evaluate field " + fldName));
} else if (onError == null || "fail".equals(onError)) {
b1.append(b2.toString());
}
if (condition != null) {
b1.append("\n }");
}
b1.append("\n }\n }\n}");
return b1.toString();
}
@Override
public String toString() {
return "AssignConversion [fldName:" + fldName + " expression: " + expression + " condition: " + condition + " orError: " + onError + "]";
}
}
class ConvertToMoleculeConversion extends Conversion {
final String field, format;
ConvertToMoleculeConversion(String structureField, String structureFormat) {
this.field = structureField;
this.format = structureFormat;
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
if (field == null) {
throw new NullPointerException("Field containing structure must be specified");
}
if (format == null) {
throw new NullPointerException("Structure format must be specified");
}
return stream.map((o) -> {
Object mol = o.getValue(field);
MoleculeObject mo = new MoleculeObject(o.getUUID(), mol == null ? null : mol.toString(), format, o.getValues());
mo.getValues().remove(field);
return mo;
});
}
@Override
void updateMetadata(DatasetMetadata meta) {
meta.appendDatasetHistory("Converted to molecules using field " + field + " and format " + format);
}
@Override
Class getObjectType(Class input) {
return MoleculeObject.class;
}
@Override
public String toString() {
return "ConvertToMoleculeConversion [field:" + field + " format: " + format + "]";
}
}
class DeleteRowConversion extends Conversion {
final String condition;
DeleteRowConversion(String condition) {
this.condition = condition;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (condition != null) {
meta.appendDatasetHistory("Deleted rows where: " + condition);
} else {
meta.appendDatasetHistory("Deleted all rows");
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
Predicate p;
try {
p = createPredicate();
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create filter", e);
}
return stream.filter(p);
}
private Predicate createPredicate() throws IllegalAccessException, InstantiationException {
if (condition == null) {
return o -> false;
} else {
Predicate predicate = createPredicteClass("!(" + condition + ")");
return predicate;
}
}
@Override
public String toString() {
return "DeleteRowConversion [condition:" + condition + "]";
}
}
private Predicate createPredicteClass(String condition)
throws IllegalAccessException, InstantiationException {
String clsdef = createPredicateClassDefinition(condition);
LOG.info("Predicate class: \n" + clsdef);
Class<Predicate> cls = getGroovyClassLoader().parseClass(clsdef);
Predicate predicate = cls.newInstance();
return predicate;
}
private String createPredicateClassDefinition(String condition) {
StringBuilder b = new StringBuilder()
.append("import static java.lang.Math.*\n")
.append("class MyPredicate").append(++classCount).append(" implements java.util.function.Predicate {\n")
.append(" boolean test(def o) {\n")
.append(" o.values.with { ")
.append(condition)
.append(" }\n }\n}");
return b.toString();
}
private String wrapErrorHandler(String expr, String message) {
StringBuilder b = new StringBuilder("\n try { ")
.append(expr)
.append(" } catch (Exception e) { \n")
.append(errorFieldName)
.append(" = ( ")
.append(errorFieldName)
.append(" == null ? '")
.append(message)
.append(". ' + e.class.simpleName + '[' + e.message")
.append("+ ']' : ")
.append(errorFieldName).append(" + '\\n' + '").append(message)
.append(". ' + e.class.simpleName + '[' + e.message")
.append(" + ']' )\n}");
return b.toString();
}
/**
* @param onError
* @throws IllegalArgumentException if not fail or continue
*/
void validateOnError(String onError) {
if (onError != null) {
if ("fail".equals(onError) || "continue".equals(onError)) {
return;
}
throw new IllegalArgumentException("Bad onError value: " + onError);
}
}
}
|
components/common-camel/src/main/java/org/squonk/camel/processor/ValueTransformerProcessor.java
|
package org.squonk.camel.processor;
import groovy.lang.GroovyClassLoader;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.TypeConverter;
import org.squonk.dataset.Dataset;
import org.squonk.dataset.DatasetMetadata;
import org.squonk.dataset.transform.*;
import org.squonk.types.BasicObject;
import org.squonk.types.MoleculeObject;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
* Processor that handles transforming values of{@link BasicObject}s. Follows
* the fluent builder pattern.
*
* @author timbo
*/
public class ValueTransformerProcessor implements Processor {
private static final Logger LOG = Logger.getLogger(ValueTransformerProcessor.class.getName());
private static final String SOURCE = "Squonk assignment potion";
private int classCount = 0;
private final List<Conversion> conversions = new ArrayList<>();
private GroovyClassLoader groovyClassLoader;
private String errorFieldName = "TransformErrors";
private GroovyClassLoader getGroovyClassLoader() {
if (groovyClassLoader == null) {
groovyClassLoader = new GroovyClassLoader();
}
return groovyClassLoader;
}
@Override
public void process(Exchange exch) throws Exception {
TypeConverter typeConverter = exch.getContext().getTypeConverter();
Dataset ds = exch.getIn().getBody(Dataset.class);
Dataset neu = execute(typeConverter, ds);
exch.getIn().setBody(neu);
}
/**
* Add operations to perform the conversions, updating the dataset with the
* transformed stream, and adding appropriate field metadata. NOTE: this does NOT perform a terminal operation on
* the stream, so after calling this method the values are not yet transformed. The resulting stream must be processed
* by performing a terminal operation.
*
* @param typeConverter
* @param dataset
* @throws IOException
*/
public Dataset<? extends BasicObject> execute(TypeConverter typeConverter, Dataset<BasicObject> dataset) throws IOException {
Stream<BasicObject> stream = addConversions(typeConverter, dataset);
Class type = dataset.getType();
for (Conversion conversion : conversions) {
type = conversion.getObjectType(type);
}
DatasetMetadata oldMeta = dataset.getMetadata();
DatasetMetadata newMeta = new DatasetMetadata(type, null, oldMeta == null ? null : oldMeta.getFieldMetaProps(), -1, oldMeta == null ? null : oldMeta.getProperties());
Dataset newData = new Dataset(type, stream, newMeta);
return newData;
}
public Stream<BasicObject> addConversions(TypeConverter typeConverter, Dataset<BasicObject> dataset) throws IOException {
Stream<BasicObject> stream = dataset.getStream();
for (Conversion conversion : conversions) {
LOG.info("Handling conversion: " + conversion);
stream = conversion.execute(typeConverter, stream);
if (dataset.getMetadata() != null) {
conversion.updateMetadata(dataset.getMetadata());
}
}
return stream;
}
public static ValueTransformerProcessor create(TransformDefinitions txdefs) {
ValueTransformerProcessor vtp = new ValueTransformerProcessor();
for (AbstractTransform tx : txdefs.getTransforms()) {
if (tx instanceof DeleteRowTransform) {
DeleteRowTransform df = (DeleteRowTransform) tx;
vtp.deleteRow(df.getCondition());
} else if (tx instanceof DeleteFieldTransform) {
DeleteFieldTransform df = (DeleteFieldTransform) tx;
vtp.deleteValue(df.getFieldName(), df.getCondition());
} else if (tx instanceof RenameFieldTransform) {
RenameFieldTransform rf = (RenameFieldTransform) tx;
vtp.convertValueName(rf.getFieldName(), rf.getNewName());
} else if (tx instanceof ConvertFieldTransform) {
ConvertFieldTransform cf = (ConvertFieldTransform) tx;
vtp.convertValueType(cf.getFieldName(), cf.getNewType(), cf.getGenericType(), cf.getOnError());
} else if (tx instanceof ReplaceValueTransform) {
ReplaceValueTransform cf = (ReplaceValueTransform) tx;
vtp.replaceValue(cf.getFieldName(), cf.getMatch(), cf.getResult());
} else if (tx instanceof ConvertToMoleculeTransform) {
ConvertToMoleculeTransform cf = (ConvertToMoleculeTransform) tx;
vtp.convertToMolecule(cf.getStructureFieldName(), cf.getStructureFormat());
} else if (tx instanceof AssignValueTransform) {
AssignValueTransform cf = (AssignValueTransform) tx;
vtp.assignValue(cf.getFieldName(), cf.getExpression(), cf.getCondition(), cf.getOnError());
}
}
return vtp;
}
public ValueTransformerProcessor replaceValue(String fldName, Object match, Object result) {
conversions.add(new ReplaceValueConversion(fldName, match, result));
return this;
}
public ValueTransformerProcessor assignValue(String fldName, String expression, String condition, String onError) {
conversions.add(new AssignConversion(fldName, expression, condition, onError));
return this;
}
public ValueTransformerProcessor convertValueType(String fldName, Class newClass) {
return convertValueType(fldName, newClass, null, null);
}
public ValueTransformerProcessor convertValueType(String fldName, Class newClass, Class genericType, String onError) {
if (genericType != null) {
// check that its got the right constructor to save nasty exceptions later
try {
Constructor c = newClass.getConstructor(Object.class, Class.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Illegal conversion. Must have constructor that takes Object, Class");
}
}
conversions.add(new TypeConversion(fldName, newClass, genericType, onError));
return this;
}
public ValueTransformerProcessor convertValueName(String oldName, String newName) {
conversions.add(new RenameFieldConversion(oldName, newName));
return this;
}
public ValueTransformerProcessor deleteValue(String name, String condition) {
conversions.add(new DeleteFieldConversion(name, condition));
return this;
}
public ValueTransformerProcessor deleteRow(String condition) {
conversions.add(new DeleteRowConversion(condition));
return this;
}
public ValueTransformerProcessor convertToMolecule(String structureField, String sturctureFormat) {
conversions.add(new ConvertToMoleculeConversion(structureField, sturctureFormat));
return this;
}
private abstract class Conversion {
abstract Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream);
abstract void updateMetadata(DatasetMetadata meta);
Class getObjectType(Class input) {
return input;
}
}
class ReplaceValueConversion extends Conversion {
final String fldName;
final Object match;
final Object result;
ReplaceValueConversion(String fldName, Object match, Object result) {
this.fldName = fldName;
this.match = match;
this.result = result;
}
void updateMetadata(DatasetMetadata meta) {
meta.appendFieldHistory(fldName, "Value conversion: " +
(match == null ? "null" : match.toString()) + " -> " +
(result == null ? "null" : result.toString()));
}
@Override
Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object old = o.getValue(fldName);
if (old == null) {
if (match == null) {
// null matches null
o.putValue(fldName, result);
}
} else {
if (old.equals(match)) {
// old matches match
o.putValue(fldName, result);
}
}
});
}
@Override
public String toString() {
return "ReplaceValueConversion [fldName:" + fldName + " match: " + match + " result: " + result + "]";
}
}
class TypeConversion extends Conversion {
final String fldName;
final Class newClass;
final Class genericClass;
final String onError;
TypeConversion(String fldName, Class newClass, Class genericClass, String onError) {
validateOnError(onError);
this.fldName = fldName;
this.newClass = newClass;
this.genericClass = genericClass;
this.onError = onError;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (genericClass == null) {
meta.appendFieldHistory(fldName, "Type converted to " + newClass.getName());
} else {
meta.appendFieldHistory(fldName, "Type converted to " + newClass.getName() + "<" + genericClass.getName() + ">");
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object old = o.getValue(fldName);
if (old != null) {
try {
Object neu = null;
if (genericClass != null) {
neu = genericCreate(old, newClass, genericClass);
} else {
neu = converter.convertTo(newClass, old);
}
o.putValue(fldName, neu);
} catch (Exception e) {
if (onError == null || "fail".equals(onError)) {
throw e;
} else if ("continue".equals(onError)) {
o.getValues().remove(fldName);
String current = o.getValue(errorFieldName, String.class);
String msg = "Failed to convert " + old + " for field " + fldName + " to " + newClass.getSimpleName();
if (current == null) {
o.putValue(errorFieldName, msg);
} else {
o.putValue(errorFieldName, current + "\n" + msg);
}
}
}
}
});
}
private Object genericCreate(Object value, Class type, Class genericType) {
try {
Constructor c = type.getConstructor(Object.class, Class.class);
return c.newInstance(value, genericType);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Failed to instantiate value", e);
}
}
@Override
public String toString() {
return "TypeConversion [fldName:" + fldName + " newClass: " + newClass + " genericClass: " + genericClass + " onError: " + onError + "]";
}
}
class RenameFieldConversion extends Conversion {
final String oldName;
final String newName;
RenameFieldConversion(String oldName, String newName) {
this.oldName = oldName;
this.newName = newName;
}
@Override
void updateMetadata(DatasetMetadata meta) {
// transfer the old
Map<String, DatasetMetadata.PropertiesHolder> phs = meta.getFieldMetaPropsMap();
DatasetMetadata.PropertiesHolder ph = phs.get(oldName);
if (ph != null) {
for (Map.Entry<String, Object> e : ph.getValues().entrySet()) {
meta.putFieldMetaProp(newName, e.getKey(), e.getValue());
}
}
// add rename event to history
meta.appendFieldHistory(newName, "Renamed from " + oldName + " to " + newName);
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
return stream.peek((o) -> {
Object value = o.getValue(oldName);
if (value != null) {
o.putValue(newName, value);
o.getValues().remove(oldName);
}
});
}
@Override
public String toString() {
return "RenameFieldConversion [oldName:" + oldName + " newName: " + newName + "]";
}
}
class DeleteFieldConversion extends Conversion {
final String fldName, condition;
DeleteFieldConversion(String fldName, String condition) {
this.fldName = fldName;
this.condition = condition;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (condition != null) {
meta.appendFieldHistory(fldName, "Deleted values matching condition: " + condition);
} else {
meta.appendDatasetHistory("Deleted field " + fldName);
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
if (condition == null) {
return stream.peek((o) -> {
o.getValues().remove(fldName);
});
} else {
try {
final Predicate predicate = createPredicteClass(condition);
return stream.peek((o) -> {
if (predicate.test(o)) {
o.getValues().remove(fldName);
}
});
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create filter", e);
}
}
}
@Override
public String toString() {
return "DeleteFieldConversion [fldName:" + fldName + " condition: " + condition + "]";
}
}
class AssignConversion extends Conversion {
final String fldName;
final String expression;
final String condition;
final String onError;
AssignConversion(String fldName, String expression, String condition, String onError) {
validateOnError(onError);
this.fldName = fldName;
this.expression = expression;
this.condition = condition;
this.onError = onError;
}
@Override
void updateMetadata(DatasetMetadata meta) {
String expr = formatExpression();
if (meta.getValueClassMappings().get(fldName) == null) {
// new field
meta.createField(fldName, SOURCE, "Assignment: " + expr, null);
} else {
meta.putFieldMetaProp(fldName, DatasetMetadata.PROP_SOURCE, SOURCE);
meta.appendFieldProperty(fldName, DatasetMetadata.PROP_DESCRIPTION, "Re-assigned: " + expr);
}
meta.appendFieldHistory(fldName, "Assignment: " + expr);
}
private String formatExpression() {
if (condition == null) {
return expression;
} else {
return expression + " IF " + condition;
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
Consumer c;
try {
c = createConsumer();
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create consumer", e);
}
return stream.peek(c);
}
private Consumer createConsumer() throws IllegalAccessException, InstantiationException {
String clsDef = createConsumerClassDefinition();
LOG.info("Built Consumer class:\n" + clsDef);
Class<Consumer> cls = getGroovyClassLoader().parseClass(clsDef);
Consumer consumer = cls.newInstance();
return consumer;
}
private String createConsumerClassDefinition() {
StringBuilder b1 = new StringBuilder();
b1.append("import static java.lang.Math.*\n")
.append("class MyConsumer").append(++classCount).append(" implements java.util.function.Consumer {\n")
.append(" void accept(def o) {\n")
.append(" o.values.with { ");
if (condition != null) {
b1.append("if ( ").append(condition).append(" ) { ");
}
StringBuilder b2 = new StringBuilder();
b2.append(fldName).append(" = ").append(expression);
if ("continue".equals(onError)) {
b1.append(wrapErrorHandler(b2.toString(), "Failed to evaluate field " + fldName));
} else if (onError == null || "fail".equals(onError)) {
b1.append(b2.toString());
}
if (condition != null) {
b1.append("\n }");
}
b1.append("\n }\n }\n}");
return b1.toString();
}
@Override
public String toString() {
return "AssignConversion [fldName:" + fldName + " expression: " + expression + " condition: " + condition + " orError: " + onError + "]";
}
}
class ConvertToMoleculeConversion extends Conversion {
final String field, format;
ConvertToMoleculeConversion(String structureField, String structureFormat) {
this.field = structureField;
this.format = structureFormat;
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
if (field == null) {
throw new NullPointerException("Field containing structure must be specified");
}
if (format == null) {
throw new NullPointerException("Structure format must be specified");
}
return stream.map((o) -> {
Object mol = o.getValue(field);
MoleculeObject mo = new MoleculeObject(o.getUUID(), mol == null ? null : mol.toString(), format, o.getValues());
mo.getValues().remove(field);
return mo;
});
}
@Override
void updateMetadata(DatasetMetadata meta) {
meta.appendDatasetHistory("Converted to molecules using field " + field + " and format " + format);
}
@Override
Class getObjectType(Class input) {
return MoleculeObject.class;
}
@Override
public String toString() {
return "ConvertToMoleculeConversion [field:" + field + " format: " + format + "]";
}
}
class DeleteRowConversion extends Conversion {
final String condition;
DeleteRowConversion(String condition) {
this.condition = condition;
}
@Override
void updateMetadata(DatasetMetadata meta) {
if (condition != null) {
meta.appendDatasetHistory("Deleted rows where: " + condition);
} else {
meta.appendDatasetHistory("Deleted all rows");
}
}
@Override
public Stream<BasicObject> execute(TypeConverter converter, Stream<BasicObject> stream) {
Predicate p;
try {
p = createPredicate();
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException("Failed to create filter", e);
}
return stream.filter(p);
}
private Predicate createPredicate() throws IllegalAccessException, InstantiationException {
if (condition == null) {
return o -> false;
} else {
Predicate predicate = createPredicteClass("!(" + condition + ")");
return predicate;
}
}
@Override
public String toString() {
return "DeleteRowConversion [condition:" + condition + "]";
}
}
private Predicate createPredicteClass(String condition)
throws IllegalAccessException, InstantiationException {
String clsdef = createPredicateClassDefinition(condition);
LOG.info("Predicate class: \n" + clsdef);
Class<Predicate> cls = getGroovyClassLoader().parseClass(clsdef);
Predicate predicate = cls.newInstance();
return predicate;
}
private String createPredicateClassDefinition(String condition) {
StringBuilder b = new StringBuilder()
.append("import static java.lang.Math.*\n")
.append("class MyPredicate").append(++classCount).append(" implements java.util.function.Predicate {\n")
.append(" boolean test(def o) {\n")
.append(" o.values.with { ")
.append(condition)
.append(" }\n }\n}");
return b.toString();
}
private String wrapErrorHandler(String expr, String message) {
StringBuilder b = new StringBuilder("\n try { ")
.append(expr)
.append(" } catch (Exception e) { \n")
.append(errorFieldName)
.append(" = ( ")
.append(errorFieldName)
.append(" == null ? '")
.append(message)
.append(". ' + e.class.simpleName + '[' + e.message")
.append("+ ']' : ")
.append(errorFieldName).append(" + '\\n' + '").append(message)
.append(". ' + e.class.simpleName + '[' + e.message")
.append(" + ']' )\n}");
return b.toString();
}
/**
* @param onError
* @throws IllegalArgumentException if not fail or continue
*/
void validateOnError(String onError) {
if (onError != null) {
if ("fail".equals(onError) || "continue".equals(onError)) {
return;
}
throw new IllegalArgumentException("Bad onError value: " + onError);
}
}
}
|
tweaks to potions metadata
|
components/common-camel/src/main/java/org/squonk/camel/processor/ValueTransformerProcessor.java
|
tweaks to potions metadata
|
|
Java
|
apache-2.0
|
1f588b13873c37cb12fd4dda017b2085cdbbfc72
| 0
|
jamesjara/Fortumo-Sms-Gateway-Cordova-Plugin,jamesjara/Fortumo-Sms-Gateway-Cordova-Plugin,jamesjara/Fortumo-Sms-Gateway-Cordova-Plugin
|
package jamesjara.com.cordova.fortumo;
//import com.squareup.okhttpxxxxxxx3.internal.StrictLineReader;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.Manifest;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import jamesjara.com.cordova.fortumo.PaymentConstants;
import mp.MpUtils;
import mp.PaymentActivity;
import mp.PaymentRequest;
import mp.PaymentResponse;
public class FortumoSmsCordovaPlugin extends CordovaPlugin
{
private static final int REQUEST_CODE = 87944598; // if you want to call me :) +506
public static final String TAG = "forumo-sms-gateway";
//private PaymentActivity mClass;
public static final String READ = "xxx";//Manifest.permission.PAYMENT_BROADCAST_PERMISSION;
public String ServiceId = "";
public String AppSecret = "";
/*
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PaymentConstants.SUCCESSFUL_PAYMENT);
registerReceiver(updateReceiver, filter);
Log.i(TAG, "updateReceiver registered");
}
@Override
protected void onStop() {
unregisterReceiver(updateReceiver);
Log.i(TAG, "updateReceiver unregistered");
super.onPause();
}
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
if ("init".equals(action))
{
/*
JSONObject config = args.getJSONObject(0);
String serviceId = config.getString("serviceId");
String appSecret = config.getString("appSecret");
ServiceId = serviceId;
AppSecret = appSecret;
*/
//_helper = Fortumo.enablePaymentBroadcast(this, Manifest.permission.PAYMENT_BROADCAST_PERMISSION);
init(callbackContext);
return true;
}
else if ("setProduct".equals(action))
{
String productId = args.getString(0);
JSONObject productData = args.getJSONObject(1) ;
setProduct(productId, productData , callbackContext);
return true;
}
else if ("getProducts".equals(action))
{
getProducts(callbackContext);
return true;
}
else if ("purchaseProduct".equals(action))
{
String productId = args.getString(0);
String payload = args.length() > 1 ? args.getString(1) : "";
purchaseProduct(productId, payload, callbackContext);
return true;
}
else if ("purchaseSubscription".equals(action))
{
/*
String sku = args.getString(0);
String payload = args.length() > 1 ? args.getString(1) : "";
purchaseProduct(sku, payload, callbackContext);
return true;
*/
}
else if ("consume".equals(action))
{
/*
String sku = args.getString(0);
consume(sku, callbackContext);
return true;
*/
}
else if ("getSkuDetails".equals(action))
{
/*
String sku = args.getString(0);
getSkuDetails(sku, callbackContext);
return true;
*/
}
else if ("getSkuListDetails".equals(action))
{
/*
List<String> skuList = new ArrayList<String>();
if (args.length() > 0) {
JSONArray jSkuList = args.getJSONArray(0);
int count = jSkuList.length();
for (int i = 0; i < count; ++i) {
skuList.add(jSkuList.getString(i));
}
}
getSkuListDetails(skuList, callbackContext);
return true;
*/
}
else if ("getPurchases".equals(action))
{
/*
getPurchases(callbackContext);
return true;
*/
}
else if ("mapSku".equals(action))
{
/*
String sku = args.getString(0);
String storeName = args.getString(1);
String storeSku = args.getString(2);
mapSku(sku, storeName, storeSku);
return true;
*/
}
return false; // Returning false results in a "MethodNotFound" error.
}
private void getProducts(final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
// try {
JSONArray JSON = new JSONArray();
for(Map.Entry<String, JSONObject> entry : products.entrySet()) {
String key = entry.getKey();
JSONObject value = entry.getValue();
JSONObject childs = new JSONObject();
childs.put( "asd" , "tsssss");
JSONObject parentObj = new JSONObject();
parentObj.put( key , childs);
JSON.put(parentObj);
}
callbackContext.success(JSON);
/* } catch (JSONException e) {
callbackContext.error( e.getMessage());
return;
}*/
}
private void mapSku(String sku, String storeName, String storeSku) {
//SkuManager.getInstance().mapSku(sku, storeName, storeSku);
}
private void getPurchases(final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
List<Purchase> purchaseList = _inventory.getAllPurchases();
JSONArray jsonPurchaseList = new JSONArray();
for (Purchase p : purchaseList) {
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(p);
jsonPurchaseList.put(jsonPurchase);
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize Purchase: " + p.getSku()));
return;
}
}
callbackContext.success(jsonPurchaseList);
*/
}
private void getSkuDetails(String sku, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
if (!_inventory.hasDetails(sku)) {
callbackContext.error(Serialization.errorToJson(-1, "SkuDetails not found: " + sku));
return;
}
JSONObject jsonSkuDetails;
try {
jsonSkuDetails = Serialization.skuDetailsToJson(_inventory.getSkuDetails(sku));
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize SkuDetails: " + sku));
return;
}
callbackContext.success(jsonSkuDetails);
*/
}
private void getSkuListDetails(List<String> skuList, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
JSONArray jsonSkuDetailsList = new JSONArray();
for (String sku : skuList) {
if (_inventory.hasDetails(sku)) {
JSONObject jsonSkuDetails;
try {
jsonSkuDetails = Serialization.skuDetailsToJson(_inventory.getSkuDetails(sku));
jsonSkuDetailsList.put(jsonSkuDetails);
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize SkuDetails: " + sku));
return;
}
}
else {
Log.d(TAG, "SKU NOT FOUND: " + sku);
}
}
callbackContext.success(jsonSkuDetailsList);
*/
}
//private void init(final JSONArray options, final List<String> skuList, final CallbackContext callbackContext) {
private void init( final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
// MpUtils.enablePaymentBroadcast(this, READ); //Manifest.permission.PAYMENT_BROADCAST_PERMISSION);
// _helper = new OpenIabHelper(cordova.getActivity(), options);
createBroadcasts();
new UpdateDataTask().execute();
// Start setup. This is asynchronous and the specified listener
// will be called once setup completes.
/*
Log.d(TAG, "Starting setup.");
_helper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (result.isFailure()) {
// Oh noes, there was a problem.
Log.e(TAG, "Problem setting up in-app billing: " + result);
callbackContext.error(Serialization.errorToJson(result));
return;
}
Log.d(TAG, "Querying inventory.");
// TODO: this is SHIT! product and subs skus shouldn't be sent two times
//_helper.queryInventoryAsync(true, skuList, skuList, new BillingCallback(callbackContext));
}
});
*/
}
});
}
private boolean checkInitialized(final CallbackContext callbackContext) {
if (false)
{
Log.e(TAG, "Not initialized");
callbackContext.error("Not initialized");
return false;
}
return true;
}
private static final HashMap<String, JSONObject> products = new HashMap<String, JSONObject>();
private void setProduct(final String productId, final JSONObject productData, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//Map<String, Object> producDataAsMap = new HashMap<String, Object>();
//producDataAsMap = toMap(productData);
products.put(productId, productData);
callbackContext.success();
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
}
});
}
private void purchaseProduct(final String productId, final String developerPayload, final CallbackContext callbackContext) throws JSONException {
if (!checkInitialized(callbackContext)) return;
//Log.d(TAG, "SKU: " + SkuManager.getInstance().getStoreSku(OpenIabHelper.NAME_GOOGLE, sku));
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//mClass.PaymentRequest.PaymentRequestBuilder builder = new mClass.PaymentRequest.PaymentRequestBuilder();
PaymentRequest.PaymentRequestBuilder builder = new PaymentRequest.PaymentRequestBuilder();
builder.setService("aaaa", "ffffffff");
JSONObject config = products.get(productId);
String testtttt = config.getString("productName");
// get data form map
builder.setProductName(testtttt);
builder.setConsumable(true);
builder.setDisplayString(PaymentConstants.DISPLAY_STRING_GOLD);
builder.setCreditsMultiplier(1.1d);
//builder.setIcon(R.drawable.ic_launcher);
PaymentRequest pr = builder.build();
// execute
Intent localIntent = pr.toIntent(cordova.getActivity());
cordova.getActivity().startActivityForResult(localIntent, REQUEST_CODE);
//makePayment(pr);
//_helper.launchPurchaseFlow(cordova.getActivity(), sku, RC_REQUEST, new BillingCallback(callbackContext), developerPayload);
}
});
}
public void purchaseSubscription(final String sku, final String developerPayload, final CallbackContext callbackContext) {
/*
if (!checkInitialized(callbackContext)) return;
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
_helper.launchSubscriptionPurchaseFlow(cordova.getActivity(), sku, RC_REQUEST, new BillingCallback(callbackContext), developerPayload);
}
});
*/
}
private void consume(final String sku, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!_inventory.hasPurchase(sku))
{
callbackContext.error(Serialization.errorToJson(-1, "Product haven't been purchased: " + sku));
return;
}
Purchase purchase = _inventory.getPurchase(sku);
_helper.consumeAsync(purchase, new BillingCallback(callbackContext));
}
});
*/
}
private class UpdateDataTask extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... voids) {
String[] result = new String[1];
result[0] = String.valueOf("asd");
//result[0] = String.valueOf(Wallet.getColdAmount(MainActivity.this));
//result[1] = String.valueOf(BonusLevel.isBonusUnlocked(MainActivity.this));
//result[2] = String.valueOf(PotionStack.getPotionAmount(MainActivity.this, PaymentConstants.PRODUCT_HEALTH_POTION));
//result[3] = String.valueOf(PotionStack.getPotionAmount(MainActivity.this, PaymentConstants.PRODUCT_MANA_POTION));
return result;
}
@Override
protected void onPostExecute(String[] data) {
// goldTextView.setText(data[0]);
// bonusLevelUnlockedTextView.setText(data[1]);
// healthPotionTextView.setText(data[2]);
// manaPotionTextView.setText(data[3]);
}
}
/**
* Callback class for when a purchase or consumption process is finished
*/
/*
public class BillingCallback implements
IabHelper.QueryInventoryFinishedListener,
IabHelper.OnIabPurchaseFinishedListener,
IabHelper.OnConsumeFinishedListener {
final CallbackContext _callbackContext;
public BillingCallback(final CallbackContext callbackContext) {
_callbackContext = callbackContext;
}
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory process finished.");
if (result.isFailure()) {
_callbackContext.error(Serialization.errorToJson(result));
return;
}
Log.d(TAG, "Query inventory was successful. Init finished.");
_inventory = inventory;
_callbackContext.success();
}
@Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase process finished: " + result + ", purchase: " + purchase);
if (result.isFailure()) {
Log.e(TAG, "Error purchasing: " + result);
_callbackContext.error(Serialization.errorToJson(result));
return;
}
_inventory.addPurchase(purchase);
Log.d(TAG, "Purchase successful.");
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(purchase);
} catch (JSONException e) {
_callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize the purchase"));
return;
}
_callbackContext.success(jsonPurchase);
}
@Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
Log.d(TAG, "Consumption process finished. Purchase: " + purchase + ", result: " + result);
if (result.isFailure()) {
Log.e(TAG, "Error while consuming: " + result);
_callbackContext.error(Serialization.errorToJson(result));
return;
}
_inventory.erasePurchase(purchase.getSku());
Log.d(TAG, "Consumption successful. Provisioning.");
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(purchase);
} catch (JSONException e) {
_callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize the purchase"));
return;
}
_callbackContext.success(jsonPurchase);
}
}
*/
private void createBroadcasts() {
Log.d(TAG, "createBroadcasts");
/*
IntentFilter filter = new IntentFilter(YANDEX_STORE_ACTION_PURCHASE_STATE_CHANGED);
cordova.getActivity().registerReceiver(_billingReceiver, filter);
*/
IntentFilter filter = new IntentFilter(PaymentConstants.SUCCESSFUL_PAYMENT);
cordova.getActivity().registerReceiver(_billingReceiver, filter);
Log.i(TAG, "updateReceiver registered");
}
private void destroyBroadcasts() {
Log.d(TAG, "destroyBroadcasts");
try {
cordova.getActivity().unregisterReceiver(_billingReceiver);
} catch (Exception ex) {
Log.d(TAG, "destroyBroadcasts exception:\n" + ex.getMessage());
}
}
private BroadcastReceiver _billingReceiver = new BroadcastReceiver() {
private static final String TAG = "YandexBillingReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();
Log.d(TAG, "onReceive intent: " + intent);
//if (YANDEX_STORE_ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(extras, intent);
//}
}
private void purchaseStateChanged(Bundle extras, Intent intent) {
Log.d(TAG, "purchaseStateChanged intent: " + extras);
//_helper.handleActivityResult(RC_REQUEST, Activity.RESULT_OK, data);
// Log.d(TAG, "- billing_status: " + getStatusString(extras.getInt("billing_status")));
Log.d(TAG, "- credit_amount: " + extras.getString("credit_amount"));
Log.d(TAG, "- credit_name: " + extras.getString("credit_name"));
Log.d(TAG, "- message_id: " + extras.getString("message_id") );
Log.d(TAG, "- payment_code: " + extras.getString("payment_code"));
Log.d(TAG, "- price_amount: " + extras.getString("price_amount"));
Log.d(TAG, "- price_currency: " + extras.getString("price_currency"));
Log.d(TAG, "- product_name: " + extras.getString("product_name"));
Log.d(TAG, "- service_id: " + extras.getString("service_id"));
Log.d(TAG, "- user_id: " + extras.getString("user_id"));
int billingStatus = extras.getInt("billing_status");
if(billingStatus == MpUtils.MESSAGE_STATUS_BILLED) {
int coins = Integer.parseInt(intent.getStringExtra("credit_amount"));
//Wallet.addCoins(context, coins);
new UpdateDataTask().execute();
}
}
};
/*
protected final void makePayment(PaymentRequest payment) {
Intent localIntent = paymentRequest.toIntent(act);
act.startActivityForResult(localIntent, requestCode);
Context context = cordova.getActivity().getApplicationContext();
Intent intent = new Intent(context,payment.toIntent(this));
startActivityForResult(this, intent, 0);
}
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if(data == null) {
return;
}
// OK
if (resultCode == Activity.RESULT_OK){//RESULT_OK) {
PaymentResponse response = new PaymentResponse(data);
switch (response.getBillingStatus()) {
case MpUtils.MESSAGE_STATUS_BILLED:
// ...
break;
case MpUtils.MESSAGE_STATUS_FAILED:
// ...
break;
case MpUtils.MESSAGE_STATUS_PENDING:
// ...
break;
}
// Cancel
} else {
// ..
}
} else {
//super.onActivityResult(requestCode, resultCode, data);
}
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
private static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
|
android/src/FortumoSmsCordovaPlugin.java
|
package jamesjara.com.cordova.fortumo;
//import com.squareup.okhttpxxxxxxx3.internal.StrictLineReader;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.Manifest;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import jamesjara.com.cordova.fortumo.PaymentConstants;
import mp.MpUtils;
import mp.PaymentActivity;
import mp.PaymentRequest;
import mp.PaymentResponse;
public class FortumoSmsCordovaPlugin extends CordovaPlugin
{
private static final int REQUEST_CODE = 87944598; // if you want to call me :) +506
public static final String TAG = "forumo-sms-gateway";
//private PaymentActivity mClass;
public static final String READ = "xxx";//Manifest.permission.PAYMENT_BROADCAST_PERMISSION;
public String ServiceId = "";
public String AppSecret = "";
/*
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PaymentConstants.SUCCESSFUL_PAYMENT);
registerReceiver(updateReceiver, filter);
Log.i(TAG, "updateReceiver registered");
}
@Override
protected void onStop() {
unregisterReceiver(updateReceiver);
Log.i(TAG, "updateReceiver unregistered");
super.onPause();
}
*/
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
if ("init".equals(action))
{
/*
JSONObject config = args.getJSONObject(0);
String serviceId = config.getString("serviceId");
String appSecret = config.getString("appSecret");
ServiceId = serviceId;
AppSecret = appSecret;
*/
//_helper = Fortumo.enablePaymentBroadcast(this, Manifest.permission.PAYMENT_BROADCAST_PERMISSION);
init(callbackContext);
return true;
}
else if ("setProduct".equals(action))
{
String productId = args.getString(0);
JSONObject productData = args.getJSONObject(1) ;
setProduct(productId, productData , callbackContext);
return true;
}
else if ("getProducts".equals(action))
{
getProducts(callbackContext);
return true;
}
else if ("purchaseProduct".equals(action))
{
String productId = args.getString(0);
String payload = args.length() > 1 ? args.getString(1) : "";
purchaseProduct(productId, payload, callbackContext);
return true;
}
else if ("purchaseSubscription".equals(action))
{
/*
String sku = args.getString(0);
String payload = args.length() > 1 ? args.getString(1) : "";
purchaseProduct(sku, payload, callbackContext);
return true;
*/
}
else if ("consume".equals(action))
{
/*
String sku = args.getString(0);
consume(sku, callbackContext);
return true;
*/
}
else if ("getSkuDetails".equals(action))
{
/*
String sku = args.getString(0);
getSkuDetails(sku, callbackContext);
return true;
*/
}
else if ("getSkuListDetails".equals(action))
{
/*
List<String> skuList = new ArrayList<String>();
if (args.length() > 0) {
JSONArray jSkuList = args.getJSONArray(0);
int count = jSkuList.length();
for (int i = 0; i < count; ++i) {
skuList.add(jSkuList.getString(i));
}
}
getSkuListDetails(skuList, callbackContext);
return true;
*/
}
else if ("getPurchases".equals(action))
{
/*
getPurchases(callbackContext);
return true;
*/
}
else if ("mapSku".equals(action))
{
/*
String sku = args.getString(0);
String storeName = args.getString(1);
String storeSku = args.getString(2);
mapSku(sku, storeName, storeSku);
return true;
*/
}
return false; // Returning false results in a "MethodNotFound" error.
}
private void getProducts(final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
try {
JSONArray JSON = new JSONArray();
for(Map.Entry<String, JSONObject> entry : products.entrySet()) {
String key = entry.getKey();
JSONObject value = entry.getValue();
JSONObject childs = new JSONObject();
childs.put( "asd" , "tsssss");
JSONObject parentObj = new JSONObject();
parentObj.put( key , childs);
JSON.put(parentObj);
}
callbackContext.success(JSON);
} catch (JSONException e) {
callbackContext.error( e.getMessage());
return;
}
}
private void mapSku(String sku, String storeName, String storeSku) {
//SkuManager.getInstance().mapSku(sku, storeName, storeSku);
}
private void getPurchases(final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
List<Purchase> purchaseList = _inventory.getAllPurchases();
JSONArray jsonPurchaseList = new JSONArray();
for (Purchase p : purchaseList) {
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(p);
jsonPurchaseList.put(jsonPurchase);
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize Purchase: " + p.getSku()));
return;
}
}
callbackContext.success(jsonPurchaseList);
*/
}
private void getSkuDetails(String sku, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
if (!_inventory.hasDetails(sku)) {
callbackContext.error(Serialization.errorToJson(-1, "SkuDetails not found: " + sku));
return;
}
JSONObject jsonSkuDetails;
try {
jsonSkuDetails = Serialization.skuDetailsToJson(_inventory.getSkuDetails(sku));
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize SkuDetails: " + sku));
return;
}
callbackContext.success(jsonSkuDetails);
*/
}
private void getSkuListDetails(List<String> skuList, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
JSONArray jsonSkuDetailsList = new JSONArray();
for (String sku : skuList) {
if (_inventory.hasDetails(sku)) {
JSONObject jsonSkuDetails;
try {
jsonSkuDetails = Serialization.skuDetailsToJson(_inventory.getSkuDetails(sku));
jsonSkuDetailsList.put(jsonSkuDetails);
} catch (JSONException e) {
callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize SkuDetails: " + sku));
return;
}
}
else {
Log.d(TAG, "SKU NOT FOUND: " + sku);
}
}
callbackContext.success(jsonSkuDetailsList);
*/
}
//private void init(final JSONArray options, final List<String> skuList, final CallbackContext callbackContext) {
private void init( final CallbackContext callbackContext) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
// MpUtils.enablePaymentBroadcast(this, READ); //Manifest.permission.PAYMENT_BROADCAST_PERMISSION);
// _helper = new OpenIabHelper(cordova.getActivity(), options);
createBroadcasts();
new UpdateDataTask().execute();
// Start setup. This is asynchronous and the specified listener
// will be called once setup completes.
/*
Log.d(TAG, "Starting setup.");
_helper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (result.isFailure()) {
// Oh noes, there was a problem.
Log.e(TAG, "Problem setting up in-app billing: " + result);
callbackContext.error(Serialization.errorToJson(result));
return;
}
Log.d(TAG, "Querying inventory.");
// TODO: this is SHIT! product and subs skus shouldn't be sent two times
//_helper.queryInventoryAsync(true, skuList, skuList, new BillingCallback(callbackContext));
}
});
*/
}
});
}
private boolean checkInitialized(final CallbackContext callbackContext) {
if (false)
{
Log.e(TAG, "Not initialized");
callbackContext.error("Not initialized");
return false;
}
return true;
}
private static final HashMap<String, JSONObject> products = new HashMap<String, JSONObject>();
private void setProduct(final String productId, final JSONObject productData, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//Map<String, Object> producDataAsMap = new HashMap<String, Object>();
//producDataAsMap = toMap(productData);
products.put(productId, productData);
callbackContext.success();
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
}
});
}
private void purchaseProduct(final String productId, final String developerPayload, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
//Log.d(TAG, "SKU: " + SkuManager.getInstance().getStoreSku(OpenIabHelper.NAME_GOOGLE, sku));
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
//mClass.PaymentRequest.PaymentRequestBuilder builder = new mClass.PaymentRequest.PaymentRequestBuilder();
PaymentRequest.PaymentRequestBuilder builder = new PaymentRequest.PaymentRequestBuilder();
builder.setService("aaaa", "ffffffff");
JSONObject config = products.get(productId);
String testtttt = config.getString("productName");
// get data form map
builder.setProductName(testtttt);
builder.setConsumable(true);
builder.setDisplayString(PaymentConstants.DISPLAY_STRING_GOLD);
builder.setCreditsMultiplier(1.1d);
//builder.setIcon(R.drawable.ic_launcher);
PaymentRequest pr = builder.build();
// execute
Intent localIntent = pr.toIntent(cordova.getActivity());
cordova.getActivity().startActivityForResult(localIntent, REQUEST_CODE);
//makePayment(pr);
//_helper.launchPurchaseFlow(cordova.getActivity(), sku, RC_REQUEST, new BillingCallback(callbackContext), developerPayload);
}
});
}
public void purchaseSubscription(final String sku, final String developerPayload, final CallbackContext callbackContext) {
/*
if (!checkInitialized(callbackContext)) return;
cordova.setActivityResultCallback(this);
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
_helper.launchSubscriptionPurchaseFlow(cordova.getActivity(), sku, RC_REQUEST, new BillingCallback(callbackContext), developerPayload);
}
});
*/
}
private void consume(final String sku, final CallbackContext callbackContext) {
if (!checkInitialized(callbackContext)) return;
/*
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (!_inventory.hasPurchase(sku))
{
callbackContext.error(Serialization.errorToJson(-1, "Product haven't been purchased: " + sku));
return;
}
Purchase purchase = _inventory.getPurchase(sku);
_helper.consumeAsync(purchase, new BillingCallback(callbackContext));
}
});
*/
}
private class UpdateDataTask extends AsyncTask<Void, Void, String[]> {
@Override
protected String[] doInBackground(Void... voids) {
String[] result = new String[1];
result[0] = String.valueOf("asd");
//result[0] = String.valueOf(Wallet.getColdAmount(MainActivity.this));
//result[1] = String.valueOf(BonusLevel.isBonusUnlocked(MainActivity.this));
//result[2] = String.valueOf(PotionStack.getPotionAmount(MainActivity.this, PaymentConstants.PRODUCT_HEALTH_POTION));
//result[3] = String.valueOf(PotionStack.getPotionAmount(MainActivity.this, PaymentConstants.PRODUCT_MANA_POTION));
return result;
}
@Override
protected void onPostExecute(String[] data) {
// goldTextView.setText(data[0]);
// bonusLevelUnlockedTextView.setText(data[1]);
// healthPotionTextView.setText(data[2]);
// manaPotionTextView.setText(data[3]);
}
}
/**
* Callback class for when a purchase or consumption process is finished
*/
/*
public class BillingCallback implements
IabHelper.QueryInventoryFinishedListener,
IabHelper.OnIabPurchaseFinishedListener,
IabHelper.OnConsumeFinishedListener {
final CallbackContext _callbackContext;
public BillingCallback(final CallbackContext callbackContext) {
_callbackContext = callbackContext;
}
@Override
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory process finished.");
if (result.isFailure()) {
_callbackContext.error(Serialization.errorToJson(result));
return;
}
Log.d(TAG, "Query inventory was successful. Init finished.");
_inventory = inventory;
_callbackContext.success();
}
@Override
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
Log.d(TAG, "Purchase process finished: " + result + ", purchase: " + purchase);
if (result.isFailure()) {
Log.e(TAG, "Error purchasing: " + result);
_callbackContext.error(Serialization.errorToJson(result));
return;
}
_inventory.addPurchase(purchase);
Log.d(TAG, "Purchase successful.");
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(purchase);
} catch (JSONException e) {
_callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize the purchase"));
return;
}
_callbackContext.success(jsonPurchase);
}
@Override
public void onConsumeFinished(Purchase purchase, IabResult result) {
Log.d(TAG, "Consumption process finished. Purchase: " + purchase + ", result: " + result);
if (result.isFailure()) {
Log.e(TAG, "Error while consuming: " + result);
_callbackContext.error(Serialization.errorToJson(result));
return;
}
_inventory.erasePurchase(purchase.getSku());
Log.d(TAG, "Consumption successful. Provisioning.");
JSONObject jsonPurchase;
try {
jsonPurchase = Serialization.purchaseToJson(purchase);
} catch (JSONException e) {
_callbackContext.error(Serialization.errorToJson(-1, "Couldn't serialize the purchase"));
return;
}
_callbackContext.success(jsonPurchase);
}
}
*/
private void createBroadcasts() {
Log.d(TAG, "createBroadcasts");
/*
IntentFilter filter = new IntentFilter(YANDEX_STORE_ACTION_PURCHASE_STATE_CHANGED);
cordova.getActivity().registerReceiver(_billingReceiver, filter);
*/
IntentFilter filter = new IntentFilter(PaymentConstants.SUCCESSFUL_PAYMENT);
cordova.getActivity().registerReceiver(_billingReceiver, filter);
Log.i(TAG, "updateReceiver registered");
}
private void destroyBroadcasts() {
Log.d(TAG, "destroyBroadcasts");
try {
cordova.getActivity().unregisterReceiver(_billingReceiver);
} catch (Exception ex) {
Log.d(TAG, "destroyBroadcasts exception:\n" + ex.getMessage());
}
}
private BroadcastReceiver _billingReceiver = new BroadcastReceiver() {
private static final String TAG = "YandexBillingReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();
Log.d(TAG, "onReceive intent: " + intent);
//if (YANDEX_STORE_ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(extras, intent);
//}
}
private void purchaseStateChanged(Bundle extras, Intent intent) {
Log.d(TAG, "purchaseStateChanged intent: " + extras);
//_helper.handleActivityResult(RC_REQUEST, Activity.RESULT_OK, data);
// Log.d(TAG, "- billing_status: " + getStatusString(extras.getInt("billing_status")));
Log.d(TAG, "- credit_amount: " + extras.getString("credit_amount"));
Log.d(TAG, "- credit_name: " + extras.getString("credit_name"));
Log.d(TAG, "- message_id: " + extras.getString("message_id") );
Log.d(TAG, "- payment_code: " + extras.getString("payment_code"));
Log.d(TAG, "- price_amount: " + extras.getString("price_amount"));
Log.d(TAG, "- price_currency: " + extras.getString("price_currency"));
Log.d(TAG, "- product_name: " + extras.getString("product_name"));
Log.d(TAG, "- service_id: " + extras.getString("service_id"));
Log.d(TAG, "- user_id: " + extras.getString("user_id"));
int billingStatus = extras.getInt("billing_status");
if(billingStatus == MpUtils.MESSAGE_STATUS_BILLED) {
int coins = Integer.parseInt(intent.getStringExtra("credit_amount"));
//Wallet.addCoins(context, coins);
new UpdateDataTask().execute();
}
}
};
/*
protected final void makePayment(PaymentRequest payment) {
Intent localIntent = paymentRequest.toIntent(act);
act.startActivityForResult(localIntent, requestCode);
Context context = cordova.getActivity().getApplicationContext();
Intent intent = new Intent(context,payment.toIntent(this));
startActivityForResult(this, intent, 0);
}
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if(data == null) {
return;
}
// OK
if (resultCode == Activity.RESULT_OK){//RESULT_OK) {
PaymentResponse response = new PaymentResponse(data);
switch (response.getBillingStatus()) {
case MpUtils.MESSAGE_STATUS_BILLED:
// ...
break;
case MpUtils.MESSAGE_STATUS_FAILED:
// ...
break;
case MpUtils.MESSAGE_STATUS_PENDING:
// ...
break;
}
// Cancel
} else {
// ..
}
} else {
//super.onActivityResult(requestCode, resultCode, data);
}
}
private static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
private static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
|
fortumo sms plugin
|
android/src/FortumoSmsCordovaPlugin.java
|
fortumo sms plugin
|
|
Java
|
apache-2.0
|
96e62f955b080e80f1047c9d2f7df2854fef0c2d
| 0
|
dankoman30/Apktool,zhanwei/android-apktool,kuter007/android-apktool,Benjamin-Dobell/Apktool,fromsatellite/Apktool,androidmchen/Apktool,sawrus/Apktool,rover12421/Apktool,pandazheng/Apktool,KuaiFaMaster/Apktool,hongnguyenpro/Apktool,fabiand93/Apktool,jianglibo/Apktool,asolfre/android-apktool,kaneawk/Apktool,lnln1111/android-apktool,370829592/android-apktool,Klozz/Apktool,zhakui/Apktool,valery-barysok/Apktool,zhic5352/Apktool,phhusson/Apktool,bingshi/android-apktool,yunemr/Apktool,MiCode/brut.apktool,CheungSKei/Apktool,pandazheng/Apktool,zdzhjx/android-apktool,sawrus/Apktool,Yaeger/Apktool,HackerTool/Apktool,admin-zhx/Apktool,desword/android-apktool,tmpgit/Apktool,zhic5352/Apktool,hongnguyenpro/Apktool,virustotalop/Apktool,harish123400/Apktool,virustotalop/Apktool,alipov/Apktool,lovely3x/Apktool,berkus/android-apktool,tmpgit/Apktool,chenrui2014/Apktool,pwelyn/Apktool,iBotPeaches/Apktool,harish123400/Apktool,akhirasip/Apktool,fabiand93/Apktool,admin-zhx/Apktool,Benjamin-Dobell/Apktool,rover12421/Apktool,yujokang/Apktool,alipov/Apktool,lovely3x/Apktool,draekko/Apktool,pwelyn/Apktool,ccgreen13/Apktool,kesuki/Apktool,yunemr/Apktool,bingshi/android-apktool,androidmchen/Apktool,youleyu/android-apktool,berkus/android-apktool,blaquee/Apktool,fromsatellite/Apktool,ccgreen13/Apktool,valery-barysok/Apktool,guiyu/android-apktool,iBotPeaches/Apktool,lczgywzyy/Apktool,PiR43/Apktool,370829592/android-apktool,yujokang/Apktool,zhanwei/android-apktool,KuaiFaMaster/Apktool,phhusson/Apktool,lczgywzyy/Apktool,jasonzhong/Apktool,akhirasip/Apktool,youleyu/android-apktool,desword/android-apktool,nitinverma/Apktool,asolfre/android-apktool,PiR43/Apktool,guiyu/android-apktool,kaneawk/Apktool,CheungSKei/Apktool,dankoman30/Apktool,simtel12/Apktool,chenrui2014/Apktool,jasonzhong/Apktool,digshock/android-apktool,blaquee/Apktool,kuter007/android-apktool,digshock/android-apktool,Klozz/Apktool,zdzhjx/android-apktool,nitinverma/Apktool,HackerTool/Apktool,iAmGhost/brut.apktool,Yaeger/Apktool,lnln1111/android-apktool,zhakui/Apktool,kesuki/Apktool,simtel12/Apktool,draekko/Apktool,jianglibo/Apktool
|
/*
* Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.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.
* under the License.
*/
package brut.androlib.res.util;
import java.io.IOException;
import java.io.OutputStream;
import org.xmlpull.mxp1_serializer.MXSerializer;
/**
* @author Ryszard Wiśniewski <brut.alll@gmail.com>
*/
public class ExtMXSerializer extends MXSerializer {
@Override
public void startDocument(String encoding, Boolean standalone) throws
IOException, IllegalArgumentException, IllegalStateException {
super.startDocument(encoding != null ? encoding : mDefaultEncoding,
standalone);
super.out.write(lineSeparator);
}
@Override
public void setOutput(OutputStream os, String encoding) throws IOException {
super.setOutput(os, encoding != null ? encoding : mDefaultEncoding);
}
@Override
public Object getProperty(String name) throws IllegalArgumentException {
if (PROPERTY_DEFAULT_ENCODING.equals(name)) {
return mDefaultEncoding;
}
return super.getProperty(name);
}
@Override
public void setProperty(String name, Object value)
throws IllegalArgumentException, IllegalStateException {
if (PROPERTY_DEFAULT_ENCODING.equals(name)) {
mDefaultEncoding = (String) value;
} else {
super.setProperty(name, value);
}
}
public final static String PROPERTY_DEFAULT_ENCODING = "DEFAULT_ENCODING";
private String mDefaultEncoding;
}
|
src/brut/androlib/res/util/ExtMXSerializer.java
|
/*
* Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.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.
* under the License.
*/
package brut.androlib.res.util;
import java.io.IOException;
import java.io.OutputStream;
import org.xmlpull.mxp1_serializer.MXSerializer;
/**
* @author Ryszard Wiśniewski <brut.alll@gmail.com>
*/
public class ExtMXSerializer extends MXSerializer {
@Override
public void startDocument(String encoding, Boolean standalone) throws
IOException, IllegalArgumentException, IllegalStateException {
super.startDocument(encoding != null ? encoding : mDefaultEncoding,
standalone);
super.out.write(lineSeparator);
}
@Override
public void setOutput(OutputStream os, String encoding) throws IOException {
super.setOutput(os, encoding != null ? encoding : mDefaultEncoding);
}
@Override
public Object getProperty(String name) throws IllegalArgumentException {
if (PROPERTY_DEFAULT_ENCODING.equals(name)) {
return mDefaultEncoding;
}
return super.getProperty(name);
}
@Override
public void setProperty(String name, Object value)
throws IllegalArgumentException, IllegalStateException {
if (PROPERTY_DEFAULT_ENCODING.equals(name)) {
mDefaultEncoding = (String) value;
}
super.setProperty(name, value);
}
public final static String PROPERTY_DEFAULT_ENCODING = "DEFAULT_ENCODING";
private String mDefaultEncoding;
}
|
ExtMXSerializer.setProperty(): fixed a bug, which makes impossible to set PROPERTY_DEFAULT_ENCODING.
|
src/brut/androlib/res/util/ExtMXSerializer.java
|
ExtMXSerializer.setProperty(): fixed a bug, which makes impossible to set PROPERTY_DEFAULT_ENCODING.
|
|
Java
|
bsd-3-clause
|
20e16d1dc8c4b17ba03db9adbe4f3daa8dc3b86a
| 0
|
muloem/xins,muloem/xins,muloem/xins
|
/*
* $Id$
*
* Copyright 2004 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.service;
import java.util.Iterator;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.TimeOutController;
import org.xins.common.TimeOutException;
import org.xins.common.Utils;
/**
* Abstraction of a service caller for a TCP-based service. Service caller
* implementations can be used to perform a call to a service, and potentially
* fail-over to other back-ends if one is not available. Additionally,
* load-balancing and different types of time-outs are supported.
*
* <p>Back-ends are
* represented by {@link TargetDescriptor} instances. Groups of back-ends are
* represented by {@link GroupDescriptor} instances.
*
* <a name="section-lbfo"></a>
* <h2>Load-balancing and fail-over</h2>
*
* <p>TODO: Describe load-balancing and fail-over.
*
* <a name="section-timeouts"></a>
* <h2>Time-outs</h2>
*
* <p>TODO: Describe time-outs.
*
* <a name="section-callconfig"></a>
* <h2>Call configuration</h2>
*
* <p>Some aspects of a call can be configured using a {@link CallConfig}
* object. For example, the <code>CallConfig</code> base class indicates
* whether fail-over is unconditionally allowed. Like this, some aspects of
* the behaviour of the caller can be tweaked.
*
* <p>There are different places where a <code>CallConfig</code> can be
* applied:
*
* <ul>
* <li>stored in a <code>ServiceCaller</code>;
* <li>stored in a <code>CallRequest</code>;
* <li>passed with the call method.
* </ul>
*
* <p>First of all, each <code>ServiceCaller</code> instance will have a
* fall-back <code>CallConfig</code>.
*
* <p>Secondly, a {@link CallRequest} instance may have a
* <code>CallConfig</code> associated with it as well. If it does, then this
* overrides the one on the <code>ServiceCaller</code> instance.
*
* <p>Finally, a <code>CallConfig</code> can be passed as an argument to the
* call method. If it is, then this overrides any other settings.
*
* <a name="section-implementations"></a>
* <h2>Implementations</h2>
*
* <p>This class is abstract and is intended to be have service-specific
* subclasses, e.g. for HTTP, FTP, JDBC, etc.
*
* <p>Normally, a subclass should be stick to the following rules:
*
* <ol>
* <li>There should be a constructor that accepts only a {@link Descriptor}
* object. This constructor should call
* <code>super(descriptor, null)</code>. If this descriptor contains
* any {@link TargetDescriptor} instances that have an unsupported
* protocol, then an {@link UnsupportedProtocolException} should be
* thrown.
* <li>There should be a constructor that accepts both a
* {@link Descriptor} and a service-specific call config object
* (derived from {@link CallConfig}). This constructor should call
* <code>super(descriptor, callConfig)</code>. If this descriptor
* contains any {@link TargetDescriptor} instances that have an
* unsupported protocol, then an {@link UnsupportedProtocolException}
* should be thrown.
* <li>There should be a <code>call</code> method that accepts only a
* service-specific request object (derived from {@link CallRequest}).
* It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, null)</code>.
* <li>There should be a <code>call</code> method that accepts both a
* service-specific request object (derived from {@link CallRequest}).
* and a service-specific call config object (derived from
* {@link CallConfig}). It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, callConfig)</code>.
* <li>The method
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} must
* be implemented as specified.
* <li>The {@link #createCallResult(CallRequest,TargetDescriptor,long,CallExceptionList,Object) createCallResult}
* method must be implemented as specified.
* <li>To control when fail-over is applied, the method
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* may also be implemented. The implementation can assume that
* the passed {@link CallRequest} object is an instance of the
* service-specific call request class and that the passed
* {@link CallConfig} object is an instance of the service-specific
* call config class.
* </ol>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
public abstract class ServiceCaller extends Object {
// TODO: Describe typical implementation scenario, e.g. a
// SpecificCallResult call(SpecificCallRequest, SpecificCallConfig)
// method that calls doCall(CallRequest,CallConfig).
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = ServiceCaller.class.getName();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>ServiceCaller</code> object.
*
* <p>A default {@link CallConfig} object will be used.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @deprecated
* Deprecated since XINS 1.1.0.
* Use {@link #ServiceCaller(Descriptor,CallConfig)} instead. Although
* marked as deprecated, this constructor still works the same as in
* XINS 1.0.x.
* This constructor is guaranteed not to be removed before XINS 2.0.0.
*/
protected ServiceCaller(Descriptor descriptor)
throws IllegalArgumentException {
final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ')';
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("descriptor", descriptor);
// Set fields
_newStyle = false;
_descriptor = descriptor;
_callConfig = null;
_className = getClass().getName();
// Make sure the old-style (XINS 1.0) doCallImpl method is implemented
try {
doCallImpl((CallRequest) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the old-style (XINS 1.0) shouldFailOver method is implemented
try {
shouldFailOver((CallRequest) null, (Throwable) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + "java.lang.Throwable)";
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) doCallImpl method is not implemented
try {
doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) shouldFailOver method is not implemented
try {
shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
/**
* Constructs a new <code>ServiceCaller</code> with the specified
* <code>CallConfig</code>.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @param callConfig
* the {@link CallConfig} object, or <code>null</code> if the default
* should be used.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @since XINS 1.1.0
*/
protected ServiceCaller(Descriptor descriptor, CallConfig callConfig)
throws IllegalArgumentException {
final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ',' + CallConfig.class.getName() + ')';
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("descriptor", descriptor);
// Initialize all fields except callConfig
_className = getClass().getName();
_newStyle = true;
_descriptor = descriptor;
// If no CallConfig is specified, then use a default one
if (callConfig == null) {
String actualClass = getClass().getName();
String SUBJECT_METHOD = "getDefaultCallConfig()";
// Call getDefaultCallConfig() to get the default config...
try {
callConfig = getDefaultCallConfig();
// ...the method must be implemented...
} catch (MethodNotImplementedError e) {
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
// ...it should not throw any exception...
} catch (Throwable t) {
final String DETAIL = null;
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL, t);
}
// ...and it should never return null.
if (callConfig == null) {
final String DETAIL = "Method returned null, although that is disallowed by the ServiceCaller.getDefaultCallConfig() contract.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Set call configuration
_callConfig = callConfig;
// Make sure the old-style (XINS 1.0) doCallImpl method is not implemented
try {
doCallImpl((CallRequest) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the old-style (XINS 1.0) shouldFailOver method is not implemented
try {
shouldFailOver((CallRequest) null, (Throwable) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + Throwable.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) doCallImpl method is implemented
try {
doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) shouldFailOver method is implemented
try {
shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The name of the current (concrete) class. Never <code>null</code>.
*/
private final String _className;
/**
* Flag that indicates if the new-style (XINS 1.1) (since XINS 1.1.0) or the old-style (XINS 1.0)
* (XINS 1.0.0) behavior is expected from the subclass.
*/
private final boolean _newStyle;
/**
* The descriptor for this service. Cannot be <code>null</code>.
*/
private final Descriptor _descriptor;
/**
* The fall-back call config object for this service caller. Cannot be
* <code>null</code>.
*/
private final CallConfig _callConfig;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Returns the descriptor.
*
* @return
* the descriptor for this service, never <code>null</code>.
*/
public final Descriptor getDescriptor() {
return _descriptor;
}
/**
* Returns the <code>CallConfig</code> associated with this service caller.
*
* @return
* the fall-back {@link CallConfig} object for this service caller,
* never <code>null</code>.
*
* @since XINS 1.1.0
*/
public final CallConfig getCallConfig() {
return _callConfig;
}
/**
* Returns a default <code>CallConfig</code> object. This method is called
* by the <code>ServiceCaller</code> constructor if no
* <code>CallConfig</code> object was given.
*
* <p>Subclasses that support the new service calling framework (introduced
* in XINS 1.1.0) <em>must</em> override this method to return a more
* suitable <code>CallConfig</code> instance.
*
* <p>This method should never be called by subclasses.
*
* @return
* a new, appropriate, {@link CallConfig} instance, never
* <code>null</code>.
*
* @since XINS 1.1.0
*/
protected CallConfig getDefaultCallConfig() {
throw new MethodNotImplementedError();
}
/**
* Attempts to execute the specified call request on one of the target
* services, with the specified call configuration. During the execution,
* {@link TargetDescriptor Target descriptors} will be picked and passed to
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} until there
* is one that succeeds, as long as fail-over can be done (according to
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}).
*
* <p>If one of the calls succeeds, then the result is returned. If
* none succeeds or if fail-over should not be done, then a
* {@link CallException} is thrown.
*
* <p>Subclasses that want to use this method <em>must</em> implement
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)}. That
* method is called for each call attempt to a specific service target
* (represented by a {@link TargetDescriptor}).
*
* @param request
* the call request, not <code>null</code>.
*
* @param callConfig
* the call configuration, or <code>null</code> if the one defined for
* the call request should be used if specified, or otherwise the
* fall-back call configuration associated with this
* <code>ServiceCaller</code> (see {@link #getCallConfig()}).
*
* @return
* a combination of the call result and a link to the
* {@link TargetDescriptor target} that returned this result, if and
* only if one of the calls succeeded, could be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws CallException
* if all call attempts failed.
*
* @since XINS 1.1.0
*/
protected final CallResult doCall(CallRequest request,
CallConfig callConfig)
throws IllegalArgumentException, CallException {
final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ')';
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the new style
if (! _newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Determine what config to use. The argument has priority, then the one
// associated with the request and the fall-back is the one associated
// with this service caller.
if (callConfig == null) {
callConfig = request.getCallConfig();
if (callConfig == null) {
callConfig = _callConfig;
}
}
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
//
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
//
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// TODO: Improve performance, do not use an iterator?
// There should be at least one target
if (! iterator.hasNext()) {
final String SUBJECT_CLASS = _descriptor.getClass().getName();
final String SUBJECT_METHOD = "iterateTargets()";
final String DETAIL = "Descriptor returns no target descriptors.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, callConfig, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "The method " + SUBJECT_METHOD + " is not implemented although it should be.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, callConfig, exceptions);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, THIS_METHOD, null);
throw first;
}
/**
* Attempts to execute the specified call request on one of the target
* services. During the execution,
* {@link TargetDescriptor Target descriptors} will be picked and passed
* to {@link #doCallImpl(CallRequest,TargetDescriptor)} until there is one
* that succeeds, as long as fail-over can be done (according to
* {@link #shouldFailOver(CallRequest,Throwable)}).
*
* <p>If one of the calls succeeds, then the result is returned. If
* none succeeds or if fail-over should not be done, then a
* {@link CallException} is thrown.
*
* <p>Each call attempt consists of a call to
* {@link #doCallImpl(CallRequest,TargetDescriptor)}.
*
* @param request
* the call request, not <code>null</code>.
*
* @return
* a combination of the call result and a link to the
* {@link TargetDescriptor target} that returned this result, if and
* only if one of the calls succeeded, could be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws CallException
* if all call attempts failed.
*
* @deprecated
* Deprecated since XINS 1.1.0.
* Use {@link #doCall(CallRequest,CallConfig)} instead. Although marked
* as deprecated, this method still works the same as in XINS 1.0.x.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected final CallResult doCall(CallRequest request)
throws IllegalArgumentException, CallException {
final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ')';
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the old style
if (_newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
//
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
//
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// There should be at least one target
if (! iterator.hasNext()) {
final String SUBJECT_CLASS = _descriptor.getClass().getName();
final String SUBJECT_METHOD = "iterateTargets()";
final String DETAIL = "Descriptor returns no target descriptors.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
// TODO: Detail message should be reviewed
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "The method is not implemented although it should be.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, exception);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, THIS_METHOD, null);
throw first;
}
/**
* Calls the specified target using the specified subject. This method must
* be implemented by subclasses. It is called as soon as a target is
* selected to be called. If the call fails, then a {@link CallException}
* should be thrown. If the call succeeds, then the call result should be
* returned from this method.
*
* <p>Subclasses that want to use {@link #doCall(CallRequest,CallConfig)}
* <em>must</em> implement this method.
*
* @param request
* the call request to be executed, never <code>null</code>.
*
* @param callConfig
* the call config to be used, never <code>null</code>; this is
* determined by {@link #doCall(CallRequest,CallConfig)} and is
* guaranteed not to be <code>null</code>.
*
* @param target
* the target to call, cannot be <code>null</code>.
*
* @return
* the result, if and only if the call succeeded, could be
* <code>null</code>.
*
* @throws ClassCastException
* if the specified <code>request</code> object is not <code>null</code>
* and not an instance of an expected subclass of class
* {@link CallRequest}.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws CallException
* if the call to the specified target failed.
*
* @since XINS 1.1.0
*/
protected Object doCallImpl(CallRequest request,
CallConfig callConfig,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
/**
* Calls the specified target using the specified subject. This method must
* be implemented by subclasses. It is called as soon as a target is
* selected to be called. If the call fails, then a {@link CallException}
* should be thrown. If the call succeeds, then the call result should be
* returned from this method.
*
* @param request
* the call request to be executed, cannot be <code>null</code>.
*
* @param target
* the target to call, cannot be <code>null</code>.
*
* @return
* the result, if and only if the call succeeded, could be
* <code>null</code>.
*
* @throws ClassCastException
* if the specified <code>request</code> object is not <code>null</code>
* and not an instance of an expected subclass of class
* {@link CallRequest}.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws CallException
* if the call to the specified target failed.
*
* @deprecated
* Deprecated since XINS 1.1.0. Implement
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} instead
* of this method. Although deprecated, this method still works the same
* as in XINS 1.0.x.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected Object doCallImpl(CallRequest request,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
/**
* Constructs an appropriate <code>CallResult</code> object for a
* successful call attempt. This method is called from
* {@link #doCall(CallRequest)}.
*
* @param request
* the {@link CallRequest} that was to be executed, never
* <code>null</code> when called from {@link #doCall(CallRequest)}.
*
* @param succeededTarget
* the {@link TargetDescriptor} for the service that was successfully
* called, never <code>null</code> when called from
* {@link #doCall(CallRequest)}.
*
* @param duration
* the call duration in milliseconds, guaranteed to be a non-negative
* number when called from {@link #doCall(CallRequest)}.
*
* @param exceptions
* the list of {@link CallException} instances, or <code>null</code> if
* there were no call failures.
*
* @param result
* the result from the call, which is the object returned by
* {@link #doCallImpl(CallRequest,TargetDescriptor)}, can be
* <code>null</code>.
*
* @return
* a {@link CallResult} instance, never <code>null</code>.
*
* @throws ClassCastException
* if <code>request</code> and/or <code>result</code> are not of the
* correct class.
*/
protected abstract CallResult createCallResult(CallRequest request,
TargetDescriptor succeededTarget,
long duration,
CallExceptionList exceptions,
Object result)
throws ClassCastException;
/**
* Runs the specified task. If the task does not finish within the total
* time-out period, then the thread executing it is interrupted using the
* {@link Thread#interrupt()} method and a {@link TimeOutException} is
* thrown.
*
* @param task
* the task to run, cannot be <code>null</code>.
*
* @param descriptor
* the descriptor for the target on which the task is executed, cannot
* be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>task == null || descriptor == null</code>.
*
* @throws IllegalThreadStateException
* if <code>descriptor.getTotalTimeOut() > 0</code> and the task is a
* {@link Thread} which is already started.
*
* @throws SecurityException
* if the task did not finish within the total time-out period, but the
* interruption of the thread was disallowed (see
* {@link Thread#interrupt()}).
*
* @throws TimeOutException
* if the task did not finish within the total time-out period and was
* interrupted.
*/
protected final void controlTimeOut(Runnable task,
TargetDescriptor descriptor)
throws IllegalArgumentException,
IllegalThreadStateException,
SecurityException,
TimeOutException {
// Check preconditions
MandatoryArgumentChecker.check("task", task,
"descriptor", descriptor);
// Determine the total time-out
int totalTimeOut = descriptor.getTotalTimeOut();
// If there is no total time-out, then execute the task on this thread
if (totalTimeOut < 1) {
task.run();
// Otherwise a time-out controller will be used
} else {
TimeOutController.execute(task, totalTimeOut);
}
}
/**
* Determines whether a call should fail-over to the next selected target.
* This method should only be called from {@link #doCall(CallRequest)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if <code>exception instanceof
* {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param exception
* the exception caught while calling the most recently called target,
* should not be <code>null</code>.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @deprecated
* Deprecated since XINS 1.1.0. Implement
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* instead of this method.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected boolean shouldFailOver(CallRequest request,
Throwable exception) {
if (_newStyle) {
throw new MethodNotImplementedError();
}
final String THIS_METHOD = "shouldFailOver(CallRequest,Throwable)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// Determine if fail-over is applicable
boolean should = (exception instanceof ConnectionCallException);
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return should;
}
/**
* Determines whether a call should fail-over to the next selected target
* based on a request, call configuration and exception list.
* This method should only be called from
* {@link #doCall(CallRequest,CallConfig)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if
* <code>callConfig.{@link CallConfig#isFailOverAllowed() isFailOverAllowed()} || exception instanceof {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param callConfig
* the call config that is currently in use, never <code>null</code>.
*
* @param exceptions
* the current list of {@link CallException}s; never
* <code>null</code>; get the most recent one by calling
* <code>exceptions.</code>{@link CallExceptionList#last() last()}.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @since XINS 1.1.0
*/
protected boolean shouldFailOver(CallRequest request,
CallConfig callConfig,
CallExceptionList exceptions) {
final String THIS_METHOD = "shouldFailOver(CallRequest,CallConfig,CallExceptionList)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the new style
if (! _newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Determine if fail-over is applicable
boolean should = callConfig.isFailOverAllowed()
|| (exceptions.last() instanceof ConnectionCallException);
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return should;
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Error used to indicate a method should be implemented in a subclass, but
* is not.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
private static final class MethodNotImplementedError extends Error {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>MethodNotImplementedError</code>.
*/
private MethodNotImplementedError() {
// empty
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
}
}
|
src/java-common/org/xins/common/service/ServiceCaller.java
|
/*
* $Id$
*
* Copyright 2004 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.service;
import java.util.Iterator;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.TimeOutController;
import org.xins.common.TimeOutException;
import org.xins.common.Utils;
/**
* Abstraction of a service caller for a TCP-based service. Service caller
* implementations can be used to perform a call to a service, and potentially
* fail-over to other back-ends if one is not available. Additionally,
* load-balancing and different types of time-outs are supported.
*
* <p>Back-ends are
* represented by {@link TargetDescriptor} instances. Groups of back-ends are
* represented by {@link GroupDescriptor} instances.
*
* <a name="section-lbfo"></a>
* <h2>Load-balancing and fail-over</h2>
*
* <p>TODO: Describe load-balancing and fail-over.
*
* <a name="section-timeouts"></a>
* <h2>Time-outs</h2>
*
* <p>TODO: Describe time-outs.
*
* <a name="section-callconfig"></a>
* <h2>Call configuration</h2>
*
* <p>Some aspects of a call can be configured using a {@link CallConfig}
* object. For example, the <code>CallConfig</code> base class indicates
* whether fail-over is unconditionally allowed. Like this, some aspects of
* the behaviour of the caller can be tweaked.
*
* <p>There are different places where a <code>CallConfig</code> can be
* applied:
*
* <ul>
* <li>stored in a <code>ServiceCaller</code>;
* <li>stored in a <code>CallRequest</code>;
* <li>passed with the call method.
* </ul>
*
* <p>First of all, each <code>ServiceCaller</code> instance will have a
* fall-back <code>CallConfig</code>.
*
* <p>Secondly, a {@link CallRequest} instance may have a
* <code>CallConfig</code> associated with it as well. If it does, then this
* overrides the one on the <code>ServiceCaller</code> instance.
*
* <p>Finally, a <code>CallConfig</code> can be passed as an argument to the
* call method. If it is, then this overrides any other settings.
*
* <a name="section-implementations"></a>
* <h2>Implementations</h2>
*
* <p>This class is abstract and is intended to be have service-specific
* subclasses, e.g. for HTTP, FTP, JDBC, etc.
*
* <p>Normally, a subclass should be stick to the following rules:
*
* <ol>
* <li>There should be a constructor that accepts only a {@link Descriptor}
* object. This constructor should call
* <code>super(descriptor, null)</code>. If this descriptor contains
* any {@link TargetDescriptor} instances that have an unsupported
* protocol, then an {@link UnsupportedProtocolException} should be
* thrown.
* <li>There should be a constructor that accepts both a
* {@link Descriptor} and a service-specific call config object
* (derived from {@link CallConfig}). This constructor should call
* <code>super(descriptor, callConfig)</code>. If this descriptor
* contains any {@link TargetDescriptor} instances that have an
* unsupported protocol, then an {@link UnsupportedProtocolException}
* should be thrown.
* <li>There should be a <code>call</code> method that accepts only a
* service-specific request object (derived from {@link CallRequest}).
* It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, null)</code>.
* <li>There should be a <code>call</code> method that accepts both a
* service-specific request object (derived from {@link CallRequest}).
* and a service-specific call config object (derived from
* {@link CallConfig}). It should call
* {@link #doCall(CallRequest,CallConfig) doCall}<code>(request, callConfig)</code>.
* <li>The method
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} must
* be implemented as specified.
* <li>The {@link #createCallResult(CallRequest,TargetDescriptor,long,CallExceptionList,Object) createCallResult}
* method must be implemented as specified.
* <li>To control when fail-over is applied, the method
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* may also be implemented. The implementation can assume that
* the passed {@link CallRequest} object is an instance of the
* service-specific call request class and that the passed
* {@link CallConfig} object is an instance of the service-specific
* call config class.
* </ol>
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*
* @since XINS 1.0.0
*/
public abstract class ServiceCaller extends Object {
// TODO: Describe typical implementation scenario, e.g. a
// SpecificCallResult call(SpecificCallRequest, SpecificCallConfig)
// method that calls doCall(CallRequest,CallConfig).
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = ServiceCaller.class.getName();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>ServiceCaller</code> object.
*
* <p>A default {@link CallConfig} object will be used.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @deprecated
* Deprecated since XINS 1.1.0.
* Use {@link #ServiceCaller(Descriptor,CallConfig)} instead. Although
* marked as deprecated, this constructor still works the same as in
* XINS 1.0.x.
* This constructor is guaranteed not to be removed before XINS 2.0.0.
*/
protected ServiceCaller(Descriptor descriptor)
throws IllegalArgumentException {
final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ')';
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("descriptor", descriptor);
// Set fields
_newStyle = false;
_descriptor = descriptor;
_callConfig = null;
_className = getClass().getName();
// Make sure the old-style (XINS 1.0) doCallImpl method is implemented
try {
doCallImpl((CallRequest) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the old-style (XINS 1.0) shouldFailOver method is implemented
try {
shouldFailOver((CallRequest) null, (Throwable) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + "java.lang.Throwable)";
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) doCallImpl method is not implemented
try {
doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) shouldFailOver method is not implemented
try {
shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since class uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
/**
* Constructs a new <code>ServiceCaller</code> with the specified
* <code>CallConfig</code>.
*
* @param descriptor
* the descriptor of the service, cannot be <code>null</code>.
*
* @param callConfig
* the {@link CallConfig} object, or <code>null</code> if the default
* should be used.
*
* @throws IllegalArgumentException
* if <code>descriptor == null</code>.
*
* @since XINS 1.1.0
*/
protected ServiceCaller(Descriptor descriptor, CallConfig callConfig)
throws IllegalArgumentException {
final String THIS_METHOD = "<init>(" + Descriptor.class.getName() + ',' + CallConfig.class.getName() + ')';
// TRACE: Enter constructor
Log.log_1000(CLASSNAME, null);
// Check preconditions
MandatoryArgumentChecker.check("descriptor", descriptor);
// Initialize all fields except callConfig
_className = getClass().getName();
_newStyle = true;
_descriptor = descriptor;
// If no CallConfig is specified, then use a default one
if (callConfig == null) {
String actualClass = getClass().getName();
String SUBJECT_METHOD = "getDefaultCallConfig()";
// Call getDefaultCallConfig() to get the default config...
try {
callConfig = getDefaultCallConfig();
// ...the method must be implemented...
} catch (MethodNotImplementedError e) {
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since class uses new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
// ...it should not throw any exception...
} catch (Throwable t) {
final String DETAIL = null;
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL, t);
}
// ...and it should never return null.
if (callConfig == null) {
final String DETAIL = "Method returned null, although that is disallowed by the ServiceCaller.getDefaultCallConfig() contract.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Set call configuration
_callConfig = callConfig;
// Make sure the old-style (XINS 1.0) doCallImpl method is not implemented
try {
doCallImpl((CallRequest) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the old-style (XINS 1.0) shouldFailOver method is not implemented
try {
shouldFailOver((CallRequest) null, (Throwable) null);
throw new Error();
} catch (Throwable t) {
if (! (t instanceof MethodNotImplementedError)) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + Throwable.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should not be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) doCallImpl method is implemented
try {
doCallImpl((CallRequest) null, (CallConfig) null, (TargetDescriptor) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// Make sure the new-style (XINS 1.1) shouldFailOver method is implemented
try {
shouldFailOver((CallRequest) null, (CallConfig) null, (CallExceptionList) null);
throw new Error();
} catch (Throwable t) {
if (t instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "shouldFailOver(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + CallExceptionList.class.getName() + ')';
final String DETAIL = "Method " + SUBJECT_METHOD + " should be implemented since this class (" + _className + ") uses the new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
}
}
// TRACE: Leave constructor
Log.log_1002(CLASSNAME, null);
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The name of the current (concrete) class. Never <code>null</code>.
*/
private final String _className;
/**
* Flag that indicates if the new-style (XINS 1.1) (since XINS 1.1.0) or the old-style (XINS 1.0)
* (XINS 1.0.0) behavior is expected from the subclass.
*/
private final boolean _newStyle;
/**
* The descriptor for this service. Cannot be <code>null</code>.
*/
private final Descriptor _descriptor;
/**
* The fall-back call config object for this service caller. Cannot be
* <code>null</code>.
*/
private final CallConfig _callConfig;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Returns the descriptor.
*
* @return
* the descriptor for this service, never <code>null</code>.
*/
public final Descriptor getDescriptor() {
return _descriptor;
}
/**
* Returns the <code>CallConfig</code> associated with this service caller.
*
* @return
* the fall-back {@link CallConfig} object for this service caller,
* never <code>null</code>.
*
* @since XINS 1.1.0
*/
public final CallConfig getCallConfig() {
return _callConfig;
}
/**
* Returns a default <code>CallConfig</code> object. This method is called
* by the <code>ServiceCaller</code> constructor if no
* <code>CallConfig</code> object was given.
*
* <p>Subclasses that support the new service calling framework (introduced
* in XINS 1.1.0) <em>must</em> override this method to return a more
* suitable <code>CallConfig</code> instance.
*
* <p>This method should never be called by subclasses.
*
* @return
* a new, appropriate, {@link CallConfig} instance, never
* <code>null</code>.
*
* @since XINS 1.1.0
*/
protected CallConfig getDefaultCallConfig() {
throw new MethodNotImplementedError();
}
/**
* Attempts to execute the specified call request on one of the target
* services, with the specified call configuration. During the execution,
* {@link TargetDescriptor Target descriptors} will be picked and passed to
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} until there
* is one that succeeds, as long as fail-over can be done (according to
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}).
*
* <p>If one of the calls succeeds, then the result is returned. If
* none succeeds or if fail-over should not be done, then a
* {@link CallException} is thrown.
*
* <p>Subclasses that want to use this method <em>must</em> implement
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)}. That
* method is called for each call attempt to a specific service target
* (represented by a {@link TargetDescriptor}).
*
* @param request
* the call request, not <code>null</code>.
*
* @param callConfig
* the call configuration, or <code>null</code> if the one defined for
* the call request should be used if specified, or otherwise the
* fall-back call configuration associated with this
* <code>ServiceCaller</code> (see {@link #getCallConfig()}).
*
* @return
* a combination of the call result and a link to the
* {@link TargetDescriptor target} that returned this result, if and
* only if one of the calls succeeded, could be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws CallException
* if all call attempts failed.
*
* @since XINS 1.1.0
*/
protected final CallResult doCall(CallRequest request,
CallConfig callConfig)
throws IllegalArgumentException, CallException {
final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ')';
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the new style
if (! _newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// FIXME: Add unit test for Utils.getCallingClass() and Utils.getCallingMethod()
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Determine what config to use. The argument has priority, then the one
// associated with the request and the fall-back is the one associated
// with this service caller.
if (callConfig == null) {
callConfig = request.getCallConfig();
if (callConfig == null) {
callConfig = _callConfig;
}
}
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
//
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
//
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// TODO: Improve performance, do not use an iterator?
// There should be at least one target
if (! iterator.hasNext()) {
final String SUBJECT_CLASS = _descriptor.getClass().getName();
final String SUBJECT_METHOD = "iterateTargets()";
final String DETAIL = "Descriptor returns no target descriptors.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, callConfig, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "The method " + SUBJECT_METHOD + " is not implemented although it should be.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, callConfig, exceptions);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, THIS_METHOD, null);
throw first;
}
/**
* Attempts to execute the specified call request on one of the target
* services. During the execution,
* {@link TargetDescriptor Target descriptors} will be picked and passed
* to {@link #doCallImpl(CallRequest,TargetDescriptor)} until there is one
* that succeeds, as long as fail-over can be done (according to
* {@link #shouldFailOver(CallRequest,Throwable)}).
*
* <p>If one of the calls succeeds, then the result is returned. If
* none succeeds or if fail-over should not be done, then a
* {@link CallException} is thrown.
*
* <p>Each call attempt consists of a call to
* {@link #doCallImpl(CallRequest,TargetDescriptor)}.
*
* @param request
* the call request, not <code>null</code>.
*
* @return
* a combination of the call result and a link to the
* {@link TargetDescriptor target} that returned this result, if and
* only if one of the calls succeeded, could be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>request == null</code>.
*
* @throws CallException
* if all call attempts failed.
*
* @deprecated
* Deprecated since XINS 1.1.0.
* Use {@link #doCall(CallRequest,CallConfig)} instead. Although marked
* as deprecated, this method still works the same as in XINS 1.0.x.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected final CallResult doCall(CallRequest request)
throws IllegalArgumentException, CallException {
final String THIS_METHOD = "doCall(" + CallRequest.class.getName() + ')';
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the old style
if (_newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses new-style (XINS 1.1) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Check preconditions
MandatoryArgumentChecker.check("request", request);
// Keep a reference to the most recent CallException since
// setNext(CallException) needs to be called on it to make it link to
// the next one (if there is one)
CallException lastException = null;
// Maintain the list of CallExceptions
//
// This is needed if a successful result (a CallResult object) is
// returned, since it will contain references to the exceptions as well;
//
// Note that this object is lazily initialized because this code is
// performance- and memory-optimized for the successful case
CallExceptionList exceptions = null;
// Iterate over all targets
Iterator iterator = _descriptor.iterateTargets();
// There should be at least one target
if (! iterator.hasNext()) {
final String SUBJECT_CLASS = _descriptor.getClass().getName();
final String SUBJECT_METHOD = "iterateTargets()";
final String DETAIL = "Descriptor returns no target descriptors.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Loop over all TargetDescriptors
boolean shouldContinue = true;
while (shouldContinue) {
// Get a reference to the next TargetDescriptor
TargetDescriptor target = (TargetDescriptor) iterator.next();
// Call using this target
Log.log_1301(target.getURL());
Object result = null;
boolean succeeded = false;
long start = System.currentTimeMillis();
try {
// Attempt the call
result = doCallImpl(request, target);
succeeded = true;
// If the call to the target fails, store the exception and try the next
} catch (Throwable exception) {
Log.log_1302(target.getURL());
long duration = System.currentTimeMillis() - start;
// If the caught exception is not a CallException, then
// encapsulate it in one
CallException currentException;
if (exception instanceof CallException) {
currentException = (CallException) exception;
} else if (exception instanceof MethodNotImplementedError) {
// TODO: Detail message should be reviewed
final String SUBJECT_METHOD = "doCallImpl(" + CallRequest.class.getName() + ',' + CallConfig.class.getName() + ',' + TargetDescriptor.class.getName() + ')';
final String DETAIL = "The method is not implemented although it should be.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, _className, SUBJECT_METHOD, DETAIL);
} else {
currentException = new UnexpectedExceptionCallException(request, target, duration, null, exception);
}
// Link the previous exception (if there is one) to this one
if (lastException != null) {
lastException.setNext(currentException);
}
// Now set this exception as the most recent CallException
lastException = currentException;
// If this is the first exception being caught, then lazily
// initialize the CallExceptionList and keep a reference to the
// first exception
if (exceptions == null) {
exceptions = new CallExceptionList();
}
// Store the failure
exceptions.add(currentException);
// Determine whether fail-over is allowed and whether we have
// another target to fail-over to
boolean failOver = shouldFailOver(request, exception);
boolean haveNext = iterator.hasNext();
// No more targets and no fail-over
if (!haveNext && !failOver) {
Log.log_1304();
shouldContinue = false;
// No more targets but fail-over would be allowed
} else if (!haveNext) {
Log.log_1305();
shouldContinue = false;
// More targets available but fail-over is not allowed
} else if (!failOver) {
Log.log_1306();
shouldContinue = false;
// More targets available and fail-over is allowed
} else {
Log.log_1307();
shouldContinue = true;
}
}
// The call succeeded
if (succeeded) {
long duration = System.currentTimeMillis() - start;
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return createCallResult(request, target, duration, exceptions, result);
}
}
// Loop ended, call failed completely
Log.log_1303();
// Get the first exception from the list, this one should be thrown
CallException first = exceptions.get(0);
// TRACE: Leave method with exception
Log.log_1004(first, CLASSNAME, THIS_METHOD, null);
throw first;
}
/**
* Calls the specified target using the specified subject. This method must
* be implemented by subclasses. It is called as soon as a target is
* selected to be called. If the call fails, then a {@link CallException}
* should be thrown. If the call succeeds, then the call result should be
* returned from this method.
*
* <p>Subclasses that want to use {@link #doCall(CallRequest,CallConfig)}
* <em>must</em> implement this method.
*
* @param request
* the call request to be executed, never <code>null</code>.
*
* @param callConfig
* the call config to be used, never <code>null</code>; this is
* determined by {@link #doCall(CallRequest,CallConfig)} and is
* guaranteed not to be <code>null</code>.
*
* @param target
* the target to call, cannot be <code>null</code>.
*
* @return
* the result, if and only if the call succeeded, could be
* <code>null</code>.
*
* @throws ClassCastException
* if the specified <code>request</code> object is not <code>null</code>
* and not an instance of an expected subclass of class
* {@link CallRequest}.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws CallException
* if the call to the specified target failed.
*
* @since XINS 1.1.0
*/
protected Object doCallImpl(CallRequest request,
CallConfig callConfig,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
/**
* Calls the specified target using the specified subject. This method must
* be implemented by subclasses. It is called as soon as a target is
* selected to be called. If the call fails, then a {@link CallException}
* should be thrown. If the call succeeds, then the call result should be
* returned from this method.
*
* @param request
* the call request to be executed, cannot be <code>null</code>.
*
* @param target
* the target to call, cannot be <code>null</code>.
*
* @return
* the result, if and only if the call succeeded, could be
* <code>null</code>.
*
* @throws ClassCastException
* if the specified <code>request</code> object is not <code>null</code>
* and not an instance of an expected subclass of class
* {@link CallRequest}.
*
* @throws IllegalArgumentException
* if <code>target == null || request == null</code>.
*
* @throws CallException
* if the call to the specified target failed.
*
* @deprecated
* Deprecated since XINS 1.1.0. Implement
* {@link #doCallImpl(CallRequest,CallConfig,TargetDescriptor)} instead
* of this method. Although deprecated, this method still works the same
* as in XINS 1.0.x.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected Object doCallImpl(CallRequest request,
TargetDescriptor target)
throws ClassCastException, IllegalArgumentException, CallException {
throw new MethodNotImplementedError();
}
/**
* Constructs an appropriate <code>CallResult</code> object for a
* successful call attempt. This method is called from
* {@link #doCall(CallRequest)}.
*
* @param request
* the {@link CallRequest} that was to be executed, never
* <code>null</code> when called from {@link #doCall(CallRequest)}.
*
* @param succeededTarget
* the {@link TargetDescriptor} for the service that was successfully
* called, never <code>null</code> when called from
* {@link #doCall(CallRequest)}.
*
* @param duration
* the call duration in milliseconds, guaranteed to be a non-negative
* number when called from {@link #doCall(CallRequest)}.
*
* @param exceptions
* the list of {@link CallException} instances, or <code>null</code> if
* there were no call failures.
*
* @param result
* the result from the call, which is the object returned by
* {@link #doCallImpl(CallRequest,TargetDescriptor)}, can be
* <code>null</code>.
*
* @return
* a {@link CallResult} instance, never <code>null</code>.
*
* @throws ClassCastException
* if <code>request</code> and/or <code>result</code> are not of the
* correct class.
*/
protected abstract CallResult createCallResult(CallRequest request,
TargetDescriptor succeededTarget,
long duration,
CallExceptionList exceptions,
Object result)
throws ClassCastException;
/**
* Runs the specified task. If the task does not finish within the total
* time-out period, then the thread executing it is interrupted using the
* {@link Thread#interrupt()} method and a {@link TimeOutException} is
* thrown.
*
* @param task
* the task to run, cannot be <code>null</code>.
*
* @param descriptor
* the descriptor for the target on which the task is executed, cannot
* be <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>task == null || descriptor == null</code>.
*
* @throws IllegalThreadStateException
* if <code>descriptor.getTotalTimeOut() > 0</code> and the task is a
* {@link Thread} which is already started.
*
* @throws SecurityException
* if the task did not finish within the total time-out period, but the
* interruption of the thread was disallowed (see
* {@link Thread#interrupt()}).
*
* @throws TimeOutException
* if the task did not finish within the total time-out period and was
* interrupted.
*/
protected final void controlTimeOut(Runnable task,
TargetDescriptor descriptor)
throws IllegalArgumentException,
IllegalThreadStateException,
SecurityException,
TimeOutException {
// Check preconditions
MandatoryArgumentChecker.check("task", task,
"descriptor", descriptor);
// Determine the total time-out
int totalTimeOut = descriptor.getTotalTimeOut();
// If there is no total time-out, then execute the task on this thread
if (totalTimeOut < 1) {
task.run();
// Otherwise a time-out controller will be used
} else {
TimeOutController.execute(task, totalTimeOut);
}
}
/**
* Determines whether a call should fail-over to the next selected target.
* This method should only be called from {@link #doCall(CallRequest)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if <code>exception instanceof
* {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param exception
* the exception caught while calling the most recently called target,
* should not be <code>null</code>.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @deprecated
* Deprecated since XINS 1.1.0. Implement
* {@link #shouldFailOver(CallRequest,CallConfig,CallExceptionList)}
* instead of this method.
* This method is guaranteed not to be removed before XINS 2.0.0.
*/
protected boolean shouldFailOver(CallRequest request,
Throwable exception) {
if (_newStyle) {
throw new MethodNotImplementedError();
}
final String THIS_METHOD = "shouldFailOver(CallRequest,Throwable)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// Determine if fail-over is applicable
boolean should = (exception instanceof ConnectionCallException);
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return should;
}
/**
* Determines whether a call should fail-over to the next selected target
* based on a request, call configuration and exception list.
* This method should only be called from
* {@link #doCall(CallRequest,CallConfig)}.
*
* <p>This method is typically overridden by subclasses. Usually, a
* subclass first calls this method in the superclass, and if that returns
* <code>false</code> it does some additional checks, otherwise
* <code>true</code> is immediately returned.
*
* <p>The implementation of this method in class {@link ServiceCaller}
* returns <code>true</code> if and only if
* <code>callConfig.{@link CallConfig#isFailOverAllowed() isFailOverAllowed()} || exception instanceof {@link ConnectionCallException}</code>.
*
* @param request
* the request for the call, as passed to {@link #doCall(CallRequest)},
* should not be <code>null</code>.
*
* @param callConfig
* the call config that is currently in use, never <code>null</code>.
*
* @param exceptions
* the current list of {@link CallException}s; never
* <code>null</code>; get the most recent one by calling
* <code>exceptions.</code>{@link CallExceptionList#last() last()}.
*
* @return
* <code>true</code> if the call should fail-over to the next target, or
* <code>false</code> if it should not.
*
* @since XINS 1.1.0
*/
protected boolean shouldFailOver(CallRequest request,
CallConfig callConfig,
CallExceptionList exceptions) {
final String THIS_METHOD = "shouldFailOver(CallRequest,CallConfig,CallExceptionList)";
// TRACE: Enter method
Log.log_1003(CLASSNAME, THIS_METHOD, null);
// This method should only be called if the subclass uses the new style
if (! _newStyle) {
final String SUBJECT_CLASS = Utils.getCallingClass();
final String SUBJECT_METHOD = Utils.getCallingMethod();
final String DETAIL = "Method " + THIS_METHOD + " called while class " + _className + " uses old-style (XINS 1.0) constructor.";
throw Utils.logProgrammingError(CLASSNAME, THIS_METHOD, SUBJECT_CLASS, SUBJECT_METHOD, DETAIL);
}
// Determine if fail-over is applicable
boolean should = callConfig.isFailOverAllowed()
|| (exceptions.last() instanceof ConnectionCallException);
// TRACE: Leave method
Log.log_1005(CLASSNAME, THIS_METHOD, null);
return should;
}
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* Error used to indicate a method should be implemented in a subclass, but
* is not.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>)
*/
private static final class MethodNotImplementedError extends Error {
//----------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------
/**
* Constructs a new <code>MethodNotImplementedError</code>.
*/
private MethodNotImplementedError() {
// empty
}
//----------------------------------------------------------------------
// Fields
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// Methods
//----------------------------------------------------------------------
}
}
|
Removed FIXME comment, since the issue is fixed.
|
src/java-common/org/xins/common/service/ServiceCaller.java
|
Removed FIXME comment, since the issue is fixed.
|
|
Java
|
bsd-3-clause
|
54b27b6bd5ee6b649e264d7871f8174030a378e2
| 0
|
flutter/flutter-intellij,flutter/flutter-intellij,flutter/flutter-intellij,flutter/flutter-intellij,flutter/flutter-intellij
|
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.bazelTest;
import com.google.gson.*;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.GenericProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.xdebugger.*;
import com.jetbrains.lang.dart.ide.runner.ObservatoryConnector;
import com.jetbrains.lang.dart.util.DartUrlResolver;
import gnu.trove.THashSet;
import io.flutter.run.PositionMapper;
import io.flutter.settings.FlutterSettings;
import io.flutter.utils.StdoutJsonParser;
import org.dartlang.vm.service.element.ScriptRef;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Set;
/**
* The Bazel version of the {@link io.flutter.run.test.DebugTestRunner}. Runs a Bazel Flutter test configuration in the debugger.
*/
public class BazelTestRunner extends GenericProgramRunner {
private static final Logger LOG = Logger.getInstance(BazelTestRunner.class);
@NotNull
@Override
public String getRunnerId() {
return "FlutterBazelTestRunner";
}
@Override
public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
// TODO(jwren) not sure what we want here, go look at DebugTestRunner.canRun
return true;
}
@Nullable
@Override
protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env)
throws ExecutionException {
return runInDebugger((BazelTestLaunchState)state, env);
}
protected RunContentDescriptor runInDebugger(@NotNull BazelTestLaunchState launcher, @NotNull ExecutionEnvironment env)
throws ExecutionException {
// Start process and create console.
final ExecutionResult executionResult = launcher.execute(env.getExecutor(), this);
final Connector connector = new Connector(executionResult.getProcessHandler());
//// Set up source file mapping.
final DartUrlResolver resolver = DartUrlResolver.getInstance(env.getProject(), launcher.getTestFile());
final PositionMapper.Analyzer analyzer = PositionMapper.Analyzer.create(env.getProject(), launcher.getTestFile());
final BazelPositionMapper mapper =
new BazelPositionMapper(env.getProject(), env.getProject().getBaseDir()/*this is different, incorrect?*/, resolver, analyzer,
connector);
// Create the debug session.
final XDebuggerManager manager = XDebuggerManager.getInstance(env.getProject());
final XDebugSession session = manager.startSession(env, new XDebugProcessStarter() {
@Override
@NotNull
public XDebugProcess start(@NotNull final XDebugSession session) {
return new BazelTestDebugProcess(env, session, executionResult, resolver, connector, mapper);
}
});
return session.getRunContentDescriptor();
}
/**
* Provides observatory URI, as received from the test process.
*/
private static final class Connector implements ObservatoryConnector {
private final StdoutJsonParser stdoutParser = new StdoutJsonParser();
private final ProcessListener listener;
private String observatoryUri;
private String runfilesDir;
private String workspaceDirName;
public Connector(ProcessHandler handler) {
listener = new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
if (!outputType.equals(ProcessOutputTypes.STDOUT)) {
return;
}
final String text = event.getText();
if (FlutterSettings.getInstance().isVerboseLogging()) {
LOG.info("[<-- " + text.trim() + "]");
}
stdoutParser.appendOutput(text);
for (String line : stdoutParser.getAvailableLines()) {
if (line.startsWith("[{")) {
line = line.trim();
final String json = line.substring(1, line.length() - 1);
dispatchJson(json);
}
}
}
@Override
public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
handler.removeProcessListener(listener);
}
};
handler.addProcessListener(listener);
}
@Nullable
@Override
public String getWebSocketUrl() {
if (observatoryUri == null || !observatoryUri.startsWith("http:") || !observatoryUri.endsWith("/")) {
return null;
}
return observatoryUri.replace("http:", "ws:") + "ws";
}
@Nullable
@Override
public String getBrowserUrl() {
return observatoryUri;
}
@Nullable
public String getRunfilesDir() {
return runfilesDir;
}
@Nullable
public String getWorkspaceDirName() {
return workspaceDirName;
}
@Nullable
@Override
public String getRemoteBaseUrl() {
return null;
}
@Override
public void onDebuggerPaused(@NotNull Runnable resume) {
}
@Override
public void onDebuggerResumed() {
}
private void dispatchJson(String json) {
final JsonObject obj;
try {
final JsonParser jp = new JsonParser();
final JsonElement elem = jp.parse(json);
obj = elem.getAsJsonObject();
}
catch (JsonSyntaxException e) {
LOG.error("Unable to parse JSON from Flutter test", e);
return;
}
final JsonPrimitive primId = obj.getAsJsonPrimitive("id");
if (primId != null) {
// Not an event.
LOG.info("Ignored JSON from Flutter test: " + json);
return;
}
final JsonPrimitive primEvent = obj.getAsJsonPrimitive("event");
if (primEvent == null) {
LOG.error("Missing event field in JSON from Flutter test: " + obj);
return;
}
final String eventName = primEvent.getAsString();
if (eventName == null) {
LOG.error("Unexpected event field in JSON from Flutter test: " + obj);
return;
}
final JsonObject params = obj.getAsJsonObject("params");
if (params == null) {
LOG.error("Missing parameters in event from Flutter test: " + obj);
return;
}
if (eventName.equals("test.startedProcess")) {
final JsonPrimitive primUri = params.getAsJsonPrimitive("observatoryUri");
if (primUri != null) {
observatoryUri = primUri.getAsString();
}
final JsonPrimitive primRunfilesDir = params.getAsJsonPrimitive("runfilesDir");
if (primRunfilesDir != null) {
runfilesDir = primRunfilesDir.getAsString();
}
final JsonPrimitive primWorkspaceDirName = params.getAsJsonPrimitive("workspaceDirName");
if (primWorkspaceDirName != null) {
workspaceDirName = primWorkspaceDirName.getAsString();
}
}
}
}
private static final class BazelPositionMapper extends PositionMapper {
@NotNull final Connector connector;
@NotNull Set<String> workspaceLocations = new THashSet<>(1);
public static final String RUNFILES_SLASH = "runfiles/";
public BazelPositionMapper(@NotNull final Project project,
@NotNull final VirtualFile sourceRoot,
@NotNull final DartUrlResolver resolver,
@Nullable final Analyzer analyzer,
@NotNull final Connector connector) {
super(project, sourceRoot, resolver, analyzer);
this.connector = connector;
}
@NotNull
public Collection<String> getBreakpointUris(@NotNull final VirtualFile file) {
// Get the results from superclass
final Collection<String> results = super.getBreakpointUris(file);
// Get the runfiles directory and workspace directory name provided by the test harness.
final String runfilesDir = connector.getRunfilesDir();
final String workspaceDirName = connector.getWorkspaceDirName();
// Verify the returned runfiles directory and workspace directory name
if (!verifyRunFilesAndWorkspaceNameValues(runfilesDir, workspaceDirName)) {
return results;
}
final String filePath = file.getPath();
final int workspaceOffset = filePath.lastIndexOf(workspaceDirName + "/");
if (workspaceOffset != -1) {
// Append the passed runfilesDir + path from workspace to the returned results, this will set an additional breakpoint in the
// generated runfiles directory
results.add(runfilesDir + filePath.substring(workspaceOffset, filePath.length()));
// Finally, add the path to the workspace to workspaceLocations so that the original path can be computed in getSourcePosition
// method below
workspaceLocations.add(filePath.substring(0, workspaceOffset));
}
return results;
}
/**
* Returns the local position (to display to the user) corresponding to a token position in Observatory.
*/
@Override
@Nullable
public XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final ScriptRef scriptRef, int tokenPos) {
final XSourcePosition xSourcePosition = super.getSourcePosition(isolateId, scriptRef, tokenPos);
if (xSourcePosition == null) return null;
// Get the runfiles directory and workspace directpory name provided by the test harness.
final String runfilesDir = connector.getRunfilesDir();
final String workspaceDirName = connector.getWorkspaceDirName();
// Verify the returned runfiles directory and workspace directory name
if (!verifyRunFilesAndWorkspaceNameValues(runfilesDir, workspaceDirName)) return xSourcePosition;
// Get the virtual file computed by the super.getSourcePosition(...)
final VirtualFile superVirtualFile = xSourcePosition.getFile();
final String filePath = superVirtualFile.getPath();
final int workspaceOffset = filePath.lastIndexOf(workspaceDirName + "/");
if (filePath.startsWith(runfilesDir) && workspaceOffset != -1) {
for (String workspaceLoc : workspaceLocations) {
final VirtualFile virtualFileInProject =
LocalFileSystem.getInstance().findFileByPath(workspaceLoc + filePath.substring(workspaceOffset, filePath.length()));
if (virtualFileInProject != null) {
return XDebuggerUtil.getInstance().createPosition(virtualFileInProject, xSourcePosition.getLine(), xSourcePosition.getOffset());
}
}
}
return xSourcePosition;
}
/**
* Return true if the passed runfilesDir and workspaceDirName are not null, are not empty, and the runfilesDir ends with
* {@value RUNFILES_SLASH}.
*/
private boolean verifyRunFilesAndWorkspaceNameValues(@Nullable final String runfilesDir, @Nullable final String workspaceDirName) {
return runfilesDir != null && runfilesDir.endsWith(RUNFILES_SLASH) && workspaceDirName != null && !workspaceDirName.isEmpty();
}
}
}
|
src/io/flutter/run/bazelTest/BazelTestRunner.java
|
/*
* Copyright 2018 The Chromium Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package io.flutter.run.bazelTest;
import com.google.gson.*;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.GenericProgramRunner;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.xdebugger.XDebugProcess;
import com.intellij.xdebugger.XDebugProcessStarter;
import com.intellij.xdebugger.XDebugSession;
import com.intellij.xdebugger.XDebuggerManager;
import com.jetbrains.lang.dart.ide.runner.ObservatoryConnector;
import com.jetbrains.lang.dart.util.DartUrlResolver;
import io.flutter.run.PositionMapper;
import io.flutter.settings.FlutterSettings;
import io.flutter.utils.StdoutJsonParser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
/**
* The Bazel version of the {@link io.flutter.run.test.DebugTestRunner}. Runs a Bazel Flutter test configuration in the debugger.
*/
public class BazelTestRunner extends GenericProgramRunner {
@NotNull
@Override
public String getRunnerId() {
return "FlutterBazelTestRunner";
}
@Override
public boolean canRun(@NotNull String executorId, @NotNull RunProfile profile) {
// TODO(jwren) not sure what we want here, go look at DebugTestRunner.canRun
return true;
}
@Nullable
@Override
protected RunContentDescriptor doExecute(@NotNull RunProfileState state, @NotNull ExecutionEnvironment env)
throws ExecutionException {
return runInDebugger((BazelTestLaunchState)state, env);
}
protected RunContentDescriptor runInDebugger(@NotNull BazelTestLaunchState launcher, @NotNull ExecutionEnvironment env)
throws ExecutionException {
// Start process and create console.
final ExecutionResult executionResult = launcher.execute(env.getExecutor(), this);
final Connector connector = new Connector(executionResult.getProcessHandler());
//// Set up source file mapping.
final DartUrlResolver resolver = DartUrlResolver.getInstance(env.getProject(), launcher.getTestFile());
final PositionMapper.Analyzer analyzer = PositionMapper.Analyzer.create(env.getProject(), launcher.getTestFile());
final BazelPositionMapper mapper =
new BazelPositionMapper(env.getProject(), env.getProject().getBaseDir()/*this is different, incorrect?*/, resolver, analyzer,
connector);
// Create the debug session.
final XDebuggerManager manager = XDebuggerManager.getInstance(env.getProject());
final XDebugSession session = manager.startSession(env, new XDebugProcessStarter() {
@Override
@NotNull
public XDebugProcess start(@NotNull final XDebugSession session) {
return new BazelTestDebugProcess(env, session, executionResult, resolver, connector, mapper);
}
});
return session.getRunContentDescriptor();
}
/**
* Provides observatory URI, as received from the test process.
*/
private static final class Connector implements ObservatoryConnector {
private final StdoutJsonParser stdoutParser = new StdoutJsonParser();
private final ProcessListener listener;
private String observatoryUri;
private String runfilesDir;
private String workspaceDirName;
public Connector(ProcessHandler handler) {
listener = new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
if (!outputType.equals(ProcessOutputTypes.STDOUT)) {
return;
}
final String text = event.getText();
if (FlutterSettings.getInstance().isVerboseLogging()) {
LOG.info("[<-- " + text.trim() + "]");
}
stdoutParser.appendOutput(text);
for (String line : stdoutParser.getAvailableLines()) {
if (line.startsWith("[{")) {
line = line.trim();
final String json = line.substring(1, line.length() - 1);
dispatchJson(json);
}
}
}
@Override
public void processWillTerminate(ProcessEvent event, boolean willBeDestroyed) {
handler.removeProcessListener(listener);
}
};
handler.addProcessListener(listener);
}
@Nullable
@Override
public String getWebSocketUrl() {
if (observatoryUri == null || !observatoryUri.startsWith("http:") || !observatoryUri.endsWith("/")) {
return null;
}
return observatoryUri.replace("http:", "ws:") + "ws";
}
@Nullable
@Override
public String getBrowserUrl() {
return observatoryUri;
}
@Nullable
public String getRunfilesDir() {
return runfilesDir;
}
@Nullable
public String getWorkspaceDirName() {
return workspaceDirName;
}
@Nullable
@Override
public String getRemoteBaseUrl() {
return null;
}
@Override
public void onDebuggerPaused(@NotNull Runnable resume) {
}
@Override
public void onDebuggerResumed() {
}
private void dispatchJson(String json) {
final JsonObject obj;
try {
final JsonParser jp = new JsonParser();
final JsonElement elem = jp.parse(json);
obj = elem.getAsJsonObject();
}
catch (JsonSyntaxException e) {
LOG.error("Unable to parse JSON from Flutter test", e);
return;
}
final JsonPrimitive primId = obj.getAsJsonPrimitive("id");
if (primId != null) {
// Not an event.
LOG.info("Ignored JSON from Flutter test: " + json);
return;
}
final JsonPrimitive primEvent = obj.getAsJsonPrimitive("event");
if (primEvent == null) {
LOG.error("Missing event field in JSON from Flutter test: " + obj);
return;
}
final String eventName = primEvent.getAsString();
if (eventName == null) {
LOG.error("Unexpected event field in JSON from Flutter test: " + obj);
return;
}
final JsonObject params = obj.getAsJsonObject("params");
if (params == null) {
LOG.error("Missing parameters in event from Flutter test: " + obj);
return;
}
if (eventName.equals("test.startedProcess")) {
final JsonPrimitive primUri = params.getAsJsonPrimitive("observatoryUri");
if (primUri != null) {
observatoryUri = primUri.getAsString();
}
final JsonPrimitive primRunfilesDir = params.getAsJsonPrimitive("runfilesDir");
if (primRunfilesDir != null) {
runfilesDir = primRunfilesDir.getAsString();
}
final JsonPrimitive primWorkspaceDirName = params.getAsJsonPrimitive("workspaceDirName");
if (primWorkspaceDirName != null) {
workspaceDirName = primWorkspaceDirName.getAsString();
}
}
}
}
private static final class BazelPositionMapper extends PositionMapper {
@NotNull final Connector connector;
public static final String RUNFILES_SLASH = "runfiles/";
public BazelPositionMapper(@NotNull final Project project,
@NotNull final VirtualFile sourceRoot,
@NotNull final DartUrlResolver resolver,
@Nullable final Analyzer analyzer,
@NotNull final Connector connector) {
super(project, sourceRoot, resolver, analyzer);
this.connector = connector;
}
@NotNull
public Collection<String> getBreakpointUris(@NotNull final VirtualFile file) {
// Get the results from superclass
final Collection<String> results = super.getBreakpointUris(file);
// If a valid runfiles was provided by the test harness, append the runfiles version of the passed file for debugging.
final String runfilesDir = connector.getRunfilesDir();
final String workspaceDirName = connector.getWorkspaceDirName();
if (runfilesDir != null && runfilesDir.endsWith(RUNFILES_SLASH) && workspaceDirName != null && !workspaceDirName.isEmpty()) {
String filePath = file.getPath();
final int workspaceOffset = filePath.lastIndexOf(workspaceDirName + "/");
if (workspaceOffset != -1) {
// Trim off all directories before the workspace directory.
filePath = filePath.substring(workspaceOffset, filePath.length());
results.add(runfilesDir + filePath);
}
}
// Return the results
return results;
}
}
private static final Logger LOG = Logger.getInstance(BazelTestRunner.class);
}
|
More incremental work for commented out Bazel test run config. (#1942)
Override getSourcePosition() in BazelPositionMapper to open the correct file when a breakpoint is hit.
|
src/io/flutter/run/bazelTest/BazelTestRunner.java
|
More incremental work for commented out Bazel test run config. (#1942)
|
|
Java
|
bsd-3-clause
|
124ab6b04b0858e5e951d57028a8736b3e1c90a2
| 0
|
lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon
|
/*
* $Id: $
*/
/*
Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.ojs2;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lockss.test.*;
import org.lockss.util.ListUtil;
import org.lockss.util.PatternFloatMap;
import org.lockss.util.RegexpUtil;
import org.lockss.plugin.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.extractor.*;
import org.lockss.plugin.ArchivalUnit.*;
import org.lockss.plugin.definable.*;
import org.lockss.plugin.wrapper.WrapperUtil;
public class TestOJS2Plugin extends LockssTestCase {
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String JOURNAL_ID_KEY = ConfigParamDescr.JOURNAL_ID.getKey();
static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey();
// from au_url_poll_result_weight in plugins/src/org/lockss/plugin/ojs2/OJS2Plugin.xml
// Note diff: java regex & vs. xml &
// if it changes in the plugin, you will likely need to change the test, so verify
static final String OJS2_REPAIR_FROM_PEER_REGEXP1 =
"/(libs?|site|images|js|public|ads)/.+[.](css|eot|gif|png|jpe?g|js|svg|ttf|woff)([?]((itok|v)=)?[^&]+)?$";
static final String OJS2_REPAIR_FROM_PEER_REGEXP2 =
"/page/css([?]name=.*)?$";
private MockLockssDaemon theDaemon;
private DefinablePlugin plugin;
public TestOJS2Plugin(String msg) {
super(msg);
}
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
theDaemon = getMockLockssDaemon();
plugin = new DefinablePlugin();
plugin.initPlugin(theDaemon,
"org.lockss.plugin.ojs2.ClockssOJS2Plugin");
}
public void testGetAuNullConfig()
throws ArchivalUnit.ConfigurationException {
try {
plugin.configureAu(null, null);
fail("Didn't throw ArchivalUnit.ConfigurationException");
} catch (ArchivalUnit.ConfigurationException e) {
}
}
public void testCreateAu() {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
au.getName();
}
private DefinableArchivalUnit makeAuFromProps(Properties props)
throws ArchivalUnit.ConfigurationException {
Configuration config = ConfigurationUtil.fromProps(props);
return (DefinableArchivalUnit)plugin.configureAu(config, null);
}
public void testGetAuHandlesBadUrl()
throws ArchivalUnit.ConfigurationException, MalformedURLException {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "blah");
props.setProperty(JOURNAL_ID_KEY, "jams");
props.setProperty(YEAR_KEY, "2001");
try {
makeAuFromProps(props);
fail ("Didn't throw InstantiationException when given a bad url");
} catch (ArchivalUnit.ConfigurationException auie) {
assertNotNull(auie.getCause());
}
}
public void testGetAuConstructsProperAu()
throws ArchivalUnit.ConfigurationException, MalformedURLException {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/ojs2/");
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = makeAuFromProps(props);
assertEquals("Open Journal Systems Plugin (OJS 2.x for CLOCKSS), " +
"Base URL http://www.example.com/ojs2/, " +
"Journal ID j_id, Year 2014", au.getName());
}
public void testGetPluginId() {
assertEquals("org.lockss.plugin.ojs2." +
"ClockssOJS2Plugin",
plugin.getPluginId());
}
public void testGetAuConfigProperties() {
assertEquals(ListUtil.list(ConfigParamDescr.YEAR,
ConfigParamDescr.JOURNAL_ID,
ConfigParamDescr.BASE_URL),
plugin.getLocalAuConfigDescrs());
}
public void testGetArticleMetadataExtractor() {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
props.setProperty(JOURNAL_ID_KEY, "asdf");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
assertTrue(""+plugin.getArticleMetadataExtractor(MetadataTarget.Any(), au),
plugin.getArticleMetadataExtractor(null, au) instanceof ArticleMetadataExtractor);
assertTrue(""+plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au),
plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au) instanceof
FileMetadataExtractor
);
}
public void testGetHashFilterFactory() {
assertNull(plugin.getHashFilterFactory("BogusFilterFactory"));
assertNull(plugin.getHashFilterFactory("application/pdf"));
assertNotNull(plugin.getHashFilterFactory("text/html"));
}
public void testGetArticleIteratorFactory() {
assertTrue(WrapperUtil.unwrap(plugin.getArticleIteratorFactory())
instanceof org.lockss.plugin.ojs2.
OJS2ArticleIteratorFactory);
}
// Test the crawl rules for OJS2Plugin
public void testShouldCacheProperPages() throws Exception {
String ROOT_URL = "http://www.example.com/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// Test for pages that should get crawled
// permission page/start url
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2014", true, au);
shouldCacheTest(ROOT_URL + "j_id/gateway/clockss?year=2014", false, au);
// toc page for an issue
shouldCacheTest(ROOT_URL + "index.php/j_id/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/issue/view/123", true, au);
// article files
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
// should not get crawled - wrong journal/year
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2004", false, au);
// should not get crawled - LOCKSS
shouldCacheTest("http://lockss.stanford.edu", false, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/viewFile/123/456/%20http://foo.edu", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/3563_files", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/3563_files/3563_files/foo", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/1.gif", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/1.gif", false, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(ROOT_URL + "index.php/j_id/article/view/123/456", "UTF-8"), true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(ROOT_URL + "j_id/article/view/123/456", "UTF-8"), true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(URLEncoder.encode(ROOT_URL + "index.php/j_id/article/view/123/456", "UTF-8"), "UTF-8"), false, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(URLEncoder.encode(ROOT_URL + "j_id/article/view/123/456", "UTF-8"), "UTF-8"), false, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/all/modules/contrib/views/css/views.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX", true, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX&v=1.1", false, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu&v=1.2", false, au);
shouldCacheTest(ROOT_URL + "j_id/rt/printerFriendly/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/rt/findingReferences/123/456", false, au);
}
// Same tests with path on base_url
public void testShouldCacheProperPagesOJS2() throws Exception {
String ROOT_URL = "http://www.example.com/ojs2/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2016");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// Test for pages that should get crawled
// permission page/start url
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2016", true, au);
shouldCacheTest(ROOT_URL + "j_id/gateway/clockss?year=2016", false, au);
// toc page for an issue
shouldCacheTest(ROOT_URL + "index.php/j_id/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/issue/view/123", true, au);
// article files
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
// should not get crawled - wrong journal/year
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2004", false, au);
// should not get crawled - LOCKSS
shouldCacheTest("http://lockss.stanford.edu", false, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/viewFile/123/456/%20http://foo.edu", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/all/modules/contrib/views/css/views.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX", true, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX&v=1.1", false, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu&v=1.2", false, au);
}
private void shouldCacheTest(String url, boolean shouldCache, ArchivalUnit au) {
log.info ("shouldCacheTest url: " + url);
assertEquals(shouldCache, au.shouldBeCached(url));
}
public void testPollSpecial() throws Exception {
String ROOT_URL = "http://www.example.com/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "asdf");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// if it changes in the plugin, you will likely need to change the test, so verify
assertEquals(ListUtil.list(
OJS2_REPAIR_FROM_PEER_REGEXP1,OJS2_REPAIR_FROM_PEER_REGEXP2),
RegexpUtil.regexpCollection(au.makeRepairFromPeerIfMissingUrlPatterns()));
// make sure that's the regexp that will match to the expected url string
// this also tests the regexp (which is the same) for the weighted poll map
// Add to pattern these urls? Has not been seen as problem, yet
// "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
// "https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js",
// "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js",
// ROOT_URL + "global/styles/common.css",
// ROOT_URL + "styles/common.css",
List <String> repairList = ListUtil.list(
ROOT_URL + "public/journals/1/cover_issue_50_en_US.jpg",
ROOT_URL + "global/images/button_facebook.png",
ROOT_URL + "global/images/icon_mendeley_16x16b.gif",
ROOT_URL + "global/js/opentip-jquery-excanvas.js",
ROOT_URL + "lib/pkp/js/functions/jqueryValidatorI18n.js",
ROOT_URL + "lib/pkp/styles/lib/jqueryUi/images/ui-bg_glass_95_fef1ec_1x400.png",
ROOT_URL + "templates/images/progbg.gif",
ROOT_URL + "submission/public/journals/2/cover_issue_3_en_US.jpg",
ROOT_URL + "public/site/crosscheck_it_trans1.gif");
Pattern p1 = Pattern.compile(OJS2_REPAIR_FROM_PEER_REGEXP1);
Pattern p2 = Pattern.compile(OJS2_REPAIR_FROM_PEER_REGEXP2);
for (String urlString : repairList) {
Matcher m1 = p1.matcher(urlString);
Matcher m2 = p1.matcher(urlString);
assertEquals(urlString, true, (m1.find() || m1.find()));
}
//and this one should fail - it needs to be weighted correctly and repaired from publisher if possible
String notString = ROOT_URL + "index.php/aa/about/editorialPolicies";
Matcher m1 = p1.matcher(notString);
assertEquals(false, m1.find());
PatternFloatMap urlPollResults = au.makeUrlPollResultWeightMap();
assertNotNull(urlPollResults);
for (String urlString : repairList) {
assertEquals(0.0, urlPollResults.getMatch(urlString, (float) 1), .0001);
}
assertEquals(1.0, urlPollResults.getMatch(notString, (float) 1), .0001);
}
}
|
plugins/test/src/org/lockss/plugin/ojs2/TestOJS2Plugin.java
|
/*
* $Id: $
*/
/*
Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.ojs2;
import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lockss.test.*;
import org.lockss.util.ListUtil;
import org.lockss.util.PatternFloatMap;
import org.lockss.util.RegexpUtil;
import org.lockss.plugin.*;
import org.lockss.config.Configuration;
import org.lockss.daemon.*;
import org.lockss.extractor.*;
import org.lockss.plugin.ArchivalUnit.*;
import org.lockss.plugin.definable.*;
import org.lockss.plugin.wrapper.WrapperUtil;
public class TestOJS2Plugin extends LockssTestCase {
static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey();
static final String JOURNAL_ID_KEY = ConfigParamDescr.JOURNAL_ID.getKey();
static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey();
// from au_url_poll_result_weight in plugins/src/org/lockss/plugin/ojs2/OJS2Plugin.xml
// Note diff: java regex & vs. xml &
// if it changes in the plugin, you will likely need to change the test, so verify
static final String OJS2_REPAIR_FROM_PEER_REGEXP1 =
"/(libs?|site|images|js|public|ads)/.+[.](css|gif|png|jpe?g|js)([?]((itok|v)=)?[^&]+)?$";
static final String OJS2_REPAIR_FROM_PEER_REGEXP2 =
"/page/css([?]name=.*)?$";
private MockLockssDaemon theDaemon;
private DefinablePlugin plugin;
public TestOJS2Plugin(String msg) {
super(msg);
}
public void setUp() throws Exception {
super.setUp();
setUpDiskSpace();
theDaemon = getMockLockssDaemon();
plugin = new DefinablePlugin();
plugin.initPlugin(theDaemon,
"org.lockss.plugin.ojs2.ClockssOJS2Plugin");
}
public void testGetAuNullConfig()
throws ArchivalUnit.ConfigurationException {
try {
plugin.configureAu(null, null);
fail("Didn't throw ArchivalUnit.ConfigurationException");
} catch (ArchivalUnit.ConfigurationException e) {
}
}
public void testCreateAu() {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
au.getName();
}
private DefinableArchivalUnit makeAuFromProps(Properties props)
throws ArchivalUnit.ConfigurationException {
Configuration config = ConfigurationUtil.fromProps(props);
return (DefinableArchivalUnit)plugin.configureAu(config, null);
}
public void testGetAuHandlesBadUrl()
throws ArchivalUnit.ConfigurationException, MalformedURLException {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "blah");
props.setProperty(JOURNAL_ID_KEY, "jams");
props.setProperty(YEAR_KEY, "2001");
try {
makeAuFromProps(props);
fail ("Didn't throw InstantiationException when given a bad url");
} catch (ArchivalUnit.ConfigurationException auie) {
assertNotNull(auie.getCause());
}
}
public void testGetAuConstructsProperAu()
throws ArchivalUnit.ConfigurationException, MalformedURLException {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/ojs2/");
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = makeAuFromProps(props);
assertEquals("Open Journal Systems Plugin (OJS 2.x for CLOCKSS), " +
"Base URL http://www.example.com/ojs2/, " +
"Journal ID j_id, Year 2014", au.getName());
}
public void testGetPluginId() {
assertEquals("org.lockss.plugin.ojs2." +
"ClockssOJS2Plugin",
plugin.getPluginId());
}
public void testGetAuConfigProperties() {
assertEquals(ListUtil.list(ConfigParamDescr.YEAR,
ConfigParamDescr.JOURNAL_ID,
ConfigParamDescr.BASE_URL),
plugin.getLocalAuConfigDescrs());
}
public void testGetArticleMetadataExtractor() {
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, "http://www.example.com/");
props.setProperty(JOURNAL_ID_KEY, "asdf");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
assertTrue(""+plugin.getArticleMetadataExtractor(MetadataTarget.Any(), au),
plugin.getArticleMetadataExtractor(null, au) instanceof ArticleMetadataExtractor);
assertTrue(""+plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au),
plugin.getFileMetadataExtractor(MetadataTarget.Any(), "text/html", au) instanceof
FileMetadataExtractor
);
}
public void testGetHashFilterFactory() {
assertNull(plugin.getHashFilterFactory("BogusFilterFactory"));
assertNull(plugin.getHashFilterFactory("application/pdf"));
assertNotNull(plugin.getHashFilterFactory("text/html"));
}
public void testGetArticleIteratorFactory() {
assertTrue(WrapperUtil.unwrap(plugin.getArticleIteratorFactory())
instanceof org.lockss.plugin.ojs2.
OJS2ArticleIteratorFactory);
}
// Test the crawl rules for OJS2Plugin
public void testShouldCacheProperPages() throws Exception {
String ROOT_URL = "http://www.example.com/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// Test for pages that should get crawled
// permission page/start url
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2014", true, au);
shouldCacheTest(ROOT_URL + "j_id/gateway/clockss?year=2014", false, au);
// toc page for an issue
shouldCacheTest(ROOT_URL + "index.php/j_id/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/issue/view/123", true, au);
// article files
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
// should not get crawled - wrong journal/year
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2004", false, au);
// should not get crawled - LOCKSS
shouldCacheTest("http://lockss.stanford.edu", false, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/viewFile/123/456/%20http://foo.edu", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/3563_files", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/3563_files/3563_files/foo", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/1.gif", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/23854/3563_files/3563_files/3563_files/1.gif", false, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(ROOT_URL + "index.php/j_id/article/view/123/456", "UTF-8"), true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(ROOT_URL + "j_id/article/view/123/456", "UTF-8"), true, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(URLEncoder.encode(ROOT_URL + "index.php/j_id/article/view/123/456", "UTF-8"), "UTF-8"), false, au);
shouldCacheTest(ROOT_URL + "plugins/generic/pdfJsViewer/pdf.js/web/viewer.html?file=" +
URLEncoder.encode(URLEncoder.encode(ROOT_URL + "j_id/article/view/123/456", "UTF-8"), "UTF-8"), false, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/all/modules/contrib/views/css/views.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX", true, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX&v=1.1", false, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu&v=1.2", false, au);
shouldCacheTest(ROOT_URL + "j_id/rt/printerFriendly/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/rt/findingReferences/123/456", false, au);
}
// Same tests with path on base_url
public void testShouldCacheProperPagesOJS2() throws Exception {
String ROOT_URL = "http://www.example.com/ojs2/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "j_id");
props.setProperty(YEAR_KEY, "2016");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// Test for pages that should get crawled
// permission page/start url
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2016", true, au);
shouldCacheTest(ROOT_URL + "j_id/gateway/clockss?year=2016", false, au);
// toc page for an issue
shouldCacheTest(ROOT_URL + "index.php/j_id/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/issue/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/issue/view/123", true, au);
// article files
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/article/download/123/456", true, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/download/123", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/123/456", true, au);
// should not get crawled - wrong journal/year
shouldCacheTest(ROOT_URL + "j_id/gateway/lockss?year=2004", false, au);
// should not get crawled - LOCKSS
shouldCacheTest("http://lockss.stanford.edu", false, au);
shouldCacheTest(ROOT_URL + "index.php/j_id/article/viewFile/123/456/%20http://foo.edu", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/filelist.xml", true, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "j_id/article/view/23854/Background_files/Background_files/Background_files/Background_files/filelist.xml", false, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "modules/user/user.css?nzdhiu&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/all/modules/contrib/views/css/views.css?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4", true, au);
shouldCacheTest(ROOT_URL + "misc/jquery.js?v=1.4.4&id=1", false, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX", true, au);
shouldCacheTest(ROOT_URL + "sites/files/styles/journals/cover%20%282%29_0.png?itok=qGTU4GfX&v=1.1", false, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu", true, au);
shouldCacheTest(ROOT_URL + "sites/themes/js/j_id.js?nzdhiu&v=1.2", false, au);
}
private void shouldCacheTest(String url, boolean shouldCache, ArchivalUnit au) {
log.info ("shouldCacheTest url: " + url);
assertEquals(shouldCache, au.shouldBeCached(url));
}
public void testPollSpecial() throws Exception {
String ROOT_URL = "http://www.example.com/";
Properties props = new Properties();
props.setProperty(BASE_URL_KEY, ROOT_URL);
props.setProperty(JOURNAL_ID_KEY, "asdf");
props.setProperty(YEAR_KEY, "2014");
DefinableArchivalUnit au = null;
try {
au = makeAuFromProps(props);
}
catch (ConfigurationException ex) {
}
theDaemon.getLockssRepository(au);
// if it changes in the plugin, you will likely need to change the test, so verify
assertEquals(ListUtil.list(
OJS2_REPAIR_FROM_PEER_REGEXP1,OJS2_REPAIR_FROM_PEER_REGEXP2),
RegexpUtil.regexpCollection(au.makeRepairFromPeerIfMissingUrlPatterns()));
// make sure that's the regexp that will match to the expected url string
// this also tests the regexp (which is the same) for the weighted poll map
// Add to pattern these urls? Has not been seen as problem, yet
// "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
// "https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js",
// "https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js",
// ROOT_URL + "global/styles/common.css",
// ROOT_URL + "styles/common.css",
List <String> repairList = ListUtil.list(
ROOT_URL + "public/journals/1/cover_issue_50_en_US.jpg",
ROOT_URL + "global/images/button_facebook.png",
ROOT_URL + "global/images/icon_mendeley_16x16b.gif",
ROOT_URL + "global/js/opentip-jquery-excanvas.js",
ROOT_URL + "lib/pkp/js/functions/jqueryValidatorI18n.js",
ROOT_URL + "lib/pkp/styles/lib/jqueryUi/images/ui-bg_glass_95_fef1ec_1x400.png",
ROOT_URL + "templates/images/progbg.gif",
ROOT_URL + "submission/public/journals/2/cover_issue_3_en_US.jpg",
ROOT_URL + "public/site/crosscheck_it_trans1.gif");
Pattern p1 = Pattern.compile(OJS2_REPAIR_FROM_PEER_REGEXP1);
Pattern p2 = Pattern.compile(OJS2_REPAIR_FROM_PEER_REGEXP2);
for (String urlString : repairList) {
Matcher m1 = p1.matcher(urlString);
Matcher m2 = p1.matcher(urlString);
assertEquals(urlString, true, (m1.find() || m1.find()));
}
//and this one should fail - it needs to be weighted correctly and repaired from publisher if possible
String notString = ROOT_URL + "index.php/aa/about/editorialPolicies";
Matcher m1 = p1.matcher(notString);
assertEquals(false, m1.find());
PatternFloatMap urlPollResults = au.makeUrlPollResultWeightMap();
assertNotNull(urlPollResults);
for (String urlString : repairList) {
assertEquals(0.0, urlPollResults.getMatch(urlString, (float) 1), .0001);
}
assertEquals(1.0, urlPollResults.getMatch(notString, (float) 1), .0001);
}
}
|
Bring test in alignment with plugin
|
plugins/test/src/org/lockss/plugin/ojs2/TestOJS2Plugin.java
|
Bring test in alignment with plugin
|
|
Java
|
bsd-3-clause
|
6b7102f6fa369ebe8e4e4b471284834656a1fed4
| 0
|
berendkleinhaneveld/VTK,mspark93/VTK,berendkleinhaneveld/VTK,gram526/VTK,mspark93/VTK,candy7393/VTK,mspark93/VTK,berendkleinhaneveld/VTK,demarle/VTK,SimVascular/VTK,mspark93/VTK,sumedhasingla/VTK,hendradarwin/VTK,jmerkow/VTK,sumedhasingla/VTK,mspark93/VTK,hendradarwin/VTK,gram526/VTK,candy7393/VTK,sumedhasingla/VTK,johnkit/vtk-dev,sankhesh/VTK,johnkit/vtk-dev,jmerkow/VTK,SimVascular/VTK,demarle/VTK,sumedhasingla/VTK,mspark93/VTK,msmolens/VTK,mspark93/VTK,gram526/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,msmolens/VTK,ashray/VTK-EVM,SimVascular/VTK,johnkit/vtk-dev,ashray/VTK-EVM,ashray/VTK-EVM,demarle/VTK,SimVascular/VTK,msmolens/VTK,jmerkow/VTK,gram526/VTK,SimVascular/VTK,sankhesh/VTK,keithroe/vtkoptix,hendradarwin/VTK,hendradarwin/VTK,keithroe/vtkoptix,jmerkow/VTK,sankhesh/VTK,msmolens/VTK,ashray/VTK-EVM,johnkit/vtk-dev,sumedhasingla/VTK,msmolens/VTK,candy7393/VTK,candy7393/VTK,johnkit/vtk-dev,berendkleinhaneveld/VTK,keithroe/vtkoptix,msmolens/VTK,SimVascular/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,johnkit/vtk-dev,sankhesh/VTK,demarle/VTK,keithroe/vtkoptix,SimVascular/VTK,gram526/VTK,gram526/VTK,demarle/VTK,sankhesh/VTK,ashray/VTK-EVM,sumedhasingla/VTK,hendradarwin/VTK,candy7393/VTK,jmerkow/VTK,sumedhasingla/VTK,demarle/VTK,ashray/VTK-EVM,msmolens/VTK,sankhesh/VTK,gram526/VTK,msmolens/VTK,sumedhasingla/VTK,jmerkow/VTK,keithroe/vtkoptix,gram526/VTK,sankhesh/VTK,SimVascular/VTK,hendradarwin/VTK,berendkleinhaneveld/VTK,demarle/VTK,jmerkow/VTK,keithroe/vtkoptix,mspark93/VTK,keithroe/vtkoptix,candy7393/VTK,ashray/VTK-EVM,keithroe/vtkoptix,sankhesh/VTK,jmerkow/VTK,candy7393/VTK,demarle/VTK,hendradarwin/VTK,candy7393/VTK
|
package vtk.rendering;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
/**
* This class implement vtkEventInterceptor with no event interception at all.
*
* @see {@link MouseMotionListener} {@link MouseListener} {@link MouseWheelListener}
* {@link KeyListener}
*
* @author Sebastien Jourdain - sebastien.jourdain@kitware.com, Kitware Inc 2013
*/
public class vtkAbstractEventInterceptor implements vtkEventInterceptor {
public boolean keyPressed(KeyEvent e) {
return false;
}
public boolean keyReleased(KeyEvent e) {
return false;
}
public boolean keyTyped(KeyEvent e) {
return false;
}
public boolean mouseDragged(MouseEvent e) {
return false;
}
public boolean mouseMoved(MouseEvent e) {
return false;
}
public boolean mouseClicked(MouseEvent e) {
return false;
}
public boolean mouseEntered(MouseEvent e) {
return false;
}
public boolean mouseExited(MouseEvent e) {
return false;
}
public boolean mousePressed(MouseEvent e) {
return false;
}
public boolean mouseReleased(MouseEvent e) {
return false;
}
public boolean mouseWheelMoved(MouseWheelEvent e) {
return false;
}
}
|
Wrapping/Java/vtk/rendering/vtkAbstractEventInterceptor.java
|
package vtk.rendering;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
/**
* This class implement vtkEventInterceptor with no event interception at all.
*
* @see {@link MouseMotionListener} {@link MouseListener} {@link MouseWheelListener}
* {@link KeyListener}
*
* @author Sebastien Jourdain - sebastien.jourdain@kitware.com, Kitware Inc 2013
*/
public class vtkAbstractEventInterceptor implements vtkEventInterceptor {
@Override
public boolean keyPressed(KeyEvent e) {
return false;
}
@Override
public boolean keyReleased(KeyEvent e) {
return false;
}
@Override
public boolean keyTyped(KeyEvent e) {
return false;
}
@Override
public boolean mouseDragged(MouseEvent e) {
return false;
}
@Override
public boolean mouseMoved(MouseEvent e) {
return false;
}
@Override
public boolean mouseClicked(MouseEvent e) {
return false;
}
@Override
public boolean mouseEntered(MouseEvent e) {
return false;
}
@Override
public boolean mouseExited(MouseEvent e) {
return false;
}
@Override
public boolean mousePressed(MouseEvent e) {
return false;
}
@Override
public boolean mouseReleased(MouseEvent e) {
return false;
}
@Override
public boolean mouseWheelMoved(MouseWheelEvent e) {
return false;
}
}
|
Remove @Override annotation to prevent compilation issue on old Java compiler
Change-Id: I9ed0e8423f5ae028294d773799979865e0dd4e8f
|
Wrapping/Java/vtk/rendering/vtkAbstractEventInterceptor.java
|
Remove @Override annotation to prevent compilation issue on old Java compiler
|
|
Java
|
mit
|
e1eb4570ca41228476eb8ae8c4385aa5812a525e
| 0
|
openforis/collect-earth,openforis/collect-earth,openforis/collect-earth
|
/**
*
*/
package org.openforis.collect.model.proxy;
import java.util.List;
import org.openforis.collect.Proxy;
import org.openforis.collect.ProxyContext;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.NodeChangeSet;
/**
* @author S. Ricci
*
*/
public class NodeChangeSetProxy implements Proxy {
private NodeChangeSet changeSet;
private CollectRecord record;
private boolean recordSaved;
private ProxyContext context;
public NodeChangeSetProxy(CollectRecord record, NodeChangeSet changeSet, ProxyContext context) {
super();
this.record = record;
this.changeSet = changeSet;
this.context = context;
}
public List<NodeChangeProxy<?>> getChanges() {
return NodeChangeProxy.fromList(changeSet.getChanges(), context);
}
public boolean isRecordSaved() {
return recordSaved;
}
public void setRecordSaved(boolean recordSaved) {
this.recordSaved = recordSaved;
}
public Integer getErrors() {
return record.getErrors();
}
public Integer getSkipped() {
return record.getSkipped();
}
public Integer getMissing() {
return record.getMissing();
}
public Integer getWarnings() {
return record.getWarnings();
}
public Integer getMissingErrors() {
return record.getMissingErrors();
}
public Integer getMissingWarnings() {
return record.getMissingWarnings();
}
}
|
collect-earth/collect-earth-app/src/main/java/org/openforis/collect/model/proxy/NodeChangeSetProxy.java
|
/**
*
*/
package org.openforis.collect.model.proxy;
import java.util.List;
import org.openforis.collect.Proxy;
import org.openforis.collect.ProxyContext;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.NodeChangeSet;
/**
* @author S. Ricci
*
*/
public class NodeChangeSetProxy implements Proxy {
private transient NodeChangeSet changeSet;
private transient CollectRecord record;
private boolean recordSaved;
private ProxyContext context;
public NodeChangeSetProxy(CollectRecord record, NodeChangeSet changeSet, ProxyContext context) {
super();
this.record = record;
this.changeSet = changeSet;
this.context = context;
}
public List<NodeChangeProxy<?>> getChanges() {
return NodeChangeProxy.fromList(changeSet.getChanges(), context);
}
public boolean isRecordSaved() {
return recordSaved;
}
public void setRecordSaved(boolean recordSaved) {
this.recordSaved = recordSaved;
}
public Integer getErrors() {
return record.getErrors();
}
public Integer getSkipped() {
return record.getSkipped();
}
public Integer getMissing() {
return record.getMissing();
}
public Integer getWarnings() {
return record.getWarnings();
}
public Integer getMissingErrors() {
return record.getMissingErrors();
}
public Integer getMissingWarnings() {
return record.getMissingWarnings();
}
}
|
code cleaning
|
collect-earth/collect-earth-app/src/main/java/org/openforis/collect/model/proxy/NodeChangeSetProxy.java
|
code cleaning
|
|
Java
|
mit
|
4da9ccb90694b869a364cd1c7e3e86b6db4361b4
| 0
|
CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab
|
package org.xcolab.service.content.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.xcolab.client.content.pojo.FileEntryWrapper;
import org.xcolab.client.content.pojo.IFileEntry;
import org.xcolab.model.tables.pojos.FileEntryImpl;
import org.xcolab.service.content.domain.fileentry.FileEntryDao;
import org.xcolab.service.content.providers.PersistenceProvider;
import java.nio.charset.Charset;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@WebMvcTest(ContentController.class)
@ComponentScan("org.xcolab.service.content")
@ComponentScan("com.netflix.discovery")
@ActiveProfiles("test")
public class FilesControllerTest {
@Mock
private FileEntryDao fileEntryDao;
@Mock
private PersistenceProvider persistenceProvider;
private MockMvc mockMvc;
private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
@Autowired
ObjectMapper objectMapper;
@InjectMocks
private FileController controller;
@Before
public void before() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void shouldCreateNewFileEntryDao() throws Exception {
IFileEntry fileEntry = new FileEntryImpl();
fileEntry.setId(12L);
FileEntryWrapper wrapper = new FileEntryWrapper(fileEntry, new byte[0], "");
this.mockMvc.perform(
post("/fileEntries")
.contentType(contentType).accept(contentType)
.content(objectMapper.writeValueAsString(wrapper)))
.andExpect(status().isOk());
Mockito.verify(fileEntryDao, Mockito.times(1)).create(Mockito.any(IFileEntry.class));
Mockito.verify(persistenceProvider, Mockito.times(1))
.saveFileToFinalDestination(new byte[0], null, "");
}
@Test
public void shouldGetFileEntryDao() throws Exception {
IFileEntry fileEntry = new FileEntryImpl();
fileEntry.setId(12L);
Mockito.when(fileEntryDao.get(Mockito.anyLong())).thenReturn(fileEntry);
this.mockMvc.perform(
get("/fileEntries/123")
.contentType(contentType).accept(contentType))
.andExpect(status().isOk());
Mockito.verify(fileEntryDao, Mockito.times(1)).get(123L);
}
}
|
microservices/services/content-service/src/test/java/org/xcolab/service/content/web/FilesControllerTest.java
|
package org.xcolab.service.content.web;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.xcolab.client.content.pojo.FileEntryWrapper;
import org.xcolab.client.content.pojo.IFileEntry;
import org.xcolab.model.tables.pojos.FileEntryImpl;
import org.xcolab.service.content.domain.fileentry.FileEntryDao;
import org.xcolab.service.content.providers.PersistenceProvider;
import java.nio.charset.Charset;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@WebMvcTest(ContentController.class)
@ComponentScan("org.xcolab.service.content")
@ComponentScan("com.netflix.discovery")
@ActiveProfiles("test")
public class FilesControllerTest {
@Mock
private FileEntryDao fileEntryDao;
@Mock
private PersistenceProvider persistenceProvider;
private MockMvc mockMvc;
private final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
@Autowired
ObjectMapper objectMapper;
@InjectMocks
private FileController controller;
@Before
public void before() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void shouldCreateNewFileEntryDao() throws Exception {
IFileEntry fileEntry = new FileEntryImpl();
fileEntry.setId(12L);
FileEntryWrapper wrapper = new FileEntryWrapper(fileEntry, new byte[0], "");
this.mockMvc.perform(
post("/fileEntries")
.contentType(contentType).accept(contentType)
.content(objectMapper.writeValueAsString(wrapper)))
.andExpect(status().isOk());
Mockito.verify(fileEntryDao, Mockito.times(1)).create(Mockito.any(IFileEntry.class));
Mockito.verify(persistenceProvider, Mockito.times(1))
.saveFileToFinalDestination(new byte[0], null, "");
}
@Test
public void shouldGetFileEntryDao() throws Exception {
IFileEntry fileEntry = new FileEntryImpl();
fileEntry.setId(12L);
this.mockMvc.perform(
get("/fileEntries/123")
.contentType(contentType).accept(contentType)
.content(objectMapper.writeValueAsString(fileEntry)))
.andExpect(status().isOk());
Mockito.verify(fileEntryDao, Mockito.times(1)).get(Mockito.anyLong());
}
}
|
[COLAB-2918]-[content]: fix getFile-test by mocking the get method of the dao and not returning null
|
microservices/services/content-service/src/test/java/org/xcolab/service/content/web/FilesControllerTest.java
|
[COLAB-2918]-[content]: fix getFile-test by mocking the get method of the dao and not returning null
|
|
Java
|
mit
|
4809280ade6ed43f17c9079495664c2414264f0d
| 0
|
myhgew/JGame_oogasalad,myhgew/JGame_oogasalad
|
package jgame;
import jgame.impl.JGEngineInterface;
import jgame.impl.Animation;
// import java.awt.*;
// import java.awt.image.ImageObserver;
// import java.io.Serializable;
// import java.net.*;
/**
* Superclass for game objects, override to define animated game objects.
* When an object is created, it is automatically registered with the
* currently running engine. The object will become active only after the
* frame ends. The object is managed by the engine, which will display it and
* call the move and hit methods when appropriate. Call remove() to remove
* the object. It will be removed after the frame ends. Use isAlive()
* to see if the object has been removed or not.
*
* <p>
* Each object corresponds to one image. The object's appearance can be changed using setImage or
* any of the animation functions. If you want multi-image objects, use multiple objects and
* co-reference them using regular references or using JGEngine's getObject(). You can also define
* your own paint() method to generate any appearance you want.
*
* <p>
* Objects have a pointer to the engine by which they are managed (eng). This can be used to call
* the various useful methods in the engine. Alternatively, the objects can be made inner classes of
* your JGEngine class, so that they have direct access to all JGEngine methods.
*
* <p>
* The object remembers some of the state of the previous frame (in particular the previous position
* and bounding boxes), so that corrective action can be taken after something special happened
* (such as bumping into a wall).
*
* <P>
* Objects have a direction and speed built in. After their move() method finishes, their x and y
* position are incremented with the given speed/direction. Speed may be used as absolute value
* (leave the direction at 1), or as a value relative to the direction (the movement is speed*dir).
* The object speed is automatically multiplied by the game speed (which has default 1.0).
*
* <P>
* Objects can be suspended, which may be useful for having them sleep until they come into view.
* When suspended, they are invisible, and their move, hit, and paint methods are not called. Also,
* they will not expire. They can still be counted by countObjects and removed by removeObjects, if
* you choose to do so. By default, objects resume operation when they enter the view. This can be
* disabled by means of the resume_in_view setting. An object that has suspend_off_view enabled will
* be suspended immediately at creation when it is off view.
*/
public class JGObject {
static int next_id = 0;
/** global which might be accessed concurrently */
static JGEngineInterface default_engine = null;
public float alpha=1f;
/**
* The engine's viewWidth and viewHeight, stored in a local variable
* for extra speed.
*/
public static int viewwidth, viewheight;
/**
* The engine's tileWidth and tileHeight, stored in a local variable
* for extra speed.
*/
public static int tilewidth, tileheight;
/**
* The engine's pfWrap settings, stored in a local variable
* for extra speed.
*/
public static boolean pfwrapx, pfwrapy;
/**
* The engine's gamespeed setting, stored in a local variable
* for extra speed.
*/
public static double gamespeed;
/**
* The engine's pfWidth/pfHeight, stored in a local variable
* for extra speed.
*/
public static int pfwidth, pfheight;
/**
* The engine's viewX/YOfs, stored in a local variable
* for extra speed.
*/
public static int viewxofs, viewyofs;
/**
* Set the engine to connect to when a new object is created. This
* should be called only by the JGEngine implementation.
*
* @param engine pass null to indicate the engine has exited.
* @return true if success; false if other engine already running.
*/
public static boolean setEngine (JGEngineInterface engine) {
if (engine == null) {
default_engine = null;
return true;
}
if (default_engine != null) return false;
default_engine = engine;
// copy some constants from engine for fast access
viewwidth = engine.viewWidth();
viewheight = engine.viewHeight();
tilewidth = engine.tileWidth();
tileheight = engine.tileHeight();
updateEngineSettings();
return true;
}
/**
* Called automatically by the engine to signal changes to pfWrap,
* gameSpeed, pfWidth/Height, viewX/YOfs. The current values of these
* settings are stored in the JGObject local variables.
*/
public static void updateEngineSettings () {
pfwrapx = default_engine.pfWrapX();
pfwrapy = default_engine.pfWrapY();
gamespeed = default_engine.getGameSpeed();
pfwidth = default_engine.pfWidth();
pfheight = default_engine.pfHeight();
viewxofs = default_engine.viewXOfs();
viewyofs = default_engine.viewYOfs();
}
// remove object creation when changing anim
/** Print a message to the debug channel, using the object ID as source */
public void dbgPrint (String msg) {
eng.dbgPrint(name, msg);
}
/** Expiry value: never expire. */
public static final int expire_never = -1;
/** Expiry value: expire when off playfield. */
public static final int expire_off_pf = -2;
/** Expiry value: expire when out of view. */
public static final int expire_off_view = -3;
/** Expiry value: suspend when out of view. */
public static final int suspend_off_view = -4;
/**
* Expiry value: suspend when out of view and expire when out of
* playfield.
*/
public static final int suspend_off_view_expire_off_pf = -5;
/** Object position */
public double x = 0, y = 0;
/** Object speed; default=0 */
public double xspeed = 0, yspeed = 0;
/** Object direction, is multiplied with speed; default=1 */
public int xdir = 1, ydir = 1;
/** Collision ID */
public int colid;
/**
* Object's global identifier; may not change during the lifetime of the
* object.
*/
String name;
/**
* Number of move() steps before object removes itself, -1 (default)
* is never; -2 means expire when off-playfield, -3 means expire when
* off-view, -4 means suspend when off-view, -5 means suspend when
* off-view and expire when off-playfield. See also the expire_ and
* suspend_ constants.
*/
public double expiry = -1;
/**
* If true, object will automatically start() when it is suspended and in
* view. Default is true.
*/
public boolean resume_in_view = true;
private boolean is_alive = true;
/** Indicates if object is suspended. */
public boolean is_suspended = false;
/** Get object's ID */
public String getName () {
return name;
}
/** Get name of current image. */
public String getImageName () {
return imgname;
}
String imgname = null;
Animation anim = null; /* will update imgname if set */
String animid = null;
/**
* cached value: has to be recomputed when image changes; simply set to
* null to do this.
*/
JGRectangle imgbbox = null;
/**
* tile bbox is the bbox with offset 0; we have to add the current
* coordinate to obtain the actual tile bbox. Set to null to use regular
* bbox instead.
*/
JGRectangle tilebbox = null;
/** The bbox that should override the image bbox if not null. */
JGRectangle bbox = null;
/**
* You can use this to call methods in the object's engine. Even handier
* is to have the objects as inner class of the engine.
*/
public JGEngineInterface eng;
/* dimensions of last time drawn */
double lastx = 0, lasty = 0;
/* bbox/tilebbox is copied into these variables each time */
JGRectangle lastbbox_copy = new JGRectangle();
JGRectangle lasttilebbox_copy = new JGRectangle();
/*
* These are equal to lastbbox_copy if bbox was defined, or null
* otherwise.
*/
JGRectangle lastbbox = null;
JGRectangle lasttilebbox = null; /* actual coordinates */
private void initObject (JGEngineInterface engine,
String name, int collisionid) {
this.eng = engine;
this.name = name;
colid = collisionid;
// XXX the test on suspend should really be done after the
// constructor of the subclass is finished, in case the position is
// changed later in the constructor.
if ((int) expiry == suspend_off_view
|| (int) expiry == suspend_off_view_expire_off_pf) {
if (!isInView(eng.getOffscreenMarginX(), eng.getOffscreenMarginY()))
suspend();
}
eng.markAddObject(this);
}
/** Clear tile bbox definition so that we use the regular bbox again. */
public void clearTileBBox () {
tilebbox = null;
}
public void setTileBBox (int x, int y, int width, int height) {
tilebbox = new JGRectangle(x, y, width, height);
}
/** Set bbox definition to override the image bbox. */
public void setBBox (int x, int y, int width, int height) {
bbox = new JGRectangle(x, y, width, height);
}
/** Clear bbox definition so that we use the image bbox again. */
public void clearBBox () {
bbox = null;
}
// /** Set object's tile span by defining the number of tiles and the margin
// * by which the object's position is snapped for determining the object's
// * top left position. */
// public void setTiles(int xtiles,int ytiles,int gridsnapx,int gridsnapy){
// this.xtiles=xtiles;
// this.ytiles=ytiles;
// this.gridsnapx=gridsnapx;
// this.gridsnapy=gridsnapy;
// }
public void setPos (double x, double y) {
this.x = x;
this.y = y;
}
/**
* Set absolute speed. Set xdir, ydir to the sign of the supplied speed,
* and xspeed and yspeed to the absolute value of the supplied speed.
* Passing a value of exactly 0.0 sets the dir to 0.
*/
public void setSpeedAbs (double xspeed, double yspeed) {
if (xspeed < 0.0) {
xdir = -1;
this.xspeed = -xspeed;
}
else if (xspeed == 0.0) {
xdir = 0;
this.xspeed = 0;
}
else {
xdir = 1;
this.xspeed = xspeed;
}
if (yspeed < 0.0) {
ydir = -1;
this.yspeed = -yspeed;
}
else if (yspeed == 0.0) {
ydir = 0;
this.yspeed = 0;
}
else {
ydir = 1;
this.yspeed = yspeed;
}
}
/** Set speed and direction in one go. */
public void setDirSpeed (int xdir, int ydir, double xspeed, double yspeed) {
this.xdir = xdir;
this.ydir = ydir;
this.xspeed = xspeed;
this.yspeed = yspeed;
}
/** Set speed and direction in one go. */
public void setDirSpeed (int xdir, int ydir, double speed) {
this.xdir = xdir;
this.ydir = ydir;
this.xspeed = speed;
this.yspeed = speed;
}
/** Set relative speed; the values are copied into xspeed,yspeed. */
public void setSpeed (double xspeed, double yspeed) {
this.xspeed = xspeed;
this.yspeed = yspeed;
}
/** Set relative speed; the value is copied into xspeed,yspeed. */
public void setSpeed (double speed) {
this.xspeed = speed;
this.yspeed = speed;
}
/** Set direction. */
public void setDir (int xdir, int ydir) {
this.xdir = xdir;
this.ydir = ydir;
}
/**
* Set ID of animation or image to display. First, look for an animation
* with the given ID, and setAnim if found. Otherwise, look for an image
* with the given ID, and setImage if found. Passing null clears the
* image and stops the animation.
*/
public void setGraphic (String gfxname) {
if (gfxname == null) {
setImage(gfxname);
}
else {
Animation newanim = eng.getAnimation(gfxname);
if (newanim != null) {
setAnim(gfxname);
}
else {
setImage(gfxname);
}
}
}
/**
* Set ID of image to display; clear animation. Passing null clears
* the image.
*/
public void setImage (String imgname) {
this.imgname = imgname;
imgbbox = null;
anim = null;
animid = null;
// stopAnim();
}
/** Get object's current animation ID, or image ID if not defined. */
public String getGraphic () {
if (animid != null) return animid;
return imgname;
}
/* animation */
/**
* Set the animation to the given default animation definition, or leave
* it as it was if the anim_id is unchanged. Subsequent changes made in
* the animation's parameters do not change the default animation
* definition. The changes will be preserved if another call to
* setAnimation is made with the same anim_id. If you want to reset the
* animation to the original settings, use resetAnimation().
*/
public void setAnim (String anim_id) {
if (animid == null || !animid.equals(anim_id)) {
anim = eng.getAnimation(anim_id);
if (anim == null) {
eng.dbgPrint(name, "Warning: animation " + anim_id + " not found.");
return;
}
anim = anim.copy();
animid = anim_id;
imgname = anim.getCurrentFrame();
}
}
/**
* Always set the animation to the given default animation definition,
* resetting any changes or updates made to the animation. Subsequent
* changes made in the animation's parameters do not change the default
* animation definition.
*/
public void resetAnim (String anim_id) {
anim = eng.getAnimation(anim_id).copy();
animid = anim_id;
}
/** Clear the animation, the object's current image will remain. */
public void clearAnim () {
anim = null;
animid = null;
}
/** Get the ID of the currently running animation. */
public String getAnimId () {
return animid;
}
// public void setAnimIncrement(int increment) {
// if (anim!=null) anim.increment=increment;
// }
/**
* Set animation speed; speed may be less than 0, indicating that
* animation should go backwards.
*/
public void setAnimSpeed (double speed) {
if (anim != null) {
if (speed >= 0) {
anim.speed = speed;
anim.increment = 1;
}
else {
anim.speed = -speed;
anim.increment = -1;
}
}
}
public void setAnimPingpong (boolean pingpong) {
if (anim != null) anim.pingpong = pingpong;
}
public void startAnim () {
if (anim != null) anim.start();
}
public void stopAnim () {
if (anim != null) anim.stop();
}
/** Reset the animation's state to the start state. */
public void resetAnim () {
if (anim != null) anim.reset();
}
/**
* Create object.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname) {
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setPos(x, y);
setGraphic(gfxname);
}
/**
* Create object with given expiry.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname, int expiry) {
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setPos(x, y);
setGraphic(gfxname);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, old style. Old style constructors
* are not compatible with the JGame Flash parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
}
/**
* Create object with given tile bbox and expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
this.expiry = expiry;
}
/**
* Create object with given absolute speed, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setSpeedAbs(xspeed, yspeed);
}
/**
* Create object with given absolute speed and expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox and absolute speed, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setSpeedAbs(xspeed, yspeed);
}
/**
* Create object with given tile bbox, absolute speed, expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given direction/speed, expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int xdir, int ydir, double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, direction/speed, expiry, old
* style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
int xdir, int ydir, double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/** Flash style constructors */
/**
* Create object with given absolute speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox.x, tilebbox.y, tilebbox.width, tilebbox.height);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given direction/speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed,
int xdir, int ydir) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, direction/speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed,
int xdir, int ydir,
JGRectangle tilebbox) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox.x, tilebbox.y, tilebbox.width, tilebbox.height);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/*
* Bounding box functions. Return copies. May return null if
* image is not defined.
*/
/**
* Copy object collision bounding box in pixels into bbox_copy. Has actual
* coordinate offset. If bounding box is not defined, bbox_copy is
* unchanged.
*
* @return false if bbox is null, true if not null
*/
public boolean getBBox (JGRectangle bbox_copy) {
if (bbox != null) {
bbox_copy.x = bbox.x + (int) x;
bbox_copy.y = bbox.y + (int) y;
bbox_copy.width = bbox.width;
bbox_copy.height = bbox.height;
return true;
}
// updateImageBBox();
// inlined updateImageBBox
if (imgbbox == null && imgname != null) {
imgbbox = eng.getImageBBox(imgname);
}
if (imgbbox != null) {
bbox_copy.x = imgbbox.x + (int) x;
bbox_copy.y = imgbbox.y + (int) y;
bbox_copy.width = imgbbox.width;
bbox_copy.height = imgbbox.height;
return true;
}
return false;
}
/**
* Get object collision bounding box in pixels.
* Has actual coordinate offset.
*
* @return copy of bbox in pixel coordinates, null if no bbox
*/
public JGRectangle getBBox () {
if (bbox != null) return new JGRectangle(bbox.x + (int) x, bbox.y + (int) y,
bbox.width, bbox.height);
updateImageBBox();
if (imgbbox != null) { return new JGRectangle(imgbbox.x + (int) x, imgbbox.y + (int) y,
imgbbox.width, imgbbox.height); }
return null;
}
// JGRectangle bbox_const = new JGRectangle(0,0,0,0);
/**
* Get object collision bounding box in pixels.
* Has actual coordinate offset. Uses a fixed temp variable to store the
* bbox, so no object is created. The returned object may not be modified,
* nor its contents used after the method is re-entered.
*
* @return bbox in pixel coordinates, null if no bbox
*/
// public JGRectangle getBBoxConst() {
// if (!getBBox(bbox_const)) return null;
// return bbox_const;
// }
/**
* Get object collision bounding box in pixels of previous frame.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getLastBBox() {
// if (lastbbox==null) return null;
// return new JGRectangle(lastbbox);
// }
/**
* Get tile collision bounding box in pixels and store it in bbox_copy.
* Bounding box has actual coordinate offset. If bounding box is not
* defined, bbox_copy is unchanged.
*
* @return false when bounding box is not defined, true otherwise
*/
public boolean getTileBBox (JGRectangle bbox_copy) {
if (tilebbox == null) { return getBBox(bbox_copy); }
bbox_copy.x = (int) x + tilebbox.x;
bbox_copy.y = (int) y + tilebbox.y;
bbox_copy.width = tilebbox.width;
bbox_copy.height = tilebbox.height;
return true;
}
/**
* Get tile collision bounding box in pixels.
* Bounding box has actual coordinate offset.
*
* @return copy of bbox in pixel coordinates, null if no bbox
*/
public JGRectangle getTileBBox () {
if (tilebbox == null) return getBBox();
return new JGRectangle((int) x + tilebbox.x, (int) y + tilebbox.y,
tilebbox.width, tilebbox.height);
}
// JGRectangle tilebbox_const = new JGRectangle(0,0,0,0);
/**
* Get tile collision bounding box in pixels.
* Bounding box has actual coordinate offset. Returns reference to a
* fixed internal variable. Do not change the object returned, avoid
* re-entering this method and then using the previous value returned.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getTileBBoxConst() {
// if (tilebbox==null) {
// JGRectangle bbox = getBBoxConst();
// if (bbox==null) return null;
// tilebbox_const.copyFrom(bbox);
// return tilebbox_const;
// }
// tilebbox_const.x = (int)x+tilebbox.x;
// tilebbox_const.y = (int)y+tilebbox.y;
// tilebbox_const.width = tilebbox.width;
// tilebbox_const.height= tilebbox.height;
// return tilebbox_const;
// }
/**
* Get tile collision bounding box of previous frame.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getLastTileBBox() {
// if (lasttilebbox==null) return null;
// return new JGRectangle(lasttilebbox);
// }
/**
* Get collision bounding box of object's image (same as object's default
* bbox, note that the offset is (0,0) here).
*
* @return copy of bbox's pixel coordinates, null if no bbox
*/
public JGRectangle getImageBBox () {
updateImageBBox();
if (imgbbox == null) return null;
return new JGRectangle(imgbbox);
}
/**
* Get collision bounding box of object's image (same as object's default
* bbox, note that the offset is (0,0) here). Optimised version of
* getImageBBox(). Do not change the value of the object!
*
* @return *original* bbox's pixel coordinates, null if no bbox
*/
public JGRectangle getImageBBoxConst () {
updateImageBBox();
return imgbbox;
}
/** Update the imgbbox variable. */
void updateImageBBox () {
if (imgbbox == null && imgname != null) {
imgbbox = eng.getImageBBox(imgname);
}
}
/** Get x position of previous frame. Returns 0 if first frame. */
public double getLastX () {
return lastx;
}
/** Get y position of previous frame. Returns 0 if first frame. */
public double getLastY () {
return lasty;
}
/* snap functions */
/**
* Snap object to grid using the default gridsnap margin of
* (xspeed*gamespeed-epsilon, yspeed*gamespeed-epsilon),
* corresponding to the default is...Aligned margin.
*/
public void snapToGrid () {
x = eng.snapToGridX(x, Math.abs(xspeed * gamespeed - 0.001));
y = eng.snapToGridY(y, Math.abs(yspeed * gamespeed - 0.001));
}
/**
* Snap object to grid.
*
* @param gridsnapx margin below which to snap, 0.0 is no snap
* @param gridsnapy margin below which to snap, 0.0 is no snap
*/
public void snapToGrid (double gridsnapx, double gridsnapy) {
x = eng.snapToGridX(x, gridsnapx);
y = eng.snapToGridY(y, gridsnapy);
}
// /** Snap object to grid. */
// public void snapToGrid(int gridsnapx, int gridsnapy) {
// JGPoint p = new JGPoint((int)x,(int)y);
// eng.snapToGrid(p,gridsnapx,gridsnapy);
// x = p.x;
// y = p.y;
// }
/**
* Snap an object's tile bbox corner to grid; floats are rounded down.
* Snaps to bottom or right of object instead of top and left if the resp.
* flags are set. Note that bottom and right alignment means that the
* object's bounding box is one pixel away from crossing the tile border.
*
* @param snap_right snap the right hand side of the tile bbox
* @param snap_bottom snap the bottom of the tile bbox
*/
public void snapBBoxToGrid (double gridsnapx, double gridsnapy,
boolean snap_right, boolean snap_bottom) {
JGRectangle bbox = getTileBBox();
double bx = x + bbox.x;
double by = y + bbox.y;
if (snap_right) bx += bbox.width;
if (snap_bottom) by += bbox.height;
double bxs = eng.snapToGridX(bx, gridsnapx);
double bys = eng.snapToGridY(by, gridsnapy);
bxs -= bbox.x;
bys -= bbox.y;
if (snap_right) bxs -= bbox.width;
if (snap_bottom) bys -= bbox.height;
x = bxs;
y = bys;
}
/* bg interaction */
// temp variables used by get*Tiles and isOnScreen/PF
JGRectangle temp_bbox_copy = new JGRectangle();
// variables returned by get*Tiles
JGRectangle tiles_copy = null;
JGRectangle last_tiles_copy = null;
JGRectangle center_tiles_copy = new JGRectangle();
JGRectangle last_center_tiles_copy = null;
JGPoint center_tile_copy = null;
JGPoint tl_tile_copy = null;
/**
* Get the tile index coordinates of all the tiles that the object's
* tile bbox overlaps with. Always returns the same temp object, so no
* object creation is necessary.
*
* @return tile index coordinates, null if no bbox
*/
public JGRectangle getTiles () {
// orig: return eng.getTiles(getTileBBox());
if (!getTileBBox(temp_bbox_copy)) return null;
if (tiles_copy == null) tiles_copy = new JGRectangle();
if (eng.getTiles(tiles_copy, temp_bbox_copy))
return tiles_copy;
return null;
}
/**
* Get the tile index coordinates of the object's previous tile bbox.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox
*/
// public JGRectangle getLastTiles() {
// //orig: return eng.getTiles(getLastTileBBox());
// // XXX object creation in getLastTileBBox
// JGRectangle bbox = getLastTileBBox();
// if (bbox==null) return null;
// if (last_tiles_copy==null) last_tiles_copy = new JGRectangle();
// if (eng.getTiles(last_tiles_copy,bbox))
// return last_tiles_copy;
// return null;
// }
/** get center tiles from bbox and store them in tiles_copy */
private JGRectangle getCenterTiles (JGRectangle bbox, JGRectangle tiles_copy) {
// XXX create a getTileIndexX and Y?
// JGPoint p =
// eng.getTileIndex(bbox.x+(bbox.width/2),bbox.y+(bbox.height/2) );
int px, py;
if (bbox.x >= 0) {
px = ((bbox.x + (bbox.width / 2))
/ tilewidth) * tilewidth + tilewidth / 2;
bbox.x = tilewidth * ((px - (bbox.width / 2)) / tilewidth);
}
else {
px = ((bbox.x + (bbox.width / 2) - tilewidth + 1)
/ tilewidth) * tilewidth + tilewidth / 2;
bbox.x = tilewidth * ((px - (bbox.width / 2) - tilewidth + 1)
/ tilewidth);
}
if (bbox.y >= 0) {
py = ((bbox.y + (bbox.height / 2))
/ tileheight) * tileheight + tileheight / 2;
bbox.y = tileheight * ((py - (bbox.height / 2)) / tileheight);
}
else {
py = ((bbox.y + (bbox.height / 2) - tileheight + 1)
/ tileheight) * tileheight + tileheight / 2;
bbox.y = tileheight * ((py - (bbox.height / 2) - tileheight + 1)
/ tileheight);
}
eng.getTiles(tiles_copy, bbox);
return tiles_copy;
}
/**
* Get the tile indices spanning the tiles that the object has the
* most overlap with. The size of the span is
* always the same as size of the tile bbox in tiles. For example, if the
* tile bbox is 48x32 pixels and the tile size is 32x32 pixels, the size
* in tiles is always 1.5x1 tiles, which is rounded up to 2x1 tiles.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox is defined
*/
public JGRectangle getCenterTiles () {
if (!getTileBBox(temp_bbox_copy)) return null;
/*
* find the tile on which the center of the bounding box is located,
* that will be the center of our tile span.
*/
return getCenterTiles(temp_bbox_copy, center_tiles_copy);
}
/**
* Get the tile indices spanning the tiles that the object's last
* bounding box had the most overlap with.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox
*/
// public JGRectangle getLastCenterTiles() {
// // XXX object creation in getLastTileBBox
// JGRectangle bbox=getLastTileBBox();
// if (bbox==null) return null;
// if (last_center_tiles_copy==null)
// last_center_tiles_copy = new JGRectangle();
// return getCenterTiles(bbox,last_center_tiles_copy);
// }
/**
* Get the top left center tile of the object (that is, the x and y of
* getCenterTiles()). If the object is 1x1 tile in size, you get the
* center tile. If the object is larger, you get the top left tile of the
* center tiles.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinate, null if no tile bbox
*/
public JGPoint getCenterTile () {
if (!getTileBBox(temp_bbox_copy)) return null;
if (center_tile_copy == null) center_tile_copy = new JGPoint();
// XXX center_tiles_copy is used also
getCenterTiles(temp_bbox_copy, center_tiles_copy);
center_tile_copy.x = center_tiles_copy.x;
center_tile_copy.y = center_tiles_copy.y;
return center_tile_copy;
}
/**
* Get the topleftmost tile of the object.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinate, null if no bbox
*/
public JGPoint getTopLeftTile () {
// XXX this global is used also
JGRectangle r = getTiles();
if (r == null) return null;
if (tl_tile_copy == null) tl_tile_copy = new JGPoint();
tl_tile_copy.x = r.x;
tl_tile_copy.y = r.y;
return tl_tile_copy;
}
/**
* Returns true if both isXAligned() and isYAligned() are true.
*
* @see #isXAligned()
* @see #isYAligned()
*/
public boolean isAligned () {
return isXAligned() && isYAligned();
}
/**
* Returns true if x is distance xspeed-epsilon away from being grid
* aligned. If an object moves at its current xspeed, this method will
* always return true when the object crosses the tile alignment line, and
* return false when the object is snapped to grid, and then
* moves xspeed*gamespeed away from its aligned position.
*/
public boolean isXAligned () {
return eng.isXAligned(x, Math.abs(xspeed * gamespeed - 0.001));
}
/**
* Returns true if y is distance yspeed-epsilon away from being grid
* aligned. If an object moves at its current yspeed, this method will
* always return true when the object crosses the tile alignment line, and
* return false when the object is snapped to grid, and then
* moves yspeed*gamespeed away from its aligned position.
*/
public boolean isYAligned () {
return eng.isYAligned(y, Math.abs(yspeed * gamespeed - 0.001));
}
/**
* Returns true if x is within margin of being tile grid aligned. Epsilon
* is added to the margin, so that isXAligned(1.0000, 1.0000)
* always returns true.
*/
public boolean isXAligned (double margin) {
return eng.isXAligned(x, margin);
}
/**
* Returns true if y is within margin of being tile grid aligned. Epsilon
* is added to the margin, so that isXAligned(1.0000, 1.0000)
* always returns true.
*/
public boolean isYAligned (double margin) {
return eng.isYAligned(y, margin);
}
/**
* Returns true if the left of the object's tile bbox is within margin of
* being tile grid aligned.
*/
public boolean isLeftAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isXAligned(bbox.x, margin);
}
else {
return eng.isXAligned(x, margin);
}
}
/**
* Returns true if the top of the object's tile bbox is within margin of
* being tile grid aligned.
*/
public boolean isTopAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isYAligned(bbox.y, margin);
}
else {
return eng.isYAligned(y, margin);
}
}
/**
* Returns true if the right of the object's tile bbox is within margin of
* being tile grid aligned. Note that right aligned means that the bbox is
* one pixel away from crossing the tile border.
*/
public boolean isRightAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isXAligned(bbox.x + bbox.width, margin);
}
else {
return eng.isXAligned(x, margin);
}
}
/**
* Returns true if the bottom of the object's tile bbox is within margin of
* being tile grid aligned. Note that right aligned means that the bbox is
* one pixel away from crossing the tile border.
*/
public boolean isBottomAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isYAligned(bbox.y + bbox.height, margin);
}
else {
return eng.isYAligned(y, margin);
}
}
/**
* Check collision of this object with other objects, when the object
* position would be offset by xofs,yofs. Returns 0 when object's bbox is
* not defined.
*
* @param cid cid mask of objects to consider, 0=any
*/
public int checkCollision (int cid, double xofs, double yofs) {
double oldx = x, oldy = y;
x += xofs;
y += yofs;
int retcid = eng.checkCollision(cid, this);
x = oldx;
y = oldy;
return retcid;
}
/*
* something odd going on here: it fails to find the checkBGCollision in
* Engine when I define this one in Object
* public int checkBGCollision() {
* return eng.checkBGCollision(getTileBBox());
* }
*/
/**
* Check collision of tiles within given rectangle, return the OR of all
* cids found. This method just calls eng.checkBGCollision; it's here
* because JGEngine.checkBGCollision(JGRectangle) is masked when the object
* is an inner class of JGEngine.
*/
public int checkBGCollision (JGRectangle r) {
return eng.checkBGCollision(r);
}
/**
* Get OR of Tile Cids of the object's current tile bbox at the current
* position, when offset by the given offset. Returns 0 if tile bbox is not
* defined.
*/
public int checkBGCollision (double xofs, double yofs) {
double oldx = x, oldy = y;
x += xofs;
y += yofs;
JGRectangle bbox = getTileBBox();
x = oldx;
y = oldy;
if (bbox == null) return 0;
return checkBGCollision(bbox);
}
/**
* Margin is the margin beyond which the object is considered offscreen.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box. isOnScreen is equal to isOnPF, but is
* deprecated because the name is ambiguous.
*
* @deprecated Use isOnPF and isInView according to your situation.
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isOnScreen (int marginx, int marginy) {
return isOnPF(marginx, marginy);
}
/**
* Margin is the margin beyond which the object is considered off-view.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box.
*
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isInView (int marginx, int marginy) {
if (!getTileBBox(temp_bbox_copy)) {
temp_bbox_copy.x = (int) x;
temp_bbox_copy.y = (int) y;
temp_bbox_copy.width = 0;
temp_bbox_copy.height = 0;
}
if (temp_bbox_copy.x + temp_bbox_copy.width < viewxofs - marginx)
return false;
if (temp_bbox_copy.y + temp_bbox_copy.height < viewyofs - marginy)
return false;
if (temp_bbox_copy.x > viewxofs + viewwidth + marginx)
return false;
if (temp_bbox_copy.y > viewyofs + viewheight + marginy)
return false;
return true;
}
/**
* Margin is the margin beyond which the object is considered off the
* playfield.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box.
*
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isOnPF (int marginx, int marginy) {
if (!getTileBBox(temp_bbox_copy)) {
temp_bbox_copy.x = (int) x;
temp_bbox_copy.y = (int) y;
temp_bbox_copy.width = 0;
temp_bbox_copy.height = 0;
}
if (!pfwrapx) {
if (temp_bbox_copy.x + temp_bbox_copy.width < -marginx) return false;
if (temp_bbox_copy.x > pfwidth + marginx) return false;
}
if (!pfwrapy) {
if (temp_bbox_copy.y + temp_bbox_copy.height < -marginy) return false;
if (temp_bbox_copy.y > pfheight + marginy) return false;
}
return true;
}
/* computation */
/**
* A Boolean AND shorthand to use for collision;
* returns (value&mask) != 0.
*/
public static boolean and (int value, int mask) {
return (value & mask) != 0;
}
public double random (double min, double max) {
return eng.random(min, max);
}
public double random (double min, double max, double interval) {
return eng.random(min, max, interval);
}
public int random (int min, int max, int interval) {
return eng.random(min, max, interval);
}
/**
* Do automatic animation. Is automatically called by the JGEngine
* implementation once for every
* moveObjects; normally it is not necessary to call this.
*/
public void updateAnimation (double gamespeed) {
if (anim != null) {// && eng.canvas.anim_running) {
imgname = anim.animate(gamespeed);
imgbbox = null;
}
}
/**
* Signal that a new frame has just been updated; make
* snapshot of object state. Should only be called by the JGEngine
* implementation.
*/
public void frameFinished () {
lastx = x;
lasty = y;
// if (getBBox(lastbbox_copy)) {
// lastbbox = lastbbox_copy;
// } else {
// lastbbox=null;
// }
// if (getTileBBox(lasttilebbox_copy)) {
// lasttilebbox = lasttilebbox_copy;
// } else {
// lasttilebbox=null;
// }
}
/**
* Modulo x/y position according to wrap settings. Is automatically
* performed by the JGEngine implementation
* after each moveObjects. Normally it is not necessary to call this, but
* it may be in special cases.
*/
public void moduloPos () {
// note: there is an inlined version of this code in EngineLogic
if (pfwrapx) x = eng.moduloXPos(x);
if (pfwrapy) y = eng.moduloYPos(y);
}
/**
* Suspend object until either resume is called or, if
* resume_in_view is true, when it comes into view. A suspended object
* does not participate in any move, hit, or paint.
*/
public void suspend () {
is_suspended = true;
}
/** Resume from suspended state, if suspended. */
public void resume () {
is_suspended = false;
}
/** Check if object is suspended. */
public boolean isSuspended () {
return is_suspended;
}
/**
* Set resume condition.
*
* @param resume_in_view resume when in view
*/
public void setResumeMode (boolean resume_in_view) {
this.resume_in_view = resume_in_view;
}
/**
* Check if object is still active, or has already been removed. Also
* returns false if the object is still pending to be removed.
*/
public boolean isAlive () {
return is_alive;
}
/**
* Signal to object that remove is done, don't call directly. This is
* used by the engine to signal that the object should be finalised.
*/
public final void removeDone () {
destroy();
is_alive = false;
}
/**
* Mark object for removal, ignore if already removed.
* The object will be removed at the end of this
* moveObjects, checkCollision, or checkBGCollision action, or immediately
* if not inside either of these actions.
*/
public void remove () {
if (isAlive()) eng.removeObject(this);
is_alive = false;
}
/**
* Override to implement object disposal code. This method is called at
* the actual moment of removal.
*/
public void destroy () {
}
/**
* Override to implement automatic move; default is do nothing.
*/
public void move () {
}
/**
* Override to handle collision; default is do nothing.
*/
public void hit (JGObject obj) {
}
/**
* Override to handle tile collision; default is do nothing.
*/
public void hit_bg (int tilecid) {
}
/**
* Override to handle tile collision; default is do nothing.
* This method is always called when hit_bg(int) is also called, only, extra
* information is passed that may be useful.
*/
public void hit_bg (int tilecid, int tx, int ty, int txsize, int tysize) {
}
/**
* Override to handle tile collision; default is do nothing.
* This method is always called when hit_bg(int) is also called, only it may
* be called multiple times, namely once for each tile the object collides
* with. The arguments pass the tile cid and position of that tile. It is
* always called after hit_bg(int) and hit_bg(int,int,int,int,int) have
* been called.
*/
public void hit_bg (int tilecid, int tx, int ty) {
}
/** Override to define custom paint actions. */
public void paint () {
}
}
|
src/jgame/JGObject.java
|
package jgame;
import jgame.impl.JGEngineInterface;
import jgame.impl.Animation;
// import java.awt.*;
// import java.awt.image.ImageObserver;
// import java.io.Serializable;
// import java.net.*;
/**
* Superclass for game objects, override to define animated game objects.
* When an object is created, it is automatically registered with the
* currently running engine. The object will become active only after the
* frame ends. The object is managed by the engine, which will display it and
* call the move and hit methods when appropriate. Call remove() to remove
* the object. It will be removed after the frame ends. Use isAlive()
* to see if the object has been removed or not.
*
* <p>
* Each object corresponds to one image. The object's appearance can be changed using setImage or
* any of the animation functions. If you want multi-image objects, use multiple objects and
* co-reference them using regular references or using JGEngine's getObject(). You can also define
* your own paint() method to generate any appearance you want.
*
* <p>
* Objects have a pointer to the engine by which they are managed (eng). This can be used to call
* the various useful methods in the engine. Alternatively, the objects can be made inner classes of
* your JGEngine class, so that they have direct access to all JGEngine methods.
*
* <p>
* The object remembers some of the state of the previous frame (in particular the previous position
* and bounding boxes), so that corrective action can be taken after something special happened
* (such as bumping into a wall).
*
* <P>
* Objects have a direction and speed built in. After their move() method finishes, their x and y
* position are incremented with the given speed/direction. Speed may be used as absolute value
* (leave the direction at 1), or as a value relative to the direction (the movement is speed*dir).
* The object speed is automatically multiplied by the game speed (which has default 1.0).
*
* <P>
* Objects can be suspended, which may be useful for having them sleep until they come into view.
* When suspended, they are invisible, and their move, hit, and paint methods are not called. Also,
* they will not expire. They can still be counted by countObjects and removed by removeObjects, if
* you choose to do so. By default, objects resume operation when they enter the view. This can be
* disabled by means of the resume_in_view setting. An object that has suspend_off_view enabled will
* be suspended immediately at creation when it is off view.
*/
public class JGObject {
static int next_id = 0;
/** global which might be accessed concurrently */
static JGEngineInterface default_engine = null;
public float alpha=0.5f;
/**
* The engine's viewWidth and viewHeight, stored in a local variable
* for extra speed.
*/
public static int viewwidth, viewheight;
/**
* The engine's tileWidth and tileHeight, stored in a local variable
* for extra speed.
*/
public static int tilewidth, tileheight;
/**
* The engine's pfWrap settings, stored in a local variable
* for extra speed.
*/
public static boolean pfwrapx, pfwrapy;
/**
* The engine's gamespeed setting, stored in a local variable
* for extra speed.
*/
public static double gamespeed;
/**
* The engine's pfWidth/pfHeight, stored in a local variable
* for extra speed.
*/
public static int pfwidth, pfheight;
/**
* The engine's viewX/YOfs, stored in a local variable
* for extra speed.
*/
public static int viewxofs, viewyofs;
/**
* Set the engine to connect to when a new object is created. This
* should be called only by the JGEngine implementation.
*
* @param engine pass null to indicate the engine has exited.
* @return true if success; false if other engine already running.
*/
public static boolean setEngine (JGEngineInterface engine) {
if (engine == null) {
default_engine = null;
return true;
}
if (default_engine != null) return false;
default_engine = engine;
// copy some constants from engine for fast access
viewwidth = engine.viewWidth();
viewheight = engine.viewHeight();
tilewidth = engine.tileWidth();
tileheight = engine.tileHeight();
updateEngineSettings();
return true;
}
/**
* Called automatically by the engine to signal changes to pfWrap,
* gameSpeed, pfWidth/Height, viewX/YOfs. The current values of these
* settings are stored in the JGObject local variables.
*/
public static void updateEngineSettings () {
pfwrapx = default_engine.pfWrapX();
pfwrapy = default_engine.pfWrapY();
gamespeed = default_engine.getGameSpeed();
pfwidth = default_engine.pfWidth();
pfheight = default_engine.pfHeight();
viewxofs = default_engine.viewXOfs();
viewyofs = default_engine.viewYOfs();
}
// remove object creation when changing anim
/** Print a message to the debug channel, using the object ID as source */
public void dbgPrint (String msg) {
eng.dbgPrint(name, msg);
}
/** Expiry value: never expire. */
public static final int expire_never = -1;
/** Expiry value: expire when off playfield. */
public static final int expire_off_pf = -2;
/** Expiry value: expire when out of view. */
public static final int expire_off_view = -3;
/** Expiry value: suspend when out of view. */
public static final int suspend_off_view = -4;
/**
* Expiry value: suspend when out of view and expire when out of
* playfield.
*/
public static final int suspend_off_view_expire_off_pf = -5;
/** Object position */
public double x = 0, y = 0;
/** Object speed; default=0 */
public double xspeed = 0, yspeed = 0;
/** Object direction, is multiplied with speed; default=1 */
public int xdir = 1, ydir = 1;
/** Collision ID */
public int colid;
/**
* Object's global identifier; may not change during the lifetime of the
* object.
*/
String name;
/**
* Number of move() steps before object removes itself, -1 (default)
* is never; -2 means expire when off-playfield, -3 means expire when
* off-view, -4 means suspend when off-view, -5 means suspend when
* off-view and expire when off-playfield. See also the expire_ and
* suspend_ constants.
*/
public double expiry = -1;
/**
* If true, object will automatically start() when it is suspended and in
* view. Default is true.
*/
public boolean resume_in_view = true;
private boolean is_alive = true;
/** Indicates if object is suspended. */
public boolean is_suspended = false;
/** Get object's ID */
public String getName () {
return name;
}
/** Get name of current image. */
public String getImageName () {
return imgname;
}
String imgname = null;
Animation anim = null; /* will update imgname if set */
String animid = null;
/**
* cached value: has to be recomputed when image changes; simply set to
* null to do this.
*/
JGRectangle imgbbox = null;
/**
* tile bbox is the bbox with offset 0; we have to add the current
* coordinate to obtain the actual tile bbox. Set to null to use regular
* bbox instead.
*/
JGRectangle tilebbox = null;
/** The bbox that should override the image bbox if not null. */
JGRectangle bbox = null;
/**
* You can use this to call methods in the object's engine. Even handier
* is to have the objects as inner class of the engine.
*/
public JGEngineInterface eng;
/* dimensions of last time drawn */
double lastx = 0, lasty = 0;
/* bbox/tilebbox is copied into these variables each time */
JGRectangle lastbbox_copy = new JGRectangle();
JGRectangle lasttilebbox_copy = new JGRectangle();
/*
* These are equal to lastbbox_copy if bbox was defined, or null
* otherwise.
*/
JGRectangle lastbbox = null;
JGRectangle lasttilebbox = null; /* actual coordinates */
private void initObject (JGEngineInterface engine,
String name, int collisionid) {
this.eng = engine;
this.name = name;
colid = collisionid;
// XXX the test on suspend should really be done after the
// constructor of the subclass is finished, in case the position is
// changed later in the constructor.
if ((int) expiry == suspend_off_view
|| (int) expiry == suspend_off_view_expire_off_pf) {
if (!isInView(eng.getOffscreenMarginX(), eng.getOffscreenMarginY()))
suspend();
}
eng.markAddObject(this);
}
/** Clear tile bbox definition so that we use the regular bbox again. */
public void clearTileBBox () {
tilebbox = null;
}
public void setTileBBox (int x, int y, int width, int height) {
tilebbox = new JGRectangle(x, y, width, height);
}
/** Set bbox definition to override the image bbox. */
public void setBBox (int x, int y, int width, int height) {
bbox = new JGRectangle(x, y, width, height);
}
/** Clear bbox definition so that we use the image bbox again. */
public void clearBBox () {
bbox = null;
}
// /** Set object's tile span by defining the number of tiles and the margin
// * by which the object's position is snapped for determining the object's
// * top left position. */
// public void setTiles(int xtiles,int ytiles,int gridsnapx,int gridsnapy){
// this.xtiles=xtiles;
// this.ytiles=ytiles;
// this.gridsnapx=gridsnapx;
// this.gridsnapy=gridsnapy;
// }
public void setPos (double x, double y) {
this.x = x;
this.y = y;
}
/**
* Set absolute speed. Set xdir, ydir to the sign of the supplied speed,
* and xspeed and yspeed to the absolute value of the supplied speed.
* Passing a value of exactly 0.0 sets the dir to 0.
*/
public void setSpeedAbs (double xspeed, double yspeed) {
if (xspeed < 0.0) {
xdir = -1;
this.xspeed = -xspeed;
}
else if (xspeed == 0.0) {
xdir = 0;
this.xspeed = 0;
}
else {
xdir = 1;
this.xspeed = xspeed;
}
if (yspeed < 0.0) {
ydir = -1;
this.yspeed = -yspeed;
}
else if (yspeed == 0.0) {
ydir = 0;
this.yspeed = 0;
}
else {
ydir = 1;
this.yspeed = yspeed;
}
}
/** Set speed and direction in one go. */
public void setDirSpeed (int xdir, int ydir, double xspeed, double yspeed) {
this.xdir = xdir;
this.ydir = ydir;
this.xspeed = xspeed;
this.yspeed = yspeed;
}
/** Set speed and direction in one go. */
public void setDirSpeed (int xdir, int ydir, double speed) {
this.xdir = xdir;
this.ydir = ydir;
this.xspeed = speed;
this.yspeed = speed;
}
/** Set relative speed; the values are copied into xspeed,yspeed. */
public void setSpeed (double xspeed, double yspeed) {
this.xspeed = xspeed;
this.yspeed = yspeed;
}
/** Set relative speed; the value is copied into xspeed,yspeed. */
public void setSpeed (double speed) {
this.xspeed = speed;
this.yspeed = speed;
}
/** Set direction. */
public void setDir (int xdir, int ydir) {
this.xdir = xdir;
this.ydir = ydir;
}
/**
* Set ID of animation or image to display. First, look for an animation
* with the given ID, and setAnim if found. Otherwise, look for an image
* with the given ID, and setImage if found. Passing null clears the
* image and stops the animation.
*/
public void setGraphic (String gfxname) {
if (gfxname == null) {
setImage(gfxname);
}
else {
Animation newanim = eng.getAnimation(gfxname);
if (newanim != null) {
setAnim(gfxname);
}
else {
setImage(gfxname);
}
}
}
/**
* Set ID of image to display; clear animation. Passing null clears
* the image.
*/
public void setImage (String imgname) {
this.imgname = imgname;
imgbbox = null;
anim = null;
animid = null;
// stopAnim();
}
/** Get object's current animation ID, or image ID if not defined. */
public String getGraphic () {
if (animid != null) return animid;
return imgname;
}
/* animation */
/**
* Set the animation to the given default animation definition, or leave
* it as it was if the anim_id is unchanged. Subsequent changes made in
* the animation's parameters do not change the default animation
* definition. The changes will be preserved if another call to
* setAnimation is made with the same anim_id. If you want to reset the
* animation to the original settings, use resetAnimation().
*/
public void setAnim (String anim_id) {
if (animid == null || !animid.equals(anim_id)) {
anim = eng.getAnimation(anim_id);
if (anim == null) {
eng.dbgPrint(name, "Warning: animation " + anim_id + " not found.");
return;
}
anim = anim.copy();
animid = anim_id;
imgname = anim.getCurrentFrame();
}
}
/**
* Always set the animation to the given default animation definition,
* resetting any changes or updates made to the animation. Subsequent
* changes made in the animation's parameters do not change the default
* animation definition.
*/
public void resetAnim (String anim_id) {
anim = eng.getAnimation(anim_id).copy();
animid = anim_id;
}
/** Clear the animation, the object's current image will remain. */
public void clearAnim () {
anim = null;
animid = null;
}
/** Get the ID of the currently running animation. */
public String getAnimId () {
return animid;
}
// public void setAnimIncrement(int increment) {
// if (anim!=null) anim.increment=increment;
// }
/**
* Set animation speed; speed may be less than 0, indicating that
* animation should go backwards.
*/
public void setAnimSpeed (double speed) {
if (anim != null) {
if (speed >= 0) {
anim.speed = speed;
anim.increment = 1;
}
else {
anim.speed = -speed;
anim.increment = -1;
}
}
}
public void setAnimPingpong (boolean pingpong) {
if (anim != null) anim.pingpong = pingpong;
}
public void startAnim () {
if (anim != null) anim.start();
}
public void stopAnim () {
if (anim != null) anim.stop();
}
/** Reset the animation's state to the start state. */
public void resetAnim () {
if (anim != null) anim.reset();
}
/**
* Create object.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname) {
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setPos(x, y);
setGraphic(gfxname);
}
/**
* Create object with given expiry.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname, int expiry) {
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setPos(x, y);
setGraphic(gfxname);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, old style. Old style constructors
* are not compatible with the JGame Flash parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
}
/**
* Create object with given tile bbox and expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
this.expiry = expiry;
}
/**
* Create object with given absolute speed, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setSpeedAbs(xspeed, yspeed);
}
/**
* Create object with given absolute speed and expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox and absolute speed, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setSpeedAbs(xspeed, yspeed);
}
/**
* Create object with given tile bbox, absolute speed, expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given direction/speed, expiry, old style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int xdir, int ydir, double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, direction/speed, expiry, old
* style.
* Old style constructors are not compatible with the JGame Flash
* parameter order.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int tilebbox_x, int tilebbox_y, int tilebbox_width, int tilebbox_height,
int xdir, int ydir, double xspeed, double yspeed, int expiry) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox_x, tilebbox_y, tilebbox_width, tilebbox_height);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/** Flash style constructors */
/**
* Create object with given absolute speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox.x, tilebbox.y, tilebbox.width, tilebbox.height);
setSpeedAbs(xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given direction/speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed,
int xdir, int ydir) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/**
* Create object with given tile bbox, direction/speed, expiry, new
* style. New-style constructors enable easier porting to JGame Flash.
*
* @param unique_id append name with unique ID if unique_id set
* @param gfxname id of animation or image, null = no image
*/
public JGObject (String name, boolean unique_id,
double x, double y, int collisionid, String gfxname,
int expiry,
double xspeed, double yspeed,
int xdir, int ydir,
JGRectangle tilebbox) {
setPos(x, y);
initObject(default_engine,
name + (unique_id ? "" + (next_id++) : ""), collisionid);
setGraphic(gfxname);
setTileBBox(tilebbox.x, tilebbox.y, tilebbox.width, tilebbox.height);
setDirSpeed(xdir, ydir, xspeed, yspeed);
this.expiry = expiry;
}
/*
* Bounding box functions. Return copies. May return null if
* image is not defined.
*/
/**
* Copy object collision bounding box in pixels into bbox_copy. Has actual
* coordinate offset. If bounding box is not defined, bbox_copy is
* unchanged.
*
* @return false if bbox is null, true if not null
*/
public boolean getBBox (JGRectangle bbox_copy) {
if (bbox != null) {
bbox_copy.x = bbox.x + (int) x;
bbox_copy.y = bbox.y + (int) y;
bbox_copy.width = bbox.width;
bbox_copy.height = bbox.height;
return true;
}
// updateImageBBox();
// inlined updateImageBBox
if (imgbbox == null && imgname != null) {
imgbbox = eng.getImageBBox(imgname);
}
if (imgbbox != null) {
bbox_copy.x = imgbbox.x + (int) x;
bbox_copy.y = imgbbox.y + (int) y;
bbox_copy.width = imgbbox.width;
bbox_copy.height = imgbbox.height;
return true;
}
return false;
}
/**
* Get object collision bounding box in pixels.
* Has actual coordinate offset.
*
* @return copy of bbox in pixel coordinates, null if no bbox
*/
public JGRectangle getBBox () {
if (bbox != null) return new JGRectangle(bbox.x + (int) x, bbox.y + (int) y,
bbox.width, bbox.height);
updateImageBBox();
if (imgbbox != null) { return new JGRectangle(imgbbox.x + (int) x, imgbbox.y + (int) y,
imgbbox.width, imgbbox.height); }
return null;
}
// JGRectangle bbox_const = new JGRectangle(0,0,0,0);
/**
* Get object collision bounding box in pixels.
* Has actual coordinate offset. Uses a fixed temp variable to store the
* bbox, so no object is created. The returned object may not be modified,
* nor its contents used after the method is re-entered.
*
* @return bbox in pixel coordinates, null if no bbox
*/
// public JGRectangle getBBoxConst() {
// if (!getBBox(bbox_const)) return null;
// return bbox_const;
// }
/**
* Get object collision bounding box in pixels of previous frame.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getLastBBox() {
// if (lastbbox==null) return null;
// return new JGRectangle(lastbbox);
// }
/**
* Get tile collision bounding box in pixels and store it in bbox_copy.
* Bounding box has actual coordinate offset. If bounding box is not
* defined, bbox_copy is unchanged.
*
* @return false when bounding box is not defined, true otherwise
*/
public boolean getTileBBox (JGRectangle bbox_copy) {
if (tilebbox == null) { return getBBox(bbox_copy); }
bbox_copy.x = (int) x + tilebbox.x;
bbox_copy.y = (int) y + tilebbox.y;
bbox_copy.width = tilebbox.width;
bbox_copy.height = tilebbox.height;
return true;
}
/**
* Get tile collision bounding box in pixels.
* Bounding box has actual coordinate offset.
*
* @return copy of bbox in pixel coordinates, null if no bbox
*/
public JGRectangle getTileBBox () {
if (tilebbox == null) return getBBox();
return new JGRectangle((int) x + tilebbox.x, (int) y + tilebbox.y,
tilebbox.width, tilebbox.height);
}
// JGRectangle tilebbox_const = new JGRectangle(0,0,0,0);
/**
* Get tile collision bounding box in pixels.
* Bounding box has actual coordinate offset. Returns reference to a
* fixed internal variable. Do not change the object returned, avoid
* re-entering this method and then using the previous value returned.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getTileBBoxConst() {
// if (tilebbox==null) {
// JGRectangle bbox = getBBoxConst();
// if (bbox==null) return null;
// tilebbox_const.copyFrom(bbox);
// return tilebbox_const;
// }
// tilebbox_const.x = (int)x+tilebbox.x;
// tilebbox_const.y = (int)y+tilebbox.y;
// tilebbox_const.width = tilebbox.width;
// tilebbox_const.height= tilebbox.height;
// return tilebbox_const;
// }
/**
* Get tile collision bounding box of previous frame.
*
* @return pixel coordinates, null if no bbox
*/
// public JGRectangle getLastTileBBox() {
// if (lasttilebbox==null) return null;
// return new JGRectangle(lasttilebbox);
// }
/**
* Get collision bounding box of object's image (same as object's default
* bbox, note that the offset is (0,0) here).
*
* @return copy of bbox's pixel coordinates, null if no bbox
*/
public JGRectangle getImageBBox () {
updateImageBBox();
if (imgbbox == null) return null;
return new JGRectangle(imgbbox);
}
/**
* Get collision bounding box of object's image (same as object's default
* bbox, note that the offset is (0,0) here). Optimised version of
* getImageBBox(). Do not change the value of the object!
*
* @return *original* bbox's pixel coordinates, null if no bbox
*/
public JGRectangle getImageBBoxConst () {
updateImageBBox();
return imgbbox;
}
/** Update the imgbbox variable. */
void updateImageBBox () {
if (imgbbox == null && imgname != null) {
imgbbox = eng.getImageBBox(imgname);
}
}
/** Get x position of previous frame. Returns 0 if first frame. */
public double getLastX () {
return lastx;
}
/** Get y position of previous frame. Returns 0 if first frame. */
public double getLastY () {
return lasty;
}
/* snap functions */
/**
* Snap object to grid using the default gridsnap margin of
* (xspeed*gamespeed-epsilon, yspeed*gamespeed-epsilon),
* corresponding to the default is...Aligned margin.
*/
public void snapToGrid () {
x = eng.snapToGridX(x, Math.abs(xspeed * gamespeed - 0.001));
y = eng.snapToGridY(y, Math.abs(yspeed * gamespeed - 0.001));
}
/**
* Snap object to grid.
*
* @param gridsnapx margin below which to snap, 0.0 is no snap
* @param gridsnapy margin below which to snap, 0.0 is no snap
*/
public void snapToGrid (double gridsnapx, double gridsnapy) {
x = eng.snapToGridX(x, gridsnapx);
y = eng.snapToGridY(y, gridsnapy);
}
// /** Snap object to grid. */
// public void snapToGrid(int gridsnapx, int gridsnapy) {
// JGPoint p = new JGPoint((int)x,(int)y);
// eng.snapToGrid(p,gridsnapx,gridsnapy);
// x = p.x;
// y = p.y;
// }
/**
* Snap an object's tile bbox corner to grid; floats are rounded down.
* Snaps to bottom or right of object instead of top and left if the resp.
* flags are set. Note that bottom and right alignment means that the
* object's bounding box is one pixel away from crossing the tile border.
*
* @param snap_right snap the right hand side of the tile bbox
* @param snap_bottom snap the bottom of the tile bbox
*/
public void snapBBoxToGrid (double gridsnapx, double gridsnapy,
boolean snap_right, boolean snap_bottom) {
JGRectangle bbox = getTileBBox();
double bx = x + bbox.x;
double by = y + bbox.y;
if (snap_right) bx += bbox.width;
if (snap_bottom) by += bbox.height;
double bxs = eng.snapToGridX(bx, gridsnapx);
double bys = eng.snapToGridY(by, gridsnapy);
bxs -= bbox.x;
bys -= bbox.y;
if (snap_right) bxs -= bbox.width;
if (snap_bottom) bys -= bbox.height;
x = bxs;
y = bys;
}
/* bg interaction */
// temp variables used by get*Tiles and isOnScreen/PF
JGRectangle temp_bbox_copy = new JGRectangle();
// variables returned by get*Tiles
JGRectangle tiles_copy = null;
JGRectangle last_tiles_copy = null;
JGRectangle center_tiles_copy = new JGRectangle();
JGRectangle last_center_tiles_copy = null;
JGPoint center_tile_copy = null;
JGPoint tl_tile_copy = null;
/**
* Get the tile index coordinates of all the tiles that the object's
* tile bbox overlaps with. Always returns the same temp object, so no
* object creation is necessary.
*
* @return tile index coordinates, null if no bbox
*/
public JGRectangle getTiles () {
// orig: return eng.getTiles(getTileBBox());
if (!getTileBBox(temp_bbox_copy)) return null;
if (tiles_copy == null) tiles_copy = new JGRectangle();
if (eng.getTiles(tiles_copy, temp_bbox_copy))
return tiles_copy;
return null;
}
/**
* Get the tile index coordinates of the object's previous tile bbox.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox
*/
// public JGRectangle getLastTiles() {
// //orig: return eng.getTiles(getLastTileBBox());
// // XXX object creation in getLastTileBBox
// JGRectangle bbox = getLastTileBBox();
// if (bbox==null) return null;
// if (last_tiles_copy==null) last_tiles_copy = new JGRectangle();
// if (eng.getTiles(last_tiles_copy,bbox))
// return last_tiles_copy;
// return null;
// }
/** get center tiles from bbox and store them in tiles_copy */
private JGRectangle getCenterTiles (JGRectangle bbox, JGRectangle tiles_copy) {
// XXX create a getTileIndexX and Y?
// JGPoint p =
// eng.getTileIndex(bbox.x+(bbox.width/2),bbox.y+(bbox.height/2) );
int px, py;
if (bbox.x >= 0) {
px = ((bbox.x + (bbox.width / 2))
/ tilewidth) * tilewidth + tilewidth / 2;
bbox.x = tilewidth * ((px - (bbox.width / 2)) / tilewidth);
}
else {
px = ((bbox.x + (bbox.width / 2) - tilewidth + 1)
/ tilewidth) * tilewidth + tilewidth / 2;
bbox.x = tilewidth * ((px - (bbox.width / 2) - tilewidth + 1)
/ tilewidth);
}
if (bbox.y >= 0) {
py = ((bbox.y + (bbox.height / 2))
/ tileheight) * tileheight + tileheight / 2;
bbox.y = tileheight * ((py - (bbox.height / 2)) / tileheight);
}
else {
py = ((bbox.y + (bbox.height / 2) - tileheight + 1)
/ tileheight) * tileheight + tileheight / 2;
bbox.y = tileheight * ((py - (bbox.height / 2) - tileheight + 1)
/ tileheight);
}
eng.getTiles(tiles_copy, bbox);
return tiles_copy;
}
/**
* Get the tile indices spanning the tiles that the object has the
* most overlap with. The size of the span is
* always the same as size of the tile bbox in tiles. For example, if the
* tile bbox is 48x32 pixels and the tile size is 32x32 pixels, the size
* in tiles is always 1.5x1 tiles, which is rounded up to 2x1 tiles.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox is defined
*/
public JGRectangle getCenterTiles () {
if (!getTileBBox(temp_bbox_copy)) return null;
/*
* find the tile on which the center of the bounding box is located,
* that will be the center of our tile span.
*/
return getCenterTiles(temp_bbox_copy, center_tiles_copy);
}
/**
* Get the tile indices spanning the tiles that the object's last
* bounding box had the most overlap with.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinates, null if no tile bbox
*/
// public JGRectangle getLastCenterTiles() {
// // XXX object creation in getLastTileBBox
// JGRectangle bbox=getLastTileBBox();
// if (bbox==null) return null;
// if (last_center_tiles_copy==null)
// last_center_tiles_copy = new JGRectangle();
// return getCenterTiles(bbox,last_center_tiles_copy);
// }
/**
* Get the top left center tile of the object (that is, the x and y of
* getCenterTiles()). If the object is 1x1 tile in size, you get the
* center tile. If the object is larger, you get the top left tile of the
* center tiles.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinate, null if no tile bbox
*/
public JGPoint getCenterTile () {
if (!getTileBBox(temp_bbox_copy)) return null;
if (center_tile_copy == null) center_tile_copy = new JGPoint();
// XXX center_tiles_copy is used also
getCenterTiles(temp_bbox_copy, center_tiles_copy);
center_tile_copy.x = center_tiles_copy.x;
center_tile_copy.y = center_tiles_copy.y;
return center_tile_copy;
}
/**
* Get the topleftmost tile of the object.
* Always returns the same temp object, so no object creation is necessary.
*
* @return tile index coordinate, null if no bbox
*/
public JGPoint getTopLeftTile () {
// XXX this global is used also
JGRectangle r = getTiles();
if (r == null) return null;
if (tl_tile_copy == null) tl_tile_copy = new JGPoint();
tl_tile_copy.x = r.x;
tl_tile_copy.y = r.y;
return tl_tile_copy;
}
/**
* Returns true if both isXAligned() and isYAligned() are true.
*
* @see #isXAligned()
* @see #isYAligned()
*/
public boolean isAligned () {
return isXAligned() && isYAligned();
}
/**
* Returns true if x is distance xspeed-epsilon away from being grid
* aligned. If an object moves at its current xspeed, this method will
* always return true when the object crosses the tile alignment line, and
* return false when the object is snapped to grid, and then
* moves xspeed*gamespeed away from its aligned position.
*/
public boolean isXAligned () {
return eng.isXAligned(x, Math.abs(xspeed * gamespeed - 0.001));
}
/**
* Returns true if y is distance yspeed-epsilon away from being grid
* aligned. If an object moves at its current yspeed, this method will
* always return true when the object crosses the tile alignment line, and
* return false when the object is snapped to grid, and then
* moves yspeed*gamespeed away from its aligned position.
*/
public boolean isYAligned () {
return eng.isYAligned(y, Math.abs(yspeed * gamespeed - 0.001));
}
/**
* Returns true if x is within margin of being tile grid aligned. Epsilon
* is added to the margin, so that isXAligned(1.0000, 1.0000)
* always returns true.
*/
public boolean isXAligned (double margin) {
return eng.isXAligned(x, margin);
}
/**
* Returns true if y is within margin of being tile grid aligned. Epsilon
* is added to the margin, so that isXAligned(1.0000, 1.0000)
* always returns true.
*/
public boolean isYAligned (double margin) {
return eng.isYAligned(y, margin);
}
/**
* Returns true if the left of the object's tile bbox is within margin of
* being tile grid aligned.
*/
public boolean isLeftAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isXAligned(bbox.x, margin);
}
else {
return eng.isXAligned(x, margin);
}
}
/**
* Returns true if the top of the object's tile bbox is within margin of
* being tile grid aligned.
*/
public boolean isTopAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isYAligned(bbox.y, margin);
}
else {
return eng.isYAligned(y, margin);
}
}
/**
* Returns true if the right of the object's tile bbox is within margin of
* being tile grid aligned. Note that right aligned means that the bbox is
* one pixel away from crossing the tile border.
*/
public boolean isRightAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isXAligned(bbox.x + bbox.width, margin);
}
else {
return eng.isXAligned(x, margin);
}
}
/**
* Returns true if the bottom of the object's tile bbox is within margin of
* being tile grid aligned. Note that right aligned means that the bbox is
* one pixel away from crossing the tile border.
*/
public boolean isBottomAligned (double margin) {
JGRectangle bbox = getTileBBox();
if (bbox != null) {
return eng.isYAligned(bbox.y + bbox.height, margin);
}
else {
return eng.isYAligned(y, margin);
}
}
/**
* Check collision of this object with other objects, when the object
* position would be offset by xofs,yofs. Returns 0 when object's bbox is
* not defined.
*
* @param cid cid mask of objects to consider, 0=any
*/
public int checkCollision (int cid, double xofs, double yofs) {
double oldx = x, oldy = y;
x += xofs;
y += yofs;
int retcid = eng.checkCollision(cid, this);
x = oldx;
y = oldy;
return retcid;
}
/*
* something odd going on here: it fails to find the checkBGCollision in
* Engine when I define this one in Object
* public int checkBGCollision() {
* return eng.checkBGCollision(getTileBBox());
* }
*/
/**
* Check collision of tiles within given rectangle, return the OR of all
* cids found. This method just calls eng.checkBGCollision; it's here
* because JGEngine.checkBGCollision(JGRectangle) is masked when the object
* is an inner class of JGEngine.
*/
public int checkBGCollision (JGRectangle r) {
return eng.checkBGCollision(r);
}
/**
* Get OR of Tile Cids of the object's current tile bbox at the current
* position, when offset by the given offset. Returns 0 if tile bbox is not
* defined.
*/
public int checkBGCollision (double xofs, double yofs) {
double oldx = x, oldy = y;
x += xofs;
y += yofs;
JGRectangle bbox = getTileBBox();
x = oldx;
y = oldy;
if (bbox == null) return 0;
return checkBGCollision(bbox);
}
/**
* Margin is the margin beyond which the object is considered offscreen.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box. isOnScreen is equal to isOnPF, but is
* deprecated because the name is ambiguous.
*
* @deprecated Use isOnPF and isInView according to your situation.
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isOnScreen (int marginx, int marginy) {
return isOnPF(marginx, marginy);
}
/**
* Margin is the margin beyond which the object is considered off-view.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box.
*
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isInView (int marginx, int marginy) {
if (!getTileBBox(temp_bbox_copy)) {
temp_bbox_copy.x = (int) x;
temp_bbox_copy.y = (int) y;
temp_bbox_copy.width = 0;
temp_bbox_copy.height = 0;
}
if (temp_bbox_copy.x + temp_bbox_copy.width < viewxofs - marginx)
return false;
if (temp_bbox_copy.y + temp_bbox_copy.height < viewyofs - marginy)
return false;
if (temp_bbox_copy.x > viewxofs + viewwidth + marginx)
return false;
if (temp_bbox_copy.y > viewyofs + viewheight + marginy)
return false;
return true;
}
/**
* Margin is the margin beyond which the object is considered off the
* playfield.
* The tile bounding box is used as the object's size, if there is none, we
* use a zero-size bounding box.
*
* @param marginx pixel margin, may be negative
* @param marginy pixel margin, may be negative
*/
public boolean isOnPF (int marginx, int marginy) {
if (!getTileBBox(temp_bbox_copy)) {
temp_bbox_copy.x = (int) x;
temp_bbox_copy.y = (int) y;
temp_bbox_copy.width = 0;
temp_bbox_copy.height = 0;
}
if (!pfwrapx) {
if (temp_bbox_copy.x + temp_bbox_copy.width < -marginx) return false;
if (temp_bbox_copy.x > pfwidth + marginx) return false;
}
if (!pfwrapy) {
if (temp_bbox_copy.y + temp_bbox_copy.height < -marginy) return false;
if (temp_bbox_copy.y > pfheight + marginy) return false;
}
return true;
}
/* computation */
/**
* A Boolean AND shorthand to use for collision;
* returns (value&mask) != 0.
*/
public static boolean and (int value, int mask) {
return (value & mask) != 0;
}
public double random (double min, double max) {
return eng.random(min, max);
}
public double random (double min, double max, double interval) {
return eng.random(min, max, interval);
}
public int random (int min, int max, int interval) {
return eng.random(min, max, interval);
}
/**
* Do automatic animation. Is automatically called by the JGEngine
* implementation once for every
* moveObjects; normally it is not necessary to call this.
*/
public void updateAnimation (double gamespeed) {
if (anim != null) {// && eng.canvas.anim_running) {
imgname = anim.animate(gamespeed);
imgbbox = null;
}
}
/**
* Signal that a new frame has just been updated; make
* snapshot of object state. Should only be called by the JGEngine
* implementation.
*/
public void frameFinished () {
lastx = x;
lasty = y;
// if (getBBox(lastbbox_copy)) {
// lastbbox = lastbbox_copy;
// } else {
// lastbbox=null;
// }
// if (getTileBBox(lasttilebbox_copy)) {
// lasttilebbox = lasttilebbox_copy;
// } else {
// lasttilebbox=null;
// }
}
/**
* Modulo x/y position according to wrap settings. Is automatically
* performed by the JGEngine implementation
* after each moveObjects. Normally it is not necessary to call this, but
* it may be in special cases.
*/
public void moduloPos () {
// note: there is an inlined version of this code in EngineLogic
if (pfwrapx) x = eng.moduloXPos(x);
if (pfwrapy) y = eng.moduloYPos(y);
}
/**
* Suspend object until either resume is called or, if
* resume_in_view is true, when it comes into view. A suspended object
* does not participate in any move, hit, or paint.
*/
public void suspend () {
is_suspended = true;
}
/** Resume from suspended state, if suspended. */
public void resume () {
is_suspended = false;
}
/** Check if object is suspended. */
public boolean isSuspended () {
return is_suspended;
}
/**
* Set resume condition.
*
* @param resume_in_view resume when in view
*/
public void setResumeMode (boolean resume_in_view) {
this.resume_in_view = resume_in_view;
}
/**
* Check if object is still active, or has already been removed. Also
* returns false if the object is still pending to be removed.
*/
public boolean isAlive () {
return is_alive;
}
/**
* Signal to object that remove is done, don't call directly. This is
* used by the engine to signal that the object should be finalised.
*/
public final void removeDone () {
destroy();
is_alive = false;
}
/**
* Mark object for removal, ignore if already removed.
* The object will be removed at the end of this
* moveObjects, checkCollision, or checkBGCollision action, or immediately
* if not inside either of these actions.
*/
public void remove () {
if (isAlive()) eng.removeObject(this);
is_alive = false;
}
/**
* Override to implement object disposal code. This method is called at
* the actual moment of removal.
*/
public void destroy () {
}
/**
* Override to implement automatic move; default is do nothing.
*/
public void move () {
}
/**
* Override to handle collision; default is do nothing.
*/
public void hit (JGObject obj) {
}
/**
* Override to handle tile collision; default is do nothing.
*/
public void hit_bg (int tilecid) {
}
/**
* Override to handle tile collision; default is do nothing.
* This method is always called when hit_bg(int) is also called, only, extra
* information is passed that may be useful.
*/
public void hit_bg (int tilecid, int tx, int ty, int txsize, int tysize) {
}
/**
* Override to handle tile collision; default is do nothing.
* This method is always called when hit_bg(int) is also called, only it may
* be called multiple times, namely once for each tile the object collides
* with. The arguments pass the tile cid and position of that tile. It is
* always called after hit_bg(int) and hit_bg(int,int,int,int,int) have
* been called.
*/
public void hit_bg (int tilecid, int tx, int ty) {
}
/** Override to define custom paint actions. */
public void paint () {
}
}
|
change alph to 1
|
src/jgame/JGObject.java
|
change alph to 1
|
|
Java
|
mit
|
f6316d42d1cb33d28d91b726a3ebad2b9dba5b93
| 0
|
TylerCarberry/PTSD-Aid,TylerCarberry/PTSD-Aid
|
package com.tytanapps.ptsd;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* A short multiple choice quiz to determine if you suffer from PTSD. Based on the results, gives
* you recommendations on what to do next. Find a professional is always a recommendation even if
* the user shows no signs of PTSD.
*/
public class PTSDTestFragment extends Fragment {
private static final String LOG_TAG = PTSDTestFragment.class.getSimpleName();
public PTSDTestFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_ptsd_test, container, false);
LinearLayout questionsLinearLayout = (LinearLayout) rootView.findViewById(R.id.questions_linearlayout);
insertQuestions(questionsLinearLayout);
return rootView;
}
/**
* Get the root view of the fragment casted to a ViewGroup
* @return The root view of the fragment as a ViewGroup
*/
private ViewGroup getViewGroup() {
View rootView = getView();
if(rootView instanceof ViewGroup)
return (ViewGroup) getView();
return null;
}
/**
* Add the questions to the linear layout
* @param questionsLinearLayout The linear layout to add the questions to
*/
private void insertQuestions(LinearLayout questionsLinearLayout) {
String[] questions = getResources().getStringArray(R.array.stress_questions);
LayoutInflater inflater = LayoutInflater.from(getActivity());
for(String question : questions) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.question_box, getViewGroup(), false);
TextView questionTextView = (TextView) layout.findViewById(R.id.stress_question_textview);
questionTextView.setText(question);
questionsLinearLayout.addView(layout);
}
addSubmitButton(questionsLinearLayout);
}
/**
* Add the submit button after the list of questions
* @param questionsLinearLayout The layout to add the submit button to
*/
private void addSubmitButton(LinearLayout questionsLinearLayout) {
Button submitButton = new Button(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int horizontalMargin = (int) getResources().getDimension(R.dimen.activity_horizontal_margin);
int verticalMargin = (int) getResources().getDimension(R.dimen.activity_vertical_margin);
params.setMargins(horizontalMargin, verticalMargin, horizontalMargin, verticalMargin);
submitButton.setLayoutParams(params);
// Set the appearance of the button
submitButton.setPadding(horizontalMargin, verticalMargin, horizontalMargin, verticalMargin);
submitButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
submitButton.setTextColor(getResources().getColor(R.color.white));
submitButton.setTextSize(20);
submitButton.setText(getString(R.string.submit_test));
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submit();
}
});
questionsLinearLayout.addView(submitButton);
}
/**
* The user has pressed the submit button.
* Calculate the total score and notify the user appropriately
*/
private void submit() {
int score = getScore();
showResults(score);
}
/**
* Display an AlertDialog with the results of the test
* @param score The score that the user received
*/
private void showResults(int score) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setPositiveButton(R.string.find_professional, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
findProfessional();
}
});
alertDialogBuilder.setNegativeButton(R.string.share_results, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
shareResults();
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
LayoutInflater inflater = LayoutInflater.from(getActivity());
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.ptsd_result_dialog, getViewGroup(), false);
String resultText;
String nextActions;
// Low
if(score <= 20) {
resultText = getString(R.string.result_minimal);
nextActions = getString(R.string.see_professional_low);
}
// Medium
else if(score <= 29) {
resultText = getString(R.string.result_medium);
nextActions = getString(R.string.see_professional_medium);
}
// High
else {
resultText = getString(R.string.result_high);
nextActions = getString(R.string.see_professional_high);
}
TextView resultTextView = (TextView) layout.findViewById(R.id.results_textview);
resultTextView.setText(resultText);
TextView nextActionsTextView = (TextView) layout.findViewById(R.id.next_steps_textview);
nextActionsTextView.setText(nextActions);
alertDialog.setView(layout);
alertDialog.show();
}
/**
* Switch to the NearbyFacilitiesFragment and show a list of nearby facilities
*/
private void findProfessional() {
NearbyFacilitiesFragment nearbyFacilitiesFragment = new NearbyFacilitiesFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment
transaction.replace(R.id.fragment_container, nearbyFacilitiesFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
/**
* Share the results of the test
* Creates a share intent. The user can share the results with any app.
*/
private void shareResults() {
String shareText = generateShareText();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(intent, "Share via"));
}
/**
* Generate the text to be shared when completing the test.
* This includes each question and the answer that was selected.
* @return A string of the text to be shared
*/
private String generateShareText() {
String[] questions = getResources().getStringArray(R.array.stress_questions);
int[] answers = getEachAnswer();
String shareText = getString(R.string.stress_prompt);
shareText += "\n\n";
for(int i = 0; i < questions.length; i++) {
// Include each question prompt
shareText += (i+1) + ") ";
shareText += questions[i] + "\n";
shareText += "-";
switch (answers[i]) {
case 1:
shareText += getString(R.string.not_at_all);
break;
case 2:
shareText += getString(R.string.little_bit);
break;
case 3:
shareText += getString(R.string.moderately);
break;
case 4:
shareText += getString(R.string.quite_a_bit);
break;
case 5:
shareText += getString(R.string.extremely);
break;
default:
shareText += "N/A";
break;
}
// Skip a line between each question
shareText += "\n\n";
}
return shareText;
}
/**
* Get each answer that the user has selected.
* Each element of the array has the id of the radio button that was selected for that question,
* -1 if no answer was provided for that question
* 1-5
* @return An array of the answers
*/
private int[] getEachAnswer() {
// TODO The number of questions is hard coded
int score[] = new int[17];
int questionCount = 0;
View rootView = getView();
if(rootView != null) {
LinearLayout questionsLinearLayout = (LinearLayout) rootView.findViewById(R.id.questions_linearlayout);
for (int i = 0; i < questionsLinearLayout.getChildCount(); i++) {
View childView = questionsLinearLayout.getChildAt(i);
if (childView instanceof ViewGroup) {
SeekBar seekBar = (SeekBar) childView.findViewById(R.id.result_seekbar);
score[questionCount] = seekBar.getProgress() + 1;
questionCount++;
}
}
}
return score;
}
/**
* Determine the total score of the answered questions.
* If not every question has been answered, return -1
* Not at all: 1, A little bit: 2, Moderately: 3, Quite a bit: 4, Extremely: 5
* @return The total score of the questions
*/
private int getScore() {
int score = 0;
for(int num : getEachAnswer()) {
if(num > 0)
score += num;
// If a question has not been answered
else
return -1;
}
return score;
}
}
|
app/src/main/java/com/tytanapps/ptsd/PTSDTestFragment.java
|
package com.tytanapps.ptsd;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* A short multiple choice quiz to determine if you suffer from PTSD. Based on the results, gives
* you recommendations on what to do next. Find a professional is always a recommendation even if
* the user shows no signs of PTSD.
*/
public class PTSDTestFragment extends Fragment {
private static final String LOG_TAG = PTSDTestFragment.class.getSimpleName();
public PTSDTestFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_ptsd_test, container, false);
LinearLayout questionsLinearLayout = (LinearLayout) rootView.findViewById(R.id.questions_linearlayout);
insertQuestions(questionsLinearLayout);
return rootView;
}
/**
* Get the root view of the fragment casted to a ViewGroup
* @return The root view of the fragment as a ViewGroup
*/
private ViewGroup getViewGroup() {
View rootView = getView();
if(rootView instanceof ViewGroup)
return (ViewGroup) getView();
return null;
}
/**
* Add the questions to the linear layout
* @param questionsLinearLayout The linear layout to add the questions to
*/
private void insertQuestions(LinearLayout questionsLinearLayout) {
String[] questions = getResources().getStringArray(R.array.stress_questions);
LayoutInflater inflater = LayoutInflater.from(getActivity());
for(String question : questions) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.question_box, getViewGroup(), false);
TextView questionTextView = (TextView) layout.findViewById(R.id.stress_question_textview);
questionTextView.setText(question);
questionsLinearLayout.addView(layout);
}
addSubmitButton(questionsLinearLayout);
}
/**
* Add the submit button after the list of questions
* @param questionsLinearLayout The layout to add the submit button to
*/
private void addSubmitButton(LinearLayout questionsLinearLayout) {
Button submitButton = new Button(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int horizontalMargin = (int) getResources().getDimension(R.dimen.activity_horizontal_margin);
int verticalMargin = (int) getResources().getDimension(R.dimen.activity_vertical_margin);
params.setMargins(horizontalMargin, verticalMargin, horizontalMargin, verticalMargin);
submitButton.setLayoutParams(params);
// Set the appearance of the button
submitButton.setPadding(horizontalMargin, verticalMargin, horizontalMargin, verticalMargin);
submitButton.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
submitButton.setTextColor(getResources().getColor(R.color.white));
submitButton.setTextSize(20);
submitButton.setText(getString(R.string.submit_test));
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
submit();
}
});
questionsLinearLayout.addView(submitButton);
}
/**
* The user has pressed the submit button.
* Calculate the total score and notify the user appropriately
*/
private void submit() {
int score = getScore();
showResults(score);
}
/**
* Display an AlertDialog with the results of the test
* @param score The score that the user received
*/
private void showResults(int score) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setPositiveButton(R.string.find_professional, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
findProfessional();
}
});
alertDialogBuilder.setNegativeButton(R.string.share_results, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
shareResults();
}
});
final AlertDialog alertDialog = alertDialogBuilder.create();
LayoutInflater inflater = LayoutInflater.from(getActivity());
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.ptsd_result_dialog, getViewGroup(), false);
String resultText;
String nextActions;
// Low
if(score <= 20) {
resultText = getString(R.string.result_minimal);
nextActions = getString(R.string.see_professional_low);
}
// Medium
else if(score <= 29) {
resultText = getString(R.string.result_medium);
nextActions = getString(R.string.see_professional_medium);
}
// High
else {
resultText = getString(R.string.result_high);
nextActions = getString(R.string.see_professional_high);
}
TextView resultTextView = (TextView) layout.findViewById(R.id.results_textview);
resultTextView.setText(resultText);
TextView nextActionsTextView = (TextView) layout.findViewById(R.id.next_steps_textview);
nextActionsTextView.setText(nextActions);
alertDialog.setView(layout);
alertDialog.show();
}
/**
* Switch to the NearbyFacilitiesFragment and show a list of nearby facilities
*/
private void findProfessional() {
NearbyFacilitiesFragment nearbyFacilitiesFragment = new NearbyFacilitiesFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment
transaction.replace(R.id.fragment_container, nearbyFacilitiesFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
/**
* Share the results of the test
* Creates a share intent. The user can share the results with any app.
*/
private void shareResults() {
String shareText = generateShareText();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, shareText);
startActivity(Intent.createChooser(intent, "Share via"));
}
/**
* Generate the text to be shared when completing the test.
* This includes each question and the answer that was selected.
* @return A string of the text to be shared
*/
private String generateShareText() {
String[] questions = getResources().getStringArray(R.array.stress_questions);
int[] answers = getEachAnswer();
String shareText = getString(R.string.stress_prompt);
shareText += "\n\n";
for(int i = 0; i < questions.length; i++) {
// Include each question prompt
shareText += (i+1) + ") ";
shareText += questions[i] + "\n";
shareText += "-";
switch (answers[i]) {
case 1:
shareText += getString(R.string.not_at_all);
break;
case 2:
shareText += getString(R.string.little_bit);
break;
case 3:
shareText += getString(R.string.moderately);
break;
case 4:
shareText += getString(R.string.quite_a_bit);
break;
case 5:
shareText += getString(R.string.extremely);
break;
default:
shareText += "N/A";
break;
}
// Skip a line between each question
shareText += "\n\n";
}
return shareText;
}
/**
* Get each answer that the user has selected.
* Each element of the array has the id of the radio button that was selected for that question,
* -1 if no answer was provided for that question
* 1-5
* @return An array of the answers
*/
private int[] getEachAnswer() {
// TODO The number of questions is hard coded
int score[] = new int[17];
int questionCount = 0;
View rootView = getView();
if(rootView != null) {
LinearLayout questionsLinearLayout = (LinearLayout) rootView.findViewById(R.id.questions_linearlayout);
for (int i = 0; i < questionsLinearLayout.getChildCount(); i++) {
View childView = questionsLinearLayout.getChildAt(i);
if (childView instanceof ViewGroup) {
SeekBar seekBar = (SeekBar) childView.findViewById(R.id.result_seekbar);
score[questionCount] = seekBar.getProgress() + 1;
questionCount++;
}
}
}
return score;
}
/**
* Determine the total score of the answered questions.
* If not every question has been answered, return -1
* Not at all: 1, A little bit: 2, Moderately: 3, Quite a bit: 4, Extremely: 5
* @return The total score of the questions
*/
private int getScore() {
int score = 0;
int[] eachAnswer = getEachAnswer();
for(int num : eachAnswer) {
if(num > 0)
score += num;
// If a question has not been answered
else
return -1;
}
return score;
}
}
|
Minor cleanup in PTSDTestFragment
|
app/src/main/java/com/tytanapps/ptsd/PTSDTestFragment.java
|
Minor cleanup in PTSDTestFragment
|
|
Java
|
mit
|
bfba38867002b805c228a11c79bf0044867c42d8
| 0
|
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
|
package org.innovateuk.ifs.invite.transactional;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.HibernateValidator;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.invite.domain.ProjectInvite;
import org.innovateuk.ifs.invite.mapper.ProjectInviteMapper;
import org.innovateuk.ifs.invite.repository.InviteRepository;
import org.innovateuk.ifs.invite.repository.ProjectInviteRepository;
import org.innovateuk.ifs.invite.resource.ProjectInviteResource;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.innovateuk.ifs.project.core.repository.ProjectUserRepository;
import org.innovateuk.ifs.project.core.transactional.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.mapper.UserMapper;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.commons.error.CommonErrors.badRequestError;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.invite.domain.Invite.generateInviteHash;
import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_PARTNER;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@Service
public class ProjectInviteServiceImpl extends InviteService<ProjectInvite> implements ProjectInviteService {
private static final Log LOG = LogFactory.getLog(ProjectInviteServiceImpl.class);
@Value("${ifs.web.baseURL}")
private String webBaseUrl;
@Autowired
private ProjectInviteMapper inviteMapper;
@Autowired
private ProjectInviteRepository projectInviteRepository;
@Autowired
private ProjectService projectService;
@Autowired
private UserMapper userMapper;
@Autowired
private ProjectUserRepository projectUserRepository;
@Autowired
private OrganisationRepository organisationRepository;
private LocalValidatorFactoryBean validator;
public ProjectInviteServiceImpl() {
validator = new LocalValidatorFactoryBean();
validator.setProviderClass(HibernateValidator.class);
validator.afterPropertiesSet();
}
@Override
protected Class<ProjectInvite> getInviteClass() {
return ProjectInvite.class;
}
@Override
protected InviteRepository<ProjectInvite> getInviteRepository() {
return projectInviteRepository;
}
@Override
@Transactional
public ServiceResult<Void> saveProjectInvite(ProjectInviteResource projectInviteResource) {
return validateProjectInviteResource(projectInviteResource).andOnSuccess(() ->
validateUserNotAlreadyInvited(projectInviteResource).andOnSuccess(() ->
validateTargetUserIsValid(projectInviteResource).andOnSuccess(() -> {
ProjectInvite projectInvite = inviteMapper.mapToDomain(projectInviteResource);
Errors errors = new BeanPropertyBindingResult(projectInvite, projectInvite.getClass().getName());
validator.validate(projectInvite, errors);
if (errors.hasErrors()) {
errors.getFieldErrors().stream().peek(e -> LOG.debug(format("Field error: %s ", e.getField())));
return serviceFailure(badRequestError(errors.toString()));
} else {
projectInvite.setHash(generateInviteHash());
projectInviteRepository.save(projectInvite);
return serviceSuccess();
}
})));
}
private ProjectInviteResource mapInviteToInviteResource(ProjectInvite invite) {
ProjectInviteResource inviteResource = inviteMapper.mapToResource(invite);
Organisation organisation = organisationRepository.findOne(inviteResource.getLeadOrganisationId());
inviteResource.setLeadOrganisation(organisation.getName());
ProjectResource project = projectService.getProjectById(inviteResource.getProject()).getSuccess();
inviteResource.setApplicationId(project.getApplication());
return inviteResource;
}
@Override
public ServiceResult<ProjectInviteResource> getInviteByHash(String hash) {
return getByHash(hash).andOnSuccessReturn(this::mapInviteToInviteResource);
}
@Override
public ServiceResult<List<ProjectInviteResource>> getInvitesByProject(Long projectId) {
if(projectId == null) {
return serviceFailure(new Error(PROJECT_INVITE_INVALID_PROJECT_ID, NOT_FOUND));
}
List<ProjectInvite> invites = projectInviteRepository.findByProjectId(projectId);
List<ProjectInviteResource> inviteResources = invites.stream().map(this::mapInviteToInviteResource).collect(Collectors.toList());
return serviceSuccess(Lists.newArrayList(inviteResources));
}
@Override
@Transactional
public ServiceResult<Void> acceptProjectInvite(String inviteHash, Long userId) {
return find(invite(inviteHash), user(userId)).andOnSuccess((invite, user) -> {
if(invite.getEmail().equalsIgnoreCase(user.getEmail())){
ProjectInvite projectInvite = projectInviteRepository.save(invite.open());
return projectService.addPartner(projectInvite.getTarget().getId(), user.getId(), projectInvite.getOrganisation().getId()).andOnSuccess(pu -> {
pu.setInvite(projectInvite);
projectUserRepository.save(pu.accept());
return serviceSuccess();
});
}
LOG.error(format("Invited email address not the same as the users email address %s => %s ", user.getEmail(), invite.getEmail()));
Error e = new Error("Invited email address not the same as the users email address", HttpStatus.NOT_ACCEPTABLE);
return serviceFailure(e);
});
}
@Override
public ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash) {
return super.checkUserExistsForInvite(inviteHash);
}
@Override
public ServiceResult<UserResource> getUserByInviteHash(String hash) {
return getByHash(hash)
.andOnSuccessReturn(i -> userRepository.findByEmail(i.getEmail()).map(userMapper::mapToResource))
.andOnSuccess(u -> u.map(ServiceResult::serviceSuccess).orElseGet(() -> serviceFailure(notFoundError(UserResource.class))));
}
private ServiceResult<Void> validateProjectInviteResource(ProjectInviteResource projectInviteResource) {
if (StringUtils.isEmpty(projectInviteResource.getEmail()) || StringUtils.isEmpty(projectInviteResource.getName())
|| projectInviteResource.getProject() == null || projectInviteResource.getOrganisation() == null ){
return serviceFailure(PROJECT_INVITE_INVALID);
}
return serviceSuccess();
}
private ServiceResult<Void> validateUserNotAlreadyInvited(ProjectInviteResource invite) {
List<ProjectInvite> existingInvites = projectInviteRepository.findByProjectIdAndEmail(invite.getProject(), invite.getEmail());
return existingInvites.isEmpty() ? serviceSuccess() : serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_ALREADY_INVITED_ON_PROJECT);
}
private ServiceResult<Void> validateTargetUserIsValid(ProjectInviteResource invite) {
String targetEmail = invite.getEmail();
Optional<User> existingUser = userRepository.findByEmail(targetEmail);
List<Long> usersOrganisations = existingUser.map(organisationRepository::findDistinctByUsers)
.map(organisations -> simpleMap(organisations, Organisation::getId))
.orElse(emptyList());
if (usersOrganisations.isEmpty()) {
serviceSuccess();
}
return existingUser.map(user ->
validateUserIsInSameOrganisation(invite, usersOrganisations).andOnSuccess(() ->
validateUserIsNotAlreadyPartnerInOrganisation(invite, user))).
orElse(serviceSuccess());
}
private ServiceResult<Void> validateUserIsInSameOrganisation(ProjectInviteResource invite, List<Long> usersOrganisations) {
if (!usersOrganisations.contains(invite.getOrganisation())) {
return serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_NOT_IN_CORRECT_ORGANISATION);
}
return serviceSuccess();
}
private ServiceResult<Void> validateUserIsNotAlreadyPartnerInOrganisation(ProjectInviteResource invite, User user) {
ProjectUser existingUserEntryForOrganisation = projectUserRepository.findOneByProjectIdAndUserIdAndOrganisationIdAndRole(invite.getProject(), invite.getOrganisation(), user.getId(), PROJECT_PARTNER);
return existingUserEntryForOrganisation == null ? serviceSuccess() :
serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_ALREADY_EXISTS_ON_PROJECT);
}
}
|
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/invite/transactional/ProjectInviteServiceImpl.java
|
package org.innovateuk.ifs.invite.transactional;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.HibernateValidator;
import org.innovateuk.ifs.commons.error.Error;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.invite.domain.ProjectInvite;
import org.innovateuk.ifs.invite.mapper.ProjectInviteMapper;
import org.innovateuk.ifs.invite.repository.InviteRepository;
import org.innovateuk.ifs.invite.repository.ProjectInviteRepository;
import org.innovateuk.ifs.invite.resource.ProjectInviteResource;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.innovateuk.ifs.project.core.repository.ProjectUserRepository;
import org.innovateuk.ifs.project.core.transactional.ProjectService;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.user.domain.User;
import org.innovateuk.ifs.user.mapper.UserMapper;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.commons.error.CommonErrors.badRequestError;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.invite.domain.Invite.generateInviteHash;
import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_PARTNER;
import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@Service
public class ProjectInviteServiceImpl extends InviteService<ProjectInvite> implements ProjectInviteService {
private static final Log LOG = LogFactory.getLog(ProjectInviteServiceImpl.class);
@Value("${ifs.web.baseURL}")
private String webBaseUrl;
@Autowired
private ProjectInviteMapper inviteMapper;
@Autowired
private ProjectInviteRepository projectInviteRepository;
@Autowired
private ProjectService projectService;
@Autowired
private UserMapper userMapper;
@Autowired
private ProjectUserRepository projectUserRepository;
@Autowired
private OrganisationRepository organisationRepository;
private LocalValidatorFactoryBean validator;
public ProjectInviteServiceImpl() {
validator = new LocalValidatorFactoryBean();
validator.setProviderClass(HibernateValidator.class);
validator.afterPropertiesSet();
}
@Override
protected Class<ProjectInvite> getInviteClass() {
return ProjectInvite.class;
}
@Override
protected InviteRepository<ProjectInvite> getInviteRepository() {
return projectInviteRepository;
}
@Override
@Transactional
public ServiceResult<Void> saveProjectInvite(ProjectInviteResource projectInviteResource) {
return validateProjectInviteResource(projectInviteResource).andOnSuccess(() ->
validateUserNotAlreadyInvited(projectInviteResource).andOnSuccess(() ->
validateTargetUserIsValid(projectInviteResource).andOnSuccess(() -> {
ProjectInvite projectInvite = inviteMapper.mapToDomain(projectInviteResource);
Errors errors = new BeanPropertyBindingResult(projectInvite, projectInvite.getClass().getName());
validator.validate(projectInvite, errors);
if (errors.hasErrors()) {
errors.getFieldErrors().stream().peek(e -> LOG.debug(format("Field error: %s ", e.getField())));
return serviceFailure(badRequestError(errors.toString()));
} else {
projectInvite.setHash(generateInviteHash());
projectInviteRepository.save(projectInvite);
return serviceSuccess();
}
})));
}
private ProjectInviteResource mapInviteToInviteResource(ProjectInvite invite) {
ProjectInviteResource inviteResource = inviteMapper.mapToResource(invite);
Organisation organisation = organisationRepository.findOne(inviteResource.getLeadOrganisationId());
inviteResource.setLeadOrganisation(organisation.getName());
ProjectResource project = projectService.getProjectById(inviteResource.getProject()).getSuccess();
inviteResource.setApplicationId(project.getApplication());
return inviteResource;
}
@Override
public ServiceResult<ProjectInviteResource> getInviteByHash(String hash) {
return getByHash(hash).andOnSuccessReturn(this::mapInviteToInviteResource);
}
@Override
public ServiceResult<List<ProjectInviteResource>> getInvitesByProject(Long projectId) {
if(projectId == null) {
return serviceFailure(new Error(PROJECT_INVITE_INVALID_PROJECT_ID, NOT_FOUND));
}
List<ProjectInvite> invites = projectInviteRepository.findByProjectId(projectId);
List<ProjectInviteResource> inviteResources = invites.stream().map(this::mapInviteToInviteResource).collect(Collectors.toList());
return serviceSuccess(Lists.newArrayList(inviteResources));
}
@Override
@Transactional
public ServiceResult<Void> acceptProjectInvite(String inviteHash, Long userId) {
return find(invite(inviteHash), user(userId)).andOnSuccess((invite, user) -> {
if(invite.getEmail().equalsIgnoreCase(user.getEmail())){
ProjectInvite projectInvite = projectInviteRepository.save(invite.open());
return projectService.addPartner(projectInvite.getTarget().getId(), user.getId(), projectInvite.getOrganisation().getId()).andOnSuccess(pu -> {
pu.setInvite(projectInvite);
projectUserRepository.save(pu.accept());
return serviceSuccess();
});
}
LOG.error(format("Invited email address not the same as the users email address %s => %s ", user.getEmail(), invite.getEmail()));
Error e = new Error("Invited email address not the same as the users email address", HttpStatus.NOT_ACCEPTABLE);
return serviceFailure(e);
});
}
@Override
public ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash) {
return super.checkUserExistsForInvite(inviteHash);
}
@Override
public ServiceResult<UserResource> getUserByInviteHash(String hash) {
return getByHash(hash)
.andOnSuccessReturn(i -> userRepository.findByEmail(i.getEmail()).map(userMapper::mapToResource))
.andOnSuccess(u -> u.map(ServiceResult::serviceSuccess).orElseGet(() -> serviceFailure(notFoundError(UserResource.class))));
}
private ServiceResult<Void> validateProjectInviteResource(ProjectInviteResource projectInviteResource) {
if (StringUtils.isEmpty(projectInviteResource.getEmail()) || StringUtils.isEmpty(projectInviteResource.getName())
|| projectInviteResource.getProject() == null ||projectInviteResource.getOrganisation() == null ){
return serviceFailure(PROJECT_INVITE_INVALID);
}
return serviceSuccess();
}
private ServiceResult<Void> validateUserNotAlreadyInvited(ProjectInviteResource invite) {
List<ProjectInvite> existingInvites = projectInviteRepository.findByProjectIdAndEmail(invite.getProject(), invite.getEmail());
return existingInvites.isEmpty() ? serviceSuccess() : serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_ALREADY_INVITED_ON_PROJECT);
}
private ServiceResult<Void> validateTargetUserIsValid(ProjectInviteResource invite) {
String targetEmail = invite.getEmail();
Optional<User> existingUser = userRepository.findByEmail(targetEmail);
List<Long> usersOrganisations = existingUser.map(organisationRepository::findDistinctByUsers)
.map(organisations -> simpleMap(organisations, Organisation::getId))
.orElse(emptyList());
return existingUser.map(user ->
validateUserIsInSameOrganisation(invite, usersOrganisations).andOnSuccess(() ->
validateUserIsNotAlreadyPartnerInOrganisation(invite, user))).
orElse(serviceSuccess());
}
private ServiceResult<Void> validateUserIsInSameOrganisation(ProjectInviteResource invite, List usersOrganisations) {
if (usersOrganisations.isEmpty()) {
serviceSuccess();
}
if (!usersOrganisations.contains(invite.getOrganisation())) {
return serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_NOT_IN_CORRECT_ORGANISATION);
}
return serviceSuccess();
}
private ServiceResult<Void> validateUserIsNotAlreadyPartnerInOrganisation(ProjectInviteResource invite, User user) {
ProjectUser existingUserEntryForOrganisation = projectUserRepository.findOneByProjectIdAndUserIdAndOrganisationIdAndRole(invite.getProject(), invite.getOrganisation(), user.getId(), PROJECT_PARTNER);
return existingUserEntryForOrganisation == null ? serviceSuccess() :
serviceFailure(PROJECT_SETUP_INVITE_TARGET_USER_ALREADY_EXISTS_ON_PROJECT);
}
}
|
IFS-4725 - Parameter updated, isEmpty moved up.
|
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/invite/transactional/ProjectInviteServiceImpl.java
|
IFS-4725 - Parameter updated, isEmpty moved up.
|
|
Java
|
mit
|
dcd6e1a84699eae2cf8e535f4a4c7942e792949e
| 0
|
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
|
package com.worth.ifs.competition.transactional;
import com.worth.ifs.BaseServiceUnitTest;
import com.worth.ifs.application.domain.GuidanceRow;
import com.worth.ifs.application.domain.Question;
import com.worth.ifs.application.repository.GuidanceRowRepository;
import com.worth.ifs.application.repository.QuestionRepository;
import com.worth.ifs.commons.service.ServiceResult;
import com.worth.ifs.competition.resource.CompetitionSetupQuestionResource;
import com.worth.ifs.competition.resource.CompetitionSetupQuestionType;
import com.worth.ifs.competition.resource.GuidanceRowResource;
import com.worth.ifs.form.domain.FormInput;
import com.worth.ifs.form.mapper.GuidanceRowMapper;
import com.worth.ifs.form.repository.FormInputRepository;
import com.worth.ifs.form.resource.FormInputScope;
import com.worth.ifs.form.resource.FormInputType;
import org.junit.Test;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
import static com.worth.ifs.application.builder.GuidanceRowBuilder.newFormInputGuidanceRow;
import static com.worth.ifs.application.builder.GuidanceRowResourceBuilder.newFormInputGuidanceRowResourceBuilder;
import static com.worth.ifs.application.builder.QuestionBuilder.newQuestion;
import static com.worth.ifs.competition.builder.CompetitionSetupQuestionResourceBuilder.newCompetitionSetupQuestionResource;
import static com.worth.ifs.form.builder.FormInputBuilder.newFormInput;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests the CompetitionSetupQuestionServiceImpl with mocked repositories/mappers.
*/
public class CompetitionSetupQuestionServiceImplTest extends BaseServiceUnitTest<CompetitionSetupQuestionServiceImpl> {
@Override
protected CompetitionSetupQuestionServiceImpl supplyServiceUnderTest() {
return new CompetitionSetupQuestionServiceImpl();
}
private static String number = "number";
private static String shortTitle = CompetitionSetupQuestionType.SCOPE.getShortName();
private static String newShortTitle = "CannotBeSet";
private static String title = "title";
private static String subTitle = "subTitle";
private static String guidanceTitle = "guidanceTitle";
private static String guidance = "guidance";
private static Integer maxWords = 1;
private static String assessmentGuidance = "assessmentGuidance";
private static Integer assessmentMaxWords = 2;
private static Integer scoreTotal = 10;
@Mock
private QuestionRepository questionRepository;
@Mock
private FormInputRepository formInputRepository;
@Mock
private GuidanceRowMapper guidanceRowMapper;
@Mock
private GuidanceRowRepository guidanceRowRepository;
@Test
public void test_getByQuestionId() {
Long questionId = 1L;
List<GuidanceRow> guidanceRows = newFormInputGuidanceRow().build(1);
Question question = newQuestion().
withFormInputs(asList(
newFormInput()
.withType(FormInputType.FILEUPLOAD)
.withScope(FormInputScope.APPLICATION)
.build(),
newFormInput()
.withType(FormInputType.TEXTAREA)
.withScope(FormInputScope.APPLICATION)
.withWordCount(maxWords)
.withGuidanceTitle(guidanceTitle)
.withGuidanceAnswer(guidance)
.build(),
newFormInput()
.withType(FormInputType.TEXTAREA)
.withScope(FormInputScope.ASSESSMENT)
.withWordCount(assessmentMaxWords)
.withGuidanceTitle(assessmentGuidance)
.withGuidanceRows(guidanceRows)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_SCORE)
.withScope(FormInputScope.ASSESSMENT)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_RESEARCH_CATEGORY)
.withScope(FormInputScope.ASSESSMENT)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_APPLICATION_IN_SCOPE)
.withScope(FormInputScope.ASSESSMENT)
.build()
)
)
.withQuestionNumber(number)
.withAssessorMaximumScore(scoreTotal)
.withDescription(subTitle)
.withShortName(shortTitle)
.withName(title)
.withId(questionId)
.build();
when(questionRepository.findOne(questionId)).thenReturn(question);
when(guidanceRowMapper.mapToResource(guidanceRows)).thenReturn(new ArrayList<>());
ServiceResult<CompetitionSetupQuestionResource> result = service.getByQuestionId(questionId);
assertTrue(result.isSuccess());
CompetitionSetupQuestionResource resource = result.getSuccessObjectOrThrowException();
assertEquals(resource.getAppendix(), true);
assertEquals(resource.getScored(), true);
assertEquals(resource.getWrittenFeedback(), true);
assertEquals(resource.getScope(), true);
assertEquals(resource.getResearchCategoryQuestion(), true);
assertEquals(resource.getAssessmentGuidance(), assessmentGuidance);
assertEquals(resource.getAssessmentMaxWords(), assessmentMaxWords);
assertEquals(resource.getGuidanceTitle(), guidanceTitle);
assertEquals(resource.getMaxWords(), maxWords);
assertEquals(resource.getScoreTotal(), scoreTotal);
assertEquals(resource.getNumber(), number);
assertEquals(resource.getQuestionId(), questionId);
assertEquals(resource.getSubTitle(), subTitle);
assertEquals(resource.getShortTitle(), shortTitle);
assertEquals(resource.getTitle(), title);
assertEquals(resource.getGuidance(), guidance);
assertEquals(resource.getType(), CompetitionSetupQuestionType.SCOPE);
assertEquals(resource.getShortTitleEditable(), false);
verify(guidanceRowMapper).mapToResource(guidanceRows);
}
@Test
public void test_save() {
long questionId = 1L;
List<GuidanceRowResource> guidanceRows = newFormInputGuidanceRowResourceBuilder().build(1);
when(guidanceRowMapper.mapToDomain(guidanceRows)).thenReturn(new ArrayList<>());
CompetitionSetupQuestionResource resource = newCompetitionSetupQuestionResource()
.withAppendix(false)
.withGuidance(guidance)
.withGuidanceTitle(guidanceTitle)
.withMaxWords(maxWords)
.withNumber(number)
.withTitle(title)
.withShortTitle(newShortTitle)
.withSubTitle(subTitle)
.withQuestionId(questionId)
.withAssessmentGuidance(assessmentGuidance)
.withAssessmentMaxWords(assessmentMaxWords)
.withGuidanceRows(guidanceRows)
.withScored(true)
.withScoreTotal(scoreTotal)
.withWrittenFeedback(true)
.build();
Question question = newQuestion().
withShortName(CompetitionSetupQuestionType.SCOPE.getShortName()).build();
FormInput questionFormInput = newFormInput().build();
FormInput appendixFormInput = newFormInput().build();
FormInput researchCategoryQuestionFormInput = newFormInput().build();
FormInput scopeQuestionFormInput = newFormInput().build();
FormInput scoredQuestionFormInput = newFormInput().build();
FormInput writtenFeedbackFormInput = newFormInput().build();
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.APPLICATION, FormInputType.TEXTAREA)).thenReturn(questionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.APPLICATION, FormInputType.FILEUPLOAD)).thenReturn(appendixFormInput);
when(questionRepository.findOne(questionId)).thenReturn(question);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_RESEARCH_CATEGORY)).thenReturn(researchCategoryQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_APPLICATION_IN_SCOPE)).thenReturn(scopeQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_SCORE)).thenReturn(scoredQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.TEXTAREA)).thenReturn(writtenFeedbackFormInput);
doNothing().when(guidanceRowRepository).delete(writtenFeedbackFormInput.getGuidanceRows());
when(guidanceRowRepository.save(writtenFeedbackFormInput.getGuidanceRows())).thenReturn(writtenFeedbackFormInput.getGuidanceRows());
ServiceResult<CompetitionSetupQuestionResource> result = service.save(resource);
assertTrue(result.isSuccess());
assertNotEquals(question.getQuestionNumber(), number);
assertEquals(question.getDescription(), subTitle);
assertEquals(question.getName(), title);
assertEquals(questionFormInput.getGuidanceTitle(), guidanceTitle);
assertEquals(questionFormInput.getGuidanceAnswer(), guidance);
assertEquals(questionFormInput.getWordCount(), maxWords);
//Short name shouldn't be set on SCOPE question.
assertNotEquals(question.getShortName(), newShortTitle);
assertEquals(question.getShortName(), shortTitle);
assertEquals(appendixFormInput.getActive(), false);
assertEquals(researchCategoryQuestionFormInput.getActive(), true);
assertEquals(scopeQuestionFormInput.getActive(), true);
assertEquals(scoredQuestionFormInput.getActive(), true);
assertEquals(writtenFeedbackFormInput.getActive(), true);
verify(guidanceRowMapper).mapToDomain(guidanceRows);
}
}
|
ifs-data-service/src/test/java/com/worth/ifs/competition/transactional/CompetitionSetupQuestionServiceImplTest.java
|
package com.worth.ifs.competition.transactional;
import com.worth.ifs.BaseServiceUnitTest;
import com.worth.ifs.application.domain.GuidanceRow;
import com.worth.ifs.application.domain.Question;
import com.worth.ifs.application.repository.GuidanceRowRepository;
import com.worth.ifs.application.repository.QuestionRepository;
import com.worth.ifs.commons.service.ServiceResult;
import com.worth.ifs.competition.resource.CompetitionSetupQuestionResource;
import com.worth.ifs.competition.resource.CompetitionSetupQuestionType;
import com.worth.ifs.competition.resource.GuidanceRowResource;
import com.worth.ifs.form.domain.FormInput;
import com.worth.ifs.form.mapper.GuidanceRowMapper;
import com.worth.ifs.form.repository.FormInputRepository;
import com.worth.ifs.form.resource.FormInputScope;
import com.worth.ifs.form.resource.FormInputType;
import org.junit.Test;
import org.mockito.Mock;
import java.util.ArrayList;
import java.util.List;
import static com.worth.ifs.application.builder.GuidanceRowBuilder.newFormInputGuidanceRow;
import static com.worth.ifs.application.builder.GuidanceRowResourceBuilder.newFormInputGuidanceRowResourceBuilder;
import static com.worth.ifs.application.builder.QuestionBuilder.newQuestion;
import static com.worth.ifs.competition.builder.CompetitionSetupQuestionResourceBuilder.newCompetitionSetupQuestionResource;
import static com.worth.ifs.form.builder.FormInputBuilder.newFormInput;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Tests the CompetitionSetupQuestionServiceImpl with mocked repositories/mappers.
*/
public class CompetitionSetupQuestionServiceImplTest extends BaseServiceUnitTest<CompetitionSetupQuestionServiceImpl> {
@Override
protected CompetitionSetupQuestionServiceImpl supplyServiceUnderTest() {
return new CompetitionSetupQuestionServiceImpl();
}
private static String number = "number";
private static String shortTitle = CompetitionSetupQuestionType.SCOPE.getShortName();
private static String newShortTitle = "CannotBeSet";
private static String title = "title";
private static String subTitle = "subTitle";
private static String guidanceTitle = "guidanceTitle";
private static String guidance = "guidance";
private static Integer maxWords = 1;
private static String assessmentGuidance = "assessmentGuidance";
private static Integer assessmentMaxWords = 2;
private static Integer scoreTotal = 10;
@Mock
private QuestionRepository questionRepository;
@Mock
private FormInputRepository formInputRepository;
@Mock
private GuidanceRowMapper guidanceRowMapper;
@Mock
private GuidanceRowRepository guidanceRowRepository;
@Test
public void test_getByQuestionId() {
Long questionId = 1L;
List<GuidanceRow> guidanceRows = newFormInputGuidanceRow().build(1);
Question question = newQuestion().
withFormInputs(asList(
newFormInput()
.withType(FormInputType.FILEUPLOAD)
.withScope(FormInputScope.APPLICATION)
.build(),
newFormInput()
.withType(FormInputType.TEXTAREA)
.withScope(FormInputScope.APPLICATION)
.withWordCount(maxWords)
.withGuidanceTitle(guidanceTitle)
.withGuidanceAnswer(guidance)
.build(),
newFormInput()
.withType(FormInputType.TEXTAREA)
.withScope(FormInputScope.ASSESSMENT)
.withWordCount(assessmentMaxWords)
.withGuidanceAnswer(assessmentGuidance)
.withGuidanceRows(guidanceRows)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_SCORE)
.withScope(FormInputScope.ASSESSMENT)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_RESEARCH_CATEGORY)
.withScope(FormInputScope.ASSESSMENT)
.build(),
newFormInput()
.withType(FormInputType.ASSESSOR_APPLICATION_IN_SCOPE)
.withScope(FormInputScope.ASSESSMENT)
.build()
)
)
.withQuestionNumber(number)
.withAssessorMaximumScore(scoreTotal)
.withDescription(subTitle)
.withShortName(shortTitle)
.withName(title)
.withId(questionId)
.build();
when(questionRepository.findOne(questionId)).thenReturn(question);
when(guidanceRowMapper.mapToResource(guidanceRows)).thenReturn(new ArrayList<>());
ServiceResult<CompetitionSetupQuestionResource> result = service.getByQuestionId(questionId);
assertTrue(result.isSuccess());
CompetitionSetupQuestionResource resource = result.getSuccessObjectOrThrowException();
assertEquals(resource.getAppendix(), true);
assertEquals(resource.getScored(), true);
assertEquals(resource.getWrittenFeedback(), true);
assertEquals(resource.getScope(), true);
assertEquals(resource.getResearchCategoryQuestion(), true);
assertEquals(resource.getAssessmentGuidance(), assessmentGuidance);
assertEquals(resource.getAssessmentMaxWords(), assessmentMaxWords);
assertEquals(resource.getGuidanceTitle(), guidanceTitle);
assertEquals(resource.getMaxWords(), maxWords);
assertEquals(resource.getScoreTotal(), scoreTotal);
assertEquals(resource.getNumber(), number);
assertEquals(resource.getQuestionId(), questionId);
assertEquals(resource.getSubTitle(), subTitle);
assertEquals(resource.getShortTitle(), shortTitle);
assertEquals(resource.getTitle(), title);
assertEquals(resource.getGuidance(), guidance);
assertEquals(resource.getType(), CompetitionSetupQuestionType.SCOPE);
assertEquals(resource.getShortTitleEditable(), false);
verify(guidanceRowMapper).mapToResource(guidanceRows);
}
@Test
public void test_save() {
long questionId = 1L;
List<GuidanceRowResource> guidanceRows = newFormInputGuidanceRowResourceBuilder().build(1);
when(guidanceRowMapper.mapToDomain(guidanceRows)).thenReturn(new ArrayList<>());
CompetitionSetupQuestionResource resource = newCompetitionSetupQuestionResource()
.withAppendix(false)
.withGuidance(guidance)
.withGuidanceTitle(guidanceTitle)
.withMaxWords(maxWords)
.withNumber(number)
.withTitle(title)
.withShortTitle(newShortTitle)
.withSubTitle(subTitle)
.withQuestionId(questionId)
.withAssessmentGuidance(assessmentGuidance)
.withAssessmentMaxWords(assessmentMaxWords)
.withGuidanceRows(guidanceRows)
.withScored(true)
.withScoreTotal(scoreTotal)
.withWrittenFeedback(true)
.build();
Question question = newQuestion().
withShortName(CompetitionSetupQuestionType.SCOPE.getShortName()).build();
FormInput questionFormInput = newFormInput().build();
FormInput appendixFormInput = newFormInput().build();
FormInput researchCategoryQuestionFormInput = newFormInput().build();
FormInput scopeQuestionFormInput = newFormInput().build();
FormInput scoredQuestionFormInput = newFormInput().build();
FormInput writtenFeedbackFormInput = newFormInput().build();
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.APPLICATION, FormInputType.TEXTAREA)).thenReturn(questionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.APPLICATION, FormInputType.FILEUPLOAD)).thenReturn(appendixFormInput);
when(questionRepository.findOne(questionId)).thenReturn(question);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_RESEARCH_CATEGORY)).thenReturn(researchCategoryQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_APPLICATION_IN_SCOPE)).thenReturn(scopeQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.ASSESSOR_SCORE)).thenReturn(scoredQuestionFormInput);
when(formInputRepository.findByQuestionIdAndScopeAndType(questionId, FormInputScope.ASSESSMENT, FormInputType.TEXTAREA)).thenReturn(writtenFeedbackFormInput);
doNothing().when(guidanceRowRepository).delete(writtenFeedbackFormInput.getGuidanceRows());
when(guidanceRowRepository.save(writtenFeedbackFormInput.getGuidanceRows())).thenReturn(writtenFeedbackFormInput.getGuidanceRows());
ServiceResult<CompetitionSetupQuestionResource> result = service.save(resource);
assertTrue(result.isSuccess());
assertNotEquals(question.getQuestionNumber(), number);
assertEquals(question.getDescription(), subTitle);
assertEquals(question.getName(), title);
assertEquals(questionFormInput.getGuidanceTitle(), guidanceTitle);
assertEquals(questionFormInput.getGuidanceAnswer(), guidance);
assertEquals(questionFormInput.getWordCount(), maxWords);
//Short name shouldn't be set on SCOPE question.
assertNotEquals(question.getShortName(), newShortTitle);
assertEquals(question.getShortName(), shortTitle);
assertEquals(appendixFormInput.getActive(), false);
assertEquals(researchCategoryQuestionFormInput.getActive(), true);
assertEquals(scopeQuestionFormInput.getActive(), true);
assertEquals(scoredQuestionFormInput.getActive(), true);
assertEquals(writtenFeedbackFormInput.getActive(), true);
verify(guidanceRowMapper).mapToDomain(guidanceRows);
}
}
|
INFUND-6287 - AssessmentGuidance should be set from title not answer
Former-commit-id: 9f8354970e5419445e7c07c5db810bca9903b1c4
|
ifs-data-service/src/test/java/com/worth/ifs/competition/transactional/CompetitionSetupQuestionServiceImplTest.java
|
INFUND-6287 - AssessmentGuidance should be set from title not answer
|
|
Java
|
mit
|
7d5e029b4077df6cd44a6058aab5c65bce0c027a
| 0
|
RayTW/TetrisGame
|
package tetris.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import tetris.Config;
import tetris.GameEvent;
import tetris.GameLoop;
import util.AudioPlayer;
import util.Debug;
/**
* 此類別只做畫面處理,不做方塊移動運算,所有GameLoop類別所觸發的事件會通知此類別的tetrisEvent() method
*
* @author Ray
*
*/
public class GameView extends JComponent implements ViewDelegate {
private int mNextBoxCount = Config.get().getNextBoxs(); // 下次要出現的方塊可顯示個數
private int[][][] mBoxBuffer; // 下次要出現的方塊style
private int mBoxStartX; // 掉落方塊的初始位置x
private int mBoxStartY; // 掉落方塊的初始位置y
private int mGameScreenWidth; // 遊戲畫面寬
private int mGameScreenHeight; // 遊戲畫面高
private int mSingleBoxWidth; // 每個方塊格寬
private int mSingleBoxHeight; // 每個方塊格高
private int mRightNextBoxesX; // 右側方塊的位置x
private int mRightNextBoxesHeightSpacing; // 右側方塊的位置y間距
private int mScoreLocationY; // 分數顯示位置
private int mLevelLocationY; // 等級顯示位置
private int mGameOverLocationX; // 遊戲結束顯示位置x
private int mGameOverLocationY; // 遊戲結束顯示位置y
private int mNextRoundCountdownSecondLocationX; // 下局倒數秒數顯示位置x
private int mNextRoundCountdownSecondLocationY; // 下局倒數秒數顯示位置y
private int mLinesLocationY; // 方塊消除累計行數顯示位置
private Font mScoreFont;
private Image mCanvasBuffer = null;
private Color[] mColor = { null, new Color(0, 255, 255, 250), new Color(0, 0, 255, 250), new Color(0, 255, 0, 250),
new Color(255, 0, 0, 250), new Color(255, 255, 0, 250), new Color(255, 0, 255, 250),
new Color(50, 100, 150, 250) };
private Color mShadowColor = new Color(0, 0, 0, 128);
private GameLoop mGameLoop; // 遊戲邏輯(無畫面)
private AudioPlayer mBackgroundMusic;// 播放背景音樂
private InfoBar mInfoBar;
public GameView() {
mBackgroundMusic = playMusic("sound/music.wav");
}
public void initialize() {
mScoreFont = null;
Config config = Config.get();
mBoxStartX = config.convertValueViaScreenScale(62);
mBoxStartY = config.convertValueViaScreenScale(79);
mGameScreenWidth = config.convertValueViaScreenScale(350);
mGameScreenHeight = config.convertValueViaScreenScale(480);
mSingleBoxWidth = config.convertValueViaScreenScale(19);
mSingleBoxHeight = config.convertValueViaScreenScale(19);
mRightNextBoxesX = config.convertValueViaScreenScale(160);
mRightNextBoxesHeightSpacing = config.convertValueViaScreenScale(50);
// 分數位置
mLevelLocationY = Config.get().convertValueViaScreenScale(20);
mLinesLocationY = Config.get().convertValueViaScreenScale(45);
mScoreLocationY = Config.get().convertValueViaScreenScale(70);
//遊戲結束
mGameOverLocationX = Config.get().convertValueViaScreenScale(100);
mGameOverLocationY = Config.get().convertValueViaScreenScale(250);
mNextRoundCountdownSecondLocationX = Config.get().convertValueViaScreenScale(155);
mNextRoundCountdownSecondLocationY = Config.get().convertValueViaScreenScale(270);
// 分數、消除行數、等級
mInfoBar = new InfoBar();
// 建立遊戲邏輯
mGameLoop = new GameLoop();
// 設定使用GameView代理遊戲邏輯進行畫面的繪圖
mGameLoop.setDelegate(this);
// 設定方塊掉落秒數為
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
// 設定下次要出現的方塊style個數為顯示3個
mBoxBuffer = getBufBox(mGameLoop, mNextBoxCount);
// 啟動遊戲邏輯執行緒
mGameLoop.startGame();
// 設定畫面大小
setSize(mGameScreenWidth, mGameScreenHeight);
}
private AudioPlayer playMusic(String path) {
return playAudio(path, 0, 1);
}
private AudioPlayer playSound(String path) {
return playAudio(path, 1, Config.get().getSoundCacheCount());
}
private AudioPlayer playAudio(String path, int playCount, int cacheCount) {
AudioPlayer audio = new AudioPlayer();
path = "/" + path;
audio.loadAudio(path, this);
audio.setCacheCount(cacheCount);
audio.setPlayCount(playCount);// 播放次數
audio.play();
return audio;
}
// 接收鍵盤事件
public void keyCode(int code) {
if (mGameLoop.isGameOver()) {
return;
}
if (!mGameLoop.isPause()) {
switch (code) {
case KeyEvent.VK_UP:// 上,順轉方塊
mGameLoop.turnRight();
tetrisEvent(GameEvent.BOX_TURN, null);
break;
case KeyEvent.VK_DOWN:// 下,下移方塊
moveDown();
break;
case KeyEvent.VK_LEFT:// 左,左移方塊
mGameLoop.moveLeft();
break;
case KeyEvent.VK_RIGHT:// 右,右移方塊
mGameLoop.moveRight();
break;
case KeyEvent.VK_SPACE:// 空白鍵,快速掉落方塊
quickDown();
break;
case KeyEvent.VK_S:// S鍵,暫停
mGameLoop.pause();
break;
default:
}
} else {
if (code == KeyEvent.VK_R) {// R鍵,回到遊戲繼續
mGameLoop.rusme();
}
}
// 每次按了鍵盤就將畫面重繪
repaint();
}
private void moveDown(){
if(mGameLoop.moveDown()){
mInfoBar.addScore(Config.get().getMoveDownScore());
}
}
private void quickDown(){
int befor = mGameLoop.getNowBoxXY()[1];
mGameLoop.quickDown();
int after = mGameLoop.getNowBoxXY()[1];
//若方塊快速落到底,再另外加分數
int quickDownScore = after - befor;
if(quickDownScore > 0){
mInfoBar.addScore(quickDownScore * Config.get().getQuickDownScore());
}
}
// 雙緩衝區繪圖
@Override
public void paintComponent(Graphics g) {
Graphics canvas = null;
if (mCanvasBuffer == null) {
mCanvasBuffer = createImage(mGameScreenWidth, mGameScreenHeight);// 新建一張image的圖
} else {
mCanvasBuffer.getGraphics().clearRect(0, 0, mGameScreenWidth, mGameScreenHeight);
}
canvas = mCanvasBuffer.getGraphics();
// 把整個陣列要畫的圖,畫到暫存的畫布上去(即後景)
int[][] boxAry = mGameLoop.getBoxAry();
showBacegroundBox(boxAry, canvas);
// 畫掉落中的方塊
int[] xy = mGameLoop.getNowBoxXY();
int[][] box = mGameLoop.getNowBoxAry();
// 畫陰影
shadow(xy, box, canvas, mGameLoop.getDownY());
showDownBox(xy, box, canvas);
// 畫右邊下次要出現的方塊
showBufferBox(mBoxBuffer, canvas);
// 顯示分數
showInfoBar(mInfoBar, canvas);
// 顯示遊戲結束,並倒數秒數
showGameOver(mInfoBar, canvas);
// 將暫存的圖,畫到前景
g.drawImage(mCanvasBuffer, 0, 0, this);
}
// 畫定住的方塊與其他背景格子
private void showBacegroundBox(int[][] boxAry, Graphics buffImg) {
for (int i = 0; i < boxAry.length; i++) {
for (int j = 0; j < boxAry[i].length; j++) {
int style = boxAry[i][j];
if (style > 0) {// 畫定住的方塊
drawBox(style, j, i, buffImg);
} else {// 畫其他背景格子
buffImg.drawRect(mBoxStartX + (mSingleBoxWidth * j), mBoxStartY + (mSingleBoxHeight * i),
mSingleBoxWidth, mSingleBoxHeight);
}
}
}
}
// 畫掉落中的方塊
private void showDownBox(int[] xy, int[][] box, Graphics buffImg) {
int boxX = xy[0];
int boxY = xy[1];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int style = box[i][j];
if (style > 0) {
drawBox(style, (j + boxX), (i + boxY), buffImg);
}
}
}
}
// 畫右邊下次要出現的方塊
private void showBufferBox(int[][][] boxBuf, Graphics buffImg) {
for (int n = 0; n < boxBuf.length; n++) {
int[][] ary = boxBuf[n];
for (int i = 0; i < ary.length; i++) {
for (int j = 0; j < ary[i].length; j++) {
int style = ary[i][j];
if (style > 0) {
buffImg.setColor(mColor[style]);
buffImg.fill3DRect(mRightNextBoxesX + (mSingleBoxWidth * (j + 5)),
(n * mRightNextBoxesHeightSpacing) + (mSingleBoxHeight * (i + 5)), mSingleBoxWidth,
mSingleBoxHeight, true);
}
}
}
}
}
// 畫陰影
private void shadow(int[] xy, int[][] box, Graphics buffImg, int index) {
int boxX = xy[0];
// int boxY = xy[1];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int style = box[i][j];
if (style > 0) {
buffImg.setColor(mShadowColor);
buffImg.fill3DRect(mBoxStartX + (mSingleBoxWidth * (j + boxX)),
mBoxStartY + (mSingleBoxHeight * (i + index)), mSingleBoxWidth, mSingleBoxHeight, true);
}
}
}
}
private void showInfoBar(InfoBar info, Graphics buffImg) {
if (mScoreFont == null) {
Font currentFont = buffImg.getFont();
Font newFont = currentFont.deriveFont(Font.BOLD, Config.get().convertValueViaScreenScale(20));
mScoreFont = newFont;
}
// 調整分數字型
buffImg.setFont(mScoreFont);
buffImg.setColor(Color.RED);
buffImg.drawString("LEVEL : " + info.getLevel(), 2, mLevelLocationY);
buffImg.setColor(Color.BLACK);
buffImg.drawString("SCORE : " + info.getScore(), 2, mLinesLocationY);
buffImg.setColor(Color.BLUE);
buffImg.drawString("LINES : " + info.getCleanedCount(), 2, mScoreLocationY);
}
private void showGameOver(InfoBar info, Graphics buffImg){
if(mGameLoop.isGameOver()){
buffImg.setColor(Color.DARK_GRAY);
buffImg.drawString("GAME OVER", mGameOverLocationX, mGameOverLocationY);
buffImg.drawString(String.valueOf(info.getWaitNextRoundSecond() + 1), mNextRoundCountdownSecondLocationX, mNextRoundCountdownSecondLocationY);
}
}
/**
* 畫每個小格子
*
* @param style
* @param x
* @param y
* @param buffImg
*/
public void drawBox(int style, int x, int y, Graphics buffImg) {
buffImg.setColor(mColor[style]);
buffImg.fill3DRect(mBoxStartX + (mSingleBoxWidth * x), mBoxStartY + (mSingleBoxHeight * y), mSingleBoxWidth,
mSingleBoxHeight, true);
buffImg.setColor(Color.BLACK);
}
/**
* 將下個方塊字串轉成2維方塊陣列,以便繪圖
*
* @param bufbox
* @param tetris
* @return
*/
public int[][][] getBufBox(GameLoop tetris, int cnt) {
String[] bufbox = tetris.getAnyCountBox(cnt);
int[][][] ary = new int[bufbox.length][][];
for (int i = 0; i < bufbox.length; i++) {
ary[i] = tetris.createBox(Integer.parseInt(bufbox[i]));
}
return ary;
}
/**
* 所有
*/
@Override
public void tetrisEvent(GameEvent code, String data) {
// 收到重畫自己畫面的陣列
if (GameEvent.REPAINT == code) {
repaint();
return;
}
if (GameEvent.BOX_TURN == code) {
playSound("sound/turn.wav");
return;
}
// 方塊落到底
if (GameEvent.BOX_DOWN == code) {
//播放方塊掉落音效
playSound("sound/down.wav");
return;
}
// 建立完下一個方塊
if (GameEvent.BOX_NEXT == code) {
mBoxBuffer = getBufBox(mGameLoop, mNextBoxCount);
return;
}
// 有方塊可清除,將要清除方塊,可取得要消去的方塊資料
if (GameEvent.CLEANING_LINE == code) {
Debug.get().println("有方塊可清除,將要清除方塊,可取得要消去的方塊資料");
return;
}
// 方塊清除完成
if (GameEvent.CLEANED_LINE == code) {
Debug.get().println("方塊清除完成" + data);
String[] lines = data.split("[,]", -1);
mInfoBar.addCleanedCount(lines.length);
mInfoBar.addScore(Config.get().getCleanLinesScore(lines.length));
if(tryLevelUp()){
Debug.get().println("提升等級!!");
}
return;
}
// 計算自己垃圾方塊數
if (GameEvent.BOX_GARBAGE == code) {
return;
}
// 方塊頂到最高處,遊戲結束
if (GameEvent.GAME_OVER == code) {
mInfoBar.setWaitNextRoundSecond(Config.get().getNextRoundDelaySecond());
while(mInfoBar.getWaitNextRoundSecond() > 0){
repaint();
Debug.get().println(mInfoBar.getWaitNextRoundSecond() + "秒後開始新局...");
mInfoBar.addWaitNextRoundSecond(-1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 重置分數
mInfoBar.initialize();
// 清除全畫面方塊
mGameLoop.clearBox();
// 設定方塊掉落秒數
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
// 當方塊到頂時,會自動將GameOver設為true,因此下次要開始時需設定遊戲為false表示可進行遊戲
mGameLoop.setGameOver(false);
}
return;
}
/**
* 試著計算是否提升等級1級,並重設方塊掉落速度
*/
private boolean tryLevelUp(){
int currentLevel = mInfoBar.getLevel();
int newLevel = Config.get().linesConvertLevel(mInfoBar.getCleanedCount());
if(currentLevel != newLevel){
mInfoBar.setLevel(newLevel);
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
return true;
}
return false;
}
}
|
src/tetris/view/GameView.java
|
package tetris.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import tetris.Config;
import tetris.GameEvent;
import tetris.GameLoop;
import util.AudioPlayer;
import util.Debug;
/**
* 此類別只做畫面處理,不做方塊移動運算,所有GameLoop類別所觸發的事件會通知此類別的tetrisEvent() method
*
* @author Ray
*
*/
public class GameView extends JComponent implements ViewDelegate {
private int mNextBoxCount = Config.get().getNextBoxs(); // 下次要出現的方塊可顯示個數
private int[][][] mBoxBuffer; // 下次要出現的方塊style
private int mBoxStartX; // 掉落方塊的初始位置x
private int mBoxStartY; // 掉落方塊的初始位置y
private int mGameScreenWidth; // 遊戲畫面寬
private int mGameScreenHeight; // 遊戲畫面高
private int mSingleBoxWidth; // 每個方塊格寬
private int mSingleBoxHeight; // 每個方塊格高
private int mRightNextBoxesX; // 右側方塊的位置x
private int mRightNextBoxesHeightSpacing; // 右側方塊的位置y間距
private int mScoreLocationY; // 分數顯示位置
private int mLevelLocationY; // 等級顯示位置
private int mGameOverLocationX; // 遊戲結束顯示位置x
private int mGameOverLocationY; // 遊戲結束顯示位置y
private int mNextRoundCountdownSecondLocationX; // 下局倒數秒數顯示位置x
private int mNextRoundCountdownSecondLocationY; // 下局倒數秒數顯示位置y
private int mLinesLocationY; // 方塊消除累計行數顯示位置
private Font mScoreFont;
private Image mCanvasBuffer = null;
private Color[] mColor = { null, new Color(0, 255, 255, 250), new Color(0, 0, 255, 250), new Color(0, 255, 0, 250),
new Color(255, 0, 0, 250), new Color(255, 255, 0, 250), new Color(255, 0, 255, 250),
new Color(50, 100, 150, 250) };
private Color mShadowColor = new Color(0, 0, 0, 128);
private GameLoop mGameLoop; // 遊戲邏輯(無畫面)
private AudioPlayer mBackgroundMusic;// 播放背景音樂
private InfoBar mInfoBar;
public GameView() {
mBackgroundMusic = playMusic("sound/music.wav");
}
public void initialize() {
mScoreFont = null;
Config config = Config.get();
mBoxStartX = config.convertValueViaScreenScale(62);
mBoxStartY = config.convertValueViaScreenScale(79);
mGameScreenWidth = config.convertValueViaScreenScale(350);
mGameScreenHeight = config.convertValueViaScreenScale(480);
mSingleBoxWidth = config.convertValueViaScreenScale(19);
mSingleBoxHeight = config.convertValueViaScreenScale(19);
mRightNextBoxesX = config.convertValueViaScreenScale(160);
mRightNextBoxesHeightSpacing = config.convertValueViaScreenScale(50);
// 分數位置
mLevelLocationY = Config.get().convertValueViaScreenScale(20);
mLinesLocationY = Config.get().convertValueViaScreenScale(45);
mScoreLocationY = Config.get().convertValueViaScreenScale(70);
//遊戲結束
mGameOverLocationX = Config.get().convertValueViaScreenScale(100);
mGameOverLocationY = Config.get().convertValueViaScreenScale(250);
mNextRoundCountdownSecondLocationX = Config.get().convertValueViaScreenScale(155);
mNextRoundCountdownSecondLocationY = Config.get().convertValueViaScreenScale(270);
// 分數、消除行數、等級
mInfoBar = new InfoBar();
// 建立遊戲邏輯
mGameLoop = new GameLoop();
// 設定使用GameView代理遊戲邏輯進行畫面的繪圖
mGameLoop.setDelegate(this);
// 設定方塊掉落秒數為
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
// 設定下次要出現的方塊style個數為顯示3個
mBoxBuffer = getBufBox(mGameLoop, mNextBoxCount);
// 啟動遊戲邏輯執行緒
mGameLoop.startGame();
// 設定畫面大小
setSize(mGameScreenWidth, mGameScreenHeight);
}
private AudioPlayer playMusic(String path) {
return playAudio(path, 0, 1);
}
private AudioPlayer playSound(String path) {
return playAudio(path, 1, Config.get().getSoundCacheCount());
}
private AudioPlayer playAudio(String path, int playCount, int cacheCount) {
AudioPlayer audio = new AudioPlayer();
path = "/" + path;
audio.loadAudio(path, this);
audio.setCacheCount(cacheCount);
audio.setPlayCount(playCount);// 播放次數
audio.play();
return audio;
}
// 接收鍵盤事件
public void keyCode(int code) {
if (mGameLoop.isGameOver()) {
return;
}
if (!mGameLoop.isPause()) {
switch (code) {
case KeyEvent.VK_UP:// 上,順轉方塊
mGameLoop.turnRight();
tetrisEvent(GameEvent.BOX_TURN, null);
break;
case KeyEvent.VK_DOWN:// 下,下移方塊
moveDown();
break;
case KeyEvent.VK_LEFT:// 左,左移方塊
mGameLoop.moveLeft();
break;
case KeyEvent.VK_RIGHT:// 右,右移方塊
mGameLoop.moveRight();
break;
case KeyEvent.VK_SPACE:// 空白鍵,快速掉落方塊
quickDown();
break;
case KeyEvent.VK_S:// S鍵,暫停
mGameLoop.pause();
break;
default:
}
} else {
if (code == KeyEvent.VK_R) {// R鍵,回到遊戲繼續
mGameLoop.rusme();
}
}
// 每次按了鍵盤就將畫面重繪
repaint();
}
private void moveDown(){
if(mGameLoop.moveDown()){
mInfoBar.addScore(Config.get().getMoveDownScore());
}
}
private void quickDown(){
int befor = mGameLoop.getNowBoxXY()[1];
mGameLoop.quickDown();
int after = mGameLoop.getNowBoxXY()[1];
//若方塊快速落到底,再另外加分數
int quickDownScore = after - befor;
if(quickDownScore > 0){
mInfoBar.addScore(quickDownScore * Config.get().getQuickDownScore());
}
}
// 雙緩衝區繪圖
@Override
public void paintComponent(Graphics g) {
Graphics canvas = null;
if (mCanvasBuffer == null) {
mCanvasBuffer = createImage(mGameScreenWidth, mGameScreenHeight);// 新建一張image的圖
} else {
mCanvasBuffer.getGraphics().clearRect(0, 0, mGameScreenWidth, mGameScreenHeight);
}
canvas = mCanvasBuffer.getGraphics();
// 把整個陣列要畫的圖,畫到暫存的畫布上去(即後景)
int[][] boxAry = mGameLoop.getBoxAry();
showBacegroundBox(boxAry, canvas);
// 畫掉落中的方塊
int[] xy = mGameLoop.getNowBoxXY();
int[][] box = mGameLoop.getNowBoxAry();
// 畫陰影
shadow(xy, box, canvas, mGameLoop.getDownY());
showDownBox(xy, box, canvas);
// 畫右邊下次要出現的方塊
showBufferBox(mBoxBuffer, canvas);
// 顯示分數
showInfoBar(mInfoBar, canvas);
// 顯示遊戲結束,並倒數秒數
showGameOver(mInfoBar, canvas);
// 將暫存的圖,畫到前景
g.drawImage(mCanvasBuffer, 0, 0, this);
}
// 畫定住的方塊與其他背景格子
private void showBacegroundBox(int[][] boxAry, Graphics buffImg) {
for (int i = 0; i < boxAry.length; i++) {
for (int j = 0; j < boxAry[i].length; j++) {
int style = boxAry[i][j];
if (style > 0) {// 畫定住的方塊
drawBox(style, j, i, buffImg);
} else {// 畫其他背景格子
buffImg.drawRect(mBoxStartX + (mSingleBoxWidth * j), mBoxStartY + (mSingleBoxHeight * i),
mSingleBoxWidth, mSingleBoxHeight);
}
}
}
}
// 畫掉落中的方塊
private void showDownBox(int[] xy, int[][] box, Graphics buffImg) {
int boxX = xy[0];
int boxY = xy[1];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int style = box[i][j];
if (style > 0) {
drawBox(style, (j + boxX), (i + boxY), buffImg);
}
}
}
}
// 畫右邊下次要出現的方塊
private void showBufferBox(int[][][] boxBuf, Graphics buffImg) {
for (int n = 0; n < boxBuf.length; n++) {
int[][] ary = boxBuf[n];
for (int i = 0; i < ary.length; i++) {
for (int j = 0; j < ary[i].length; j++) {
int style = ary[i][j];
if (style > 0) {
buffImg.setColor(mColor[style]);
buffImg.fill3DRect(mRightNextBoxesX + (mSingleBoxWidth * (j + 5)),
(n * mRightNextBoxesHeightSpacing) + (mSingleBoxHeight * (i + 5)), mSingleBoxWidth,
mSingleBoxHeight, true);
}
}
}
}
}
// 畫陰影
private void shadow(int[] xy, int[][] box, Graphics buffImg, int index) {
int boxX = xy[0];
// int boxY = xy[1];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int style = box[i][j];
if (style > 0) {
buffImg.setColor(mShadowColor);
buffImg.fill3DRect(mBoxStartX + (mSingleBoxWidth * (j + boxX)),
mBoxStartY + (mSingleBoxHeight * (i + index)), mSingleBoxWidth, mSingleBoxHeight, true);
}
}
}
}
private void showInfoBar(InfoBar info, Graphics buffImg) {
if (mScoreFont == null) {
Font currentFont = buffImg.getFont();
Font newFont = currentFont.deriveFont(Font.BOLD, Config.get().convertValueViaScreenScale(20));
mScoreFont = newFont;
}
// 調整分數字型
buffImg.setFont(mScoreFont);
buffImg.setColor(Color.RED);
buffImg.drawString("LEVEL : " + info.getLevel(), 2, mLevelLocationY);
buffImg.setColor(Color.BLACK);
buffImg.drawString("SCORE : " + info.getScore(), 2, mLinesLocationY);
buffImg.setColor(Color.BLUE);
buffImg.drawString("LINES : " + info.getCleanedCount(), 2, mScoreLocationY);
}
private void showGameOver(InfoBar info, Graphics buffImg){
if(mGameLoop.isGameOver()){
buffImg.setColor(Color.DARK_GRAY);
buffImg.drawString("GAME OVER", mGameOverLocationX, mGameOverLocationY);
buffImg.drawString(String.valueOf(info.getWaitNextRoundSecond() + 1), mNextRoundCountdownSecondLocationX, mNextRoundCountdownSecondLocationY);
}
}
/**
* 畫每個小格子
*
* @param style
* @param x
* @param y
* @param buffImg
*/
public void drawBox(int style, int x, int y, Graphics buffImg) {
buffImg.setColor(mColor[style]);
buffImg.fill3DRect(mBoxStartX + (mSingleBoxWidth * x), mBoxStartY + (mSingleBoxHeight * y), mSingleBoxWidth,
mSingleBoxHeight, true);
buffImg.setColor(Color.BLACK);
}
/**
* 將下個方塊字串轉成2維方塊陣列,以便繪圖
*
* @param bufbox
* @param tetris
* @return
*/
public int[][][] getBufBox(GameLoop tetris, int cnt) {
String[] bufbox = tetris.getAnyCountBox(cnt);
int[][][] ary = new int[bufbox.length][][];
for (int i = 0; i < bufbox.length; i++) {
ary[i] = tetris.createBox(Integer.parseInt(bufbox[i]));
}
return ary;
}
/**
* 所有
*/
@Override
public void tetrisEvent(GameEvent code, String data) {
// 收到重畫自己畫面的陣列
if (GameEvent.REPAINT == code) {
repaint();
return;
}
if (GameEvent.BOX_TURN == code) {
playSound("sound/turn.wav");
return;
}
// 方塊落到底
if (GameEvent.BOX_DOWN == code) {
//播放方塊掉落音效
playSound("sound/down.wav");
return;
}
// 建立完下一個方塊
if (GameEvent.BOX_NEXT == code) {
mBoxBuffer = getBufBox(mGameLoop, mNextBoxCount);
return;
}
// 有方塊可清除,將要清除方塊,可取得要消去的方塊資料
if (GameEvent.CLEANING_LINE == code) {
Debug.get().println("有方塊可清除,將要清除方塊,可取得要消去的方塊資料");
return;
}
// 方塊清除完成
if (GameEvent.CLEANED_LINE == code) {
Debug.get().println("方塊清除完成" + data);
String[] lines = data.split("[,]", -1);
mInfoBar.addCleanedCount(lines.length);
mInfoBar.addScore(Config.get().getCleanLinesScore(lines.length));
if(tryLevelUp()){
Debug.get().println("提升等級!!");
}
return;
}
// 計算自己垃圾方塊數
if (GameEvent.BOX_GARBAGE == code) {
return;
}
// 方塊頂到最高處,遊戲結束
if (GameEvent.GAME_OVER == code) {
mInfoBar.setWaitNextRoundSecond(Config.get().getNextRoundDelaySecond());
while(mInfoBar.getWaitNextRoundSecond() > 0){
repaint();
Debug.get().println(mInfoBar.getWaitNextRoundSecond() + "秒後開始新局...");
mInfoBar.addWaitNextRoundSecond(-1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 重置分數
mInfoBar.initialize();
// 清除全畫面方塊
mGameLoop.clearBox();
// 設定方塊掉落秒數
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
// 當方塊到頂時,會自動將GameOver設為true,因此下次要開始時需設定遊戲為false表示可進行遊戲
mGameLoop.setGameOver(false);
}
return;
}
/**
* 試著計算是否提升等級1級,並重設方塊掉落速度
*/
private boolean tryLevelUp(){
int currentLevel = mInfoBar.getLevel();
int newLevel = Config.get().linesConvertLevel(mInfoBar.getCleanedCount());
if(currentLevel != newLevel){
mInfoBar.setLevel(newLevel);
mGameLoop.setSec(Config.get().getBoxFallSpeed(mInfoBar.getLevel()));
return true;
}
return false;
}
public void objEvent(String code, Object obj) {
}
}
|
removed : 移除無意義的method。
|
src/tetris/view/GameView.java
|
removed : 移除無意義的method。
|
|
Java
|
mit
|
54f38d3e7337ec432d9f4860d0bb06f8c156d68f
| 0
|
bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula,bkahlert/com.bkahlert.nebula
|
package com.bkahlert.nebula.widgets.browser;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.ProgressAdapter;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import com.bkahlert.nebula.utils.CompletedFuture;
import com.bkahlert.nebula.utils.EventDelegator;
import com.bkahlert.nebula.utils.ExecUtils;
import com.bkahlert.nebula.utils.HandlerUtils;
import com.bkahlert.nebula.utils.IConverter;
import com.bkahlert.nebula.utils.SWTUtils;
import com.bkahlert.nebula.utils.colors.RGB;
import com.bkahlert.nebula.widgets.browser.extended.html.Anker;
import com.bkahlert.nebula.widgets.browser.extended.html.Element;
import com.bkahlert.nebula.widgets.browser.extended.html.IAnker;
import com.bkahlert.nebula.widgets.browser.extended.html.IElement;
import com.bkahlert.nebula.widgets.browser.listener.IAnkerListener;
import com.bkahlert.nebula.widgets.browser.listener.IDNDListener;
import com.bkahlert.nebula.widgets.browser.listener.IFocusListener;
import com.bkahlert.nebula.widgets.browser.listener.IMouseListener;
import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner;
import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner.BrowserStatus;
public class Browser extends Composite implements IBrowser {
private static Logger LOGGER = Logger.getLogger(Browser.class);
private static final int STYLES = SWT.INHERIT_FORCE;
public static final String FOCUS_CONTROL_ID = "com.bkahlert.nebula.browser";
private org.eclipse.swt.browser.Browser browser;
private BrowserScriptRunner browserScriptRunner;
private boolean initWithSystemBackgroundColor;
private boolean textSelectionsDisabled = false;
private boolean settingUri = false;
private boolean allowLocationChange = false;
private Rectangle cachedContentBounds = null;
private final List<IAnkerListener> ankerListeners = new ArrayList<IAnkerListener>();
private final List<IMouseListener> mouseListeners = new ArrayList<IMouseListener>();
private final List<IFocusListener> focusListeners = new ArrayList<IFocusListener>();
private final List<IDNDListener> dndListeners = new ArrayList<IDNDListener>();
/**
* Constructs a new {@link Browser} with the given styles.
*
* @param parent
* @param style
* if {@link SWT#INHERIT_FORCE}) is set the loaded page's
* background is replaced by the inherited background color
*/
public Browser(Composite parent, int style) {
super(parent, style | SWT.EMBEDDED & ~STYLES);
this.setLayout(new FillLayout());
this.initWithSystemBackgroundColor = (style & SWT.INHERIT_FORCE) != 0;
this.browser = new org.eclipse.swt.browser.Browser(this, SWT.NONE);
this.browser.setVisible(false);
this.browserScriptRunner = new BrowserScriptRunner(this.browser) {
@Override
public void scriptAboutToBeSentToBrowser(String script) {
Browser.this.scriptAboutToBeSentToBrowser(script);
}
@Override
public void scriptReturnValueReceived(Object returnValue) {
Browser.this.scriptReturnValueReceived(returnValue);
}
};
new BrowserFunction(this.browser, "__mouseenter") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
Browser.this.fireAnkerHover((String) arguments[0], true);
}
return null;
}
};
new BrowserFunction(this.browser, "__mouseleave") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
Browser.this.fireAnkerHover((String) arguments[0], false);
}
return null;
}
};
new BrowserFunction(this.browser, "__mousemove") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 2
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)) {
Browser.this.fireMouseMove((Double) arguments[0],
(Double) arguments[1]);
}
return null;
}
};
new BrowserFunction(this.browser, "__mousedown") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireMouseDown((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__mouseup") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireMouseUp((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__click") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireClicked((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__focusgained") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
final IElement element = new Element((String) arguments[0]);
Browser.this.fireFocusGained(element);
}
return null;
}
};
new BrowserFunction(this.browser, "__focuslost") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
final IElement element = new Element((String) arguments[0]);
Browser.this.fireFocusLost(element);
}
return null;
}
};
new BrowserFunction(this.browser, "__resize") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof Double)
&& (arguments[3] == null || arguments[3] instanceof Double)) {
Browser.this.cachedContentBounds = new Rectangle(
arguments[0] != null ? (int) Math.round((Double) arguments[0])
: 0,
arguments[1] != null ? (int) Math
.round((Double) arguments[1]) : 0,
arguments[2] != null ? (int) Math
.round((Double) arguments[2])
: Integer.MAX_VALUE,
arguments[3] != null ? (int) Math
.round((Double) arguments[3])
: Integer.MAX_VALUE);
}
return null;
}
};
new BrowserFunction(this.browser, "__dragStart") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4 && arguments[0] instanceof Double
&& arguments[1] instanceof Double
&& arguments[2] instanceof String
&& arguments[3] instanceof String) {
long offsetX = Math.round((Double) arguments[0]);
long offsetY = Math.round((Double) arguments[1]);
String mimeType = (String) arguments[2];
String data = (String) arguments[3];
Browser.this
.fireDragStart(offsetX, offsetY, mimeType, data);
}
return null;
}
};
new BrowserFunction(this.browser, "__drop") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4 && arguments[0] instanceof Double
&& arguments[1] instanceof Double
&& arguments[2] instanceof String
&& arguments[3] instanceof String) {
long offsetX = Math.round((Double) arguments[0]);
long offsetY = Math.round((Double) arguments[1]);
String mimeType = (String) arguments[2];
String data = (String) arguments[3];
Browser.this.fireDrop(offsetX, offsetY, mimeType, data);
}
return null;
}
};
this.browser.addLocationListener(new LocationAdapter() {
@Override
public void changing(LocationEvent event) {
if (!Browser.this.settingUri) {
event.doit = Browser.this.allowLocationChange
|| Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADING;
}
}
});
HandlerUtils.activateCustomPasteHandlerConsideration(this.browser,
FOCUS_CONTROL_ID, "application/x-java-file-list", "image");
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
HandlerUtils
.deactivateCustomPasteHandlerConsideration(Browser.this.browser);
}
});
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADING) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.CANCELLED);
}
Browser.this.browserScriptRunner.dispose();
Browser.this.monitor.notifyAll();
}
}
});
}
private boolean eventCatchScriptInjected = false;
/**
* Injects the code needed for {@link #addAnkerListener(IAnkerListener)},
* {@link #addFokusListener(IFocusListener)} and
* {@link #addDNDListener(IFocusListener)} to work.
* <p>
* The JavaScript remembers a successful injection in case to consecutive
* calls are made.
* <p>
* As soon as a successful injection has been registered,
* {@link #eventCatchScriptInjected} is set so no unnecessary further
* injection is made.
*/
private void injectEventCatchScript() {
if (this.eventCatchScriptInjected) {
return;
}
File events = BrowserUtils.getFile(Browser.class, "events.js");
try {
Browser.this.runImmediately(events);
} catch (Exception e) {
LOGGER.error("Could not inject events catch script in "
+ Browser.this.getClass().getSimpleName(), e);
}
File dnd = BrowserUtils.getFile(Browser.class, "dnd.js");
File dndCss = BrowserUtils.getFile(Browser.class, "dnd.css");
try {
Browser.this.runImmediately(dnd);
Browser.this.injectCssFile(new URI("file://" + dndCss));
} catch (Exception e) {
LOGGER.error("Could not inject drop catch script in "
+ Browser.this.getClass().getSimpleName(), e);
}
Browser.this.eventCatchScriptInjected = true;
}
/**
* This method waits for the {@link Browser} to complete loading.
* <p>
* It has been observed that the
* {@link ProgressListener#completed(ProgressEvent)} fires to early. This
* method uses JavaScript to reliably detect the completed state.
*
* @param pageLoadCheckExpression
*/
private void waitAndComplete(String pageLoadCheckExpression) {
if (Browser.this.browser == null || Browser.this.browser.isDisposed()) {
return;
}
if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.LOADING) {
if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.CANCELLED) {
LOGGER.error("State Error: "
+ Browser.this.browserScriptRunner.getBrowserStatus());
}
return;
}
String completedCallbackFunctionName = BrowserUtils
.createRandomFunctionName();
String completedCheckScript = "(function() { "
+ "function test() { if(document.readyState == 'complete'"
+ (pageLoadCheckExpression != null ? " && ("
+ pageLoadCheckExpression + ")" : "") + ") { "
+ completedCallbackFunctionName
+ "(); } else { window.setTimeout(test, 50); } } "
+ "test(); })()";
final AtomicReference<BrowserFunction> completedCallback = new AtomicReference<BrowserFunction>();
completedCallback.set(new BrowserFunction(this.browser,
completedCallbackFunctionName) {
@Override
public Object function(Object[] arguments) {
Browser.this.complete();
completedCallback.get().dispose();
return null;
}
});
try {
this.runImmediately(completedCheckScript, IConverter.CONVERTER_VOID);
} catch (Exception e) {
LOGGER.error(
"An error occurred while checking the page load state", e);
synchronized (Browser.this.monitor) {
Browser.this.monitor.notifyAll();
}
}
}
/**
* This method is called by {@link #waitAndComplete(String)} and post
* processes the loaded page.
* <ol>
* <li>calls {@link #beforeCompletion(String)}</li>
* <li>injects necessary scripts</li>
* <li>runs the scheduled user scripts</li>
* </ol>
*/
private void complete() {
final String uri = Browser.this.browser.getUrl();
if (this.initWithSystemBackgroundColor) {
this.setBackground(SWTUtils.getEffectiveBackground(Browser.this));
}
if (this.textSelectionsDisabled) {
try {
this.injectCssImmediately("* { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }");
} catch (Exception e) {
LOGGER.error(e);
}
}
final Future<Void> finished = Browser.this.beforeCompletion(uri);
ExecUtils.nonUISyncExec(Browser.class, "Progress Check for " + uri,
new Runnable() {
@Override
public void run() {
try {
if (finished != null) {
finished.get();
}
} catch (Exception e) {
LOGGER.error(e);
}
Browser.this.injectEventCatchScript();
ExecUtils.asyncExec(new Runnable() {
@Override
public void run() {
if (!Browser.this.browser.isDisposed()) {
Browser.this.browser.setVisible(true);
}
}
});
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() != BrowserStatus.CANCELLED) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.LOADED);
}
Browser.this.monitor.notifyAll();
}
}
});
}
@Override
public Future<Boolean> open(final String uri, final Integer timeout,
final String pageLoadCheckExpression) {
if (this.browser.isDisposed()) {
throw new SWTException(SWT.ERROR_WIDGET_DISPOSED);
}
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.LOADING);
this.browser.addProgressListener(new ProgressAdapter() {
@Override
public void completed(ProgressEvent event) {
Browser.this.waitAndComplete(pageLoadCheckExpression);
}
});
return ExecUtils.nonUIAsyncExec(Browser.class, "Opening " + uri,
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// stops waiting after timeout
Future<Void> timeoutMonitor = null;
if (timeout != null && timeout > 0) {
timeoutMonitor = ExecUtils.nonUIAsyncExec(
Browser.class,
"Timeout Watcher for " + uri,
new Runnable() {
@Override
public void run() {
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() != BrowserStatus.LOADED) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.CANCELLED);
}
Browser.this.monitor
.notifyAll();
}
}
}, timeout);
} else {
LOGGER.warn("timeout must be greater or equal 0. Ignoring timeout.");
}
Browser.this.beforeLoad(uri);
ExecUtils.syncExec(new Runnable() {
@Override
public void run() {
Browser.this.settingUri = true;
if (!Browser.this.browser.isDisposed()) {
Browser.this.browser.setUrl(uri.toString());
}
Browser.this.settingUri = false;
}
});
Browser.this.afterLoad(uri);
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADING) {
LOGGER.debug("Waiting for "
+ uri
+ " to be loaded (Thread: "
+ Thread.currentThread()
+ "; status: "
+ Browser.this.browserScriptRunner
.getBrowserStatus() + ")");
Browser.this.monitor.wait();
// notified by progresslistener or by timeout
}
if (timeoutMonitor != null) {
timeoutMonitor.cancel(true);
}
switch (Browser.this.browserScriptRunner
.getBrowserStatus()) {
case LOADED:
LOGGER.debug("Successfully loaded " + uri);
break;
case CANCELLED:
if (!Browser.this.browser.isDisposed()) {
LOGGER.warn("Aborted loading " + uri
+ " due to timeout");
}
break;
default:
throw new RuntimeException(
"Implementation error");
}
return Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADED;
}
}
});
}
@Override
public Future<Boolean> open(String address, Integer timeout) {
return this.open(address, timeout, null);
}
@Override
public Future<Boolean> open(URI uri, Integer timeout) {
return this.open(uri.toString(), timeout, null);
}
@Override
public Future<Boolean> open(URI uri, Integer timeout,
String pageLoadCheckExpression) {
return this.open(uri.toString(), timeout, pageLoadCheckExpression);
}
@Override
public Future<Boolean> openBlank() {
try {
File empty = File.createTempFile("blank", ".html");
FileUtils.writeStringToFile(empty,
"<html><head></head><body></body></html>", "UTF-8");
return this.open(new URI("file://" + empty.getAbsolutePath()),
60000);
} catch (Exception e) {
return new CompletedFuture<Boolean>(false, e);
}
}
@Override
public void setAllowLocationChange(boolean allow) {
this.allowLocationChange = allow;
}
@Override
public void beforeLoad(String uri) {
}
@Override
public void afterLoad(String uri) {
}
@Override
public Future<Void> beforeCompletion(String uri) {
return null;
}
@Override
public void addListener(int eventType, Listener listener) {
// TODO evtl. erst ausführen, wenn alles wirklich geladen wurde, um
// evtl. falsche Mauskoordinaten zu verhindern und so ein Fehlverhalten
// im InformationControl vorzeugen
if (EventDelegator.mustDelegate(eventType, this)) {
this.browser.addListener(eventType, listener);
} else {
super.addListener(eventType, listener);
}
}
/**
* Deactivate browser's native context/popup menu. Doing so allows the
* definition of menus in an inheriting composite via setMenu.
*/
public void deactivateNativeMenu() {
this.browser.addListener(SWT.MenuDetect, new Listener() {
@Override
public void handleEvent(Event event) {
event.doit = false;
}
});
}
public void deactivateTextSelections() {
this.textSelectionsDisabled = true;
}
@Override
public org.eclipse.swt.browser.Browser getBrowser() {
return this.browser;
}
public boolean isLoadingCompleted() {
return this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADED;
}
private final Object monitor = new Object();
@Override
public Future<Boolean> inject(URI script) {
return this.browserScriptRunner.inject(script);
}
@Override
public Future<Boolean> run(final File script) {
return this.browserScriptRunner.run(script);
}
@Override
public Future<Boolean> run(final URI script) {
return this.browserScriptRunner.run(script);
}
@Override
public Future<Object> run(final String script) {
return this.browserScriptRunner.run(script);
}
@Override
public <DEST> Future<DEST> run(final String script,
final IConverter<Object, DEST> converter) {
return this.browserScriptRunner.run(script, converter);
}
@Override
public <DEST> DEST runImmediately(String script,
IConverter<Object, DEST> converter) throws Exception {
return this.browserScriptRunner.runImmediately(script, converter);
}
@Override
public void runImmediately(File script) throws Exception {
this.browserScriptRunner.runImmediately(script);
}
@Override
public void scriptAboutToBeSentToBrowser(String script) {
return;
}
@Override
public void scriptReturnValueReceived(Object returnValue) {
return;
}
private static String createJsFileInjectionScript(File file) {
return "var script=document.createElement(\"script\"); script.type=\"text/javascript\"; script.src=\""
+ "file://"
+ file
+ "\"; document.getElementsByTagName(\"head\")[0].appendChild(script);";
}
@Override
public Future<Void> injectJsFile(File file) {
return this.run(createJsFileInjectionScript(file),
IConverter.CONVERTER_VOID);
}
@Override
public void injectJsFileImmediately(File file) throws Exception {
this.runImmediately(createJsFileInjectionScript(file),
IConverter.CONVERTER_VOID);
}
private static String createCssFileInjectionScript(URI uri) {
return "if(document.createStyleSheet){document.createStyleSheet(\""
+ uri.toString()
+ "\")}else{ var link=document.createElement(\"link\"); link.rel=\"stylesheet\"; link.type=\"text/css\"; link.href=\""
+ uri.toString()
+ "\"; document.getElementsByTagName(\"head\")[0].appendChild(link); }";
}
@Override
public Future<Void> injectCssFile(URI uri) {
return this.run(createCssFileInjectionScript(uri),
IConverter.CONVERTER_VOID);
}
public void injectCssFileImmediately(URI uri) throws Exception {
this.runImmediately(createCssFileInjectionScript(uri),
IConverter.CONVERTER_VOID);
}
private static String createCssInjectionScript(String css) {
return "(function(){var style=document.createElement(\"style\");style.appendChild(document.createTextNode(\""
+ css
+ "\"));(document.getElementsByTagName(\"head\")[0]||document.documentElement).appendChild(style)})()";
}
@Override
public Future<Void> injectCss(String css) {
return this.run(createCssInjectionScript(css),
IConverter.CONVERTER_VOID);
}
@Override
public void injectCssImmediately(String css) throws Exception {
this.runImmediately(createCssInjectionScript(css),
IConverter.CONVERTER_VOID);
}
@Override
public void addAnkerListener(IAnkerListener ankerListener) {
this.ankerListeners.add(ankerListener);
}
@Override
public void removeAnkerListener(IAnkerListener ankerListener) {
this.ankerListeners.remove(ankerListener);
}
@Override
public void addMouseListener(IMouseListener mouseListener) {
this.mouseListeners.add(mouseListener);
}
@Override
public void removeMouseListener(IMouseListener mouseListener) {
this.mouseListeners.remove(mouseListener);
}
/**
*
* @param string
* @param mouseEnter
* true if mouseenter; false otherwise
*/
protected void fireAnkerHover(String html, boolean mouseEnter) {
IElement element = BrowserUtils.extractElement(html);
IAnker anker = new Anker(element.getAttributes(), element.getContent());
for (IAnkerListener ankerListener : Browser.this.ankerListeners) {
ankerListener.ankerHovered(anker, mouseEnter);
}
}
/**
*
* @param x
* @param y
*/
protected void fireMouseMove(double x, double y) {
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseMove(x, y);
}
}
/**
*
* @param x
* @param y
* @param element
* on which the mouse went down
*/
protected void fireMouseDown(double x, double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseDown(x, y, element);
}
}
/**
*
* @param x
* @param y
* @param arguments
* on which the mouse went up
*/
protected void fireMouseUp(double x, double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseUp(x, y, element);
}
}
/**
*
* @param y
* @param x
* @param string
*/
protected void fireClicked(Double x, Double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.clicked(x, y, element);
}
if (element.getName().equals("a")) {
IAnker anker = new Anker(element.getAttributes(),
element.getContent());
for (IAnkerListener ankerListener : Browser.this.ankerListeners) {
ankerListener.ankerClicked(anker);
}
}
}
@Override
public void addFocusListener(IFocusListener focusListener) {
this.focusListeners.add(focusListener);
}
@Override
public void removeFocusListener(IFocusListener focusListener) {
this.focusListeners.remove(focusListener);
}
protected void fireFocusGained(IElement element) {
for (IFocusListener focusListener : this.focusListeners) {
focusListener.focusGained(element);
}
}
protected void fireFocusLost(IElement element) {
for (IFocusListener focusListener : this.focusListeners) {
focusListener.focusLost(element);
}
}
@Override
public void addDNDListener(IDNDListener dndListener) {
this.dndListeners.add(dndListener);
}
@Override
public void removeDNDListener(IDNDListener dndListener) {
this.dndListeners.remove(dndListener);
}
synchronized protected void fireDragStart(long offsetX, long offsetY,
String mimeType, String data) {
for (IDNDListener dndListener : this.dndListeners) {
dndListener.dragStart(offsetX, offsetY, mimeType, data);
}
}
synchronized protected void fireDrop(long offsetX, long offsetY,
String mimeType, String data) {
for (IDNDListener dndListener : this.dndListeners) {
dndListener.drop(offsetX, offsetY, mimeType, data);
}
}
@Override
public Future<Boolean> containsElementWithID(String id) {
return this.run("return document.getElementById('" + id + "') != null",
IConverter.CONVERTER_BOOLEAN);
}
@Override
public Future<Boolean> containsElementsWithName(String name) {
return this.run("return document.getElementsByName('" + name
+ "').length > 0", IConverter.CONVERTER_BOOLEAN);
}
private String escape(String html) {
return html.replace("\n", "<br>").replace("
", "")
.replace("\r", "").replace("\"", "\\\"").replace("'", "\\'");
}
@Override
public Future<Void> setBodyHtml(String html) {
return this.run("document.body.innerHTML = ('" + this.escape(html)
+ "');", IConverter.CONVERTER_VOID);
}
@Override
public Future<String> getBodyHtml() {
return this.run("return document.body.innerHTML",
IConverter.CONVERTER_STRING);
}
@Override
public Future<String> getHtml() {
return this.run("return document.documentElement.outerHTML",
IConverter.CONVERTER_STRING);
}
@Override
public void setBackground(Color color) {
super.setBackground(color);
String hex = color != null ? new RGB(color.getRGB()).toHexString()
: "transparent";
try {
this.injectCssImmediately("html, body { background-color: " + hex
+ "; }");
} catch (Exception e) {
LOGGER.error("Error setting background color to " + color, e);
}
}
@Override
public Future<Void> pasteHtmlAtCaret(String html) {
String escapedHtml = this.escape(html);
try {
File js = File.createTempFile("paste", ".js");
FileUtils
.write(js,
"if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '");
FileOutputStream outStream = new FileOutputStream(js, true);
IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
IOUtils.copy(
IOUtils.toInputStream("';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"),
outStream);
IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
IOUtils.copy(
IOUtils.toInputStream("';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"),
outStream);
IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream);
return this.injectJsFile(js);
} catch (Exception e) {
return new CompletedFuture<Void>(null, e);
}
}
@Override
public Point computeSize(int wHint, int hHint, boolean changed) {
try {
this.browser
.execute("if (window[\"__notifySize\"] && typeof window[\"__notifySize\"]) window[\"__notifySize\"]();");
} catch (Exception e) {
LOGGER.error("Error computing size for "
+ Browser.class.getSimpleName());
}
Rectangle bounds = this.cachedContentBounds;
if (bounds == null) {
return super.computeSize(wHint, hHint, changed);
}
return new Point(bounds.x + bounds.width, bounds.y + bounds.height);
}
}
|
src/com/bkahlert/nebula/widgets/browser/Browser.java
|
package com.bkahlert.nebula.widgets.browser;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.browser.LocationAdapter;
import org.eclipse.swt.browser.LocationEvent;
import org.eclipse.swt.browser.ProgressAdapter;
import org.eclipse.swt.browser.ProgressEvent;
import org.eclipse.swt.browser.ProgressListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import com.bkahlert.nebula.utils.CompletedFuture;
import com.bkahlert.nebula.utils.EventDelegator;
import com.bkahlert.nebula.utils.ExecUtils;
import com.bkahlert.nebula.utils.HandlerUtils;
import com.bkahlert.nebula.utils.IConverter;
import com.bkahlert.nebula.utils.SWTUtils;
import com.bkahlert.nebula.utils.colors.RGB;
import com.bkahlert.nebula.widgets.browser.extended.html.Anker;
import com.bkahlert.nebula.widgets.browser.extended.html.Element;
import com.bkahlert.nebula.widgets.browser.extended.html.IAnker;
import com.bkahlert.nebula.widgets.browser.extended.html.IElement;
import com.bkahlert.nebula.widgets.browser.listener.IAnkerListener;
import com.bkahlert.nebula.widgets.browser.listener.IDNDListener;
import com.bkahlert.nebula.widgets.browser.listener.IFocusListener;
import com.bkahlert.nebula.widgets.browser.listener.IMouseListener;
import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner;
import com.bkahlert.nebula.widgets.browser.runner.BrowserScriptRunner.BrowserStatus;
public class Browser extends Composite implements IBrowser {
private static Logger LOGGER = Logger.getLogger(Browser.class);
private static final int STYLES = SWT.INHERIT_FORCE;
public static final String FOCUS_CONTROL_ID = "com.bkahlert.nebula.browser";
private org.eclipse.swt.browser.Browser browser;
private BrowserScriptRunner browserScriptRunner;
private boolean initWithSystemBackgroundColor;
private boolean textSelectionsDisabled = false;
private boolean settingUri = false;
private boolean allowLocationChange = false;
private Rectangle cachedContentBounds = null;
private final List<IAnkerListener> ankerListeners = new ArrayList<IAnkerListener>();
private final List<IMouseListener> mouseListeners = new ArrayList<IMouseListener>();
private final List<IFocusListener> focusListeners = new ArrayList<IFocusListener>();
private final List<IDNDListener> dndListeners = new ArrayList<IDNDListener>();
/**
* Constructs a new {@link Browser} with the given styles.
*
* @param parent
* @param style
* if {@link SWT#INHERIT_FORCE}) is set the loaded page's
* background is replaced by the inherited background color
*/
public Browser(Composite parent, int style) {
super(parent, style | SWT.EMBEDDED & ~STYLES);
this.setLayout(new FillLayout());
this.initWithSystemBackgroundColor = (style & SWT.INHERIT_FORCE) != 0;
this.browser = new org.eclipse.swt.browser.Browser(this, SWT.NONE);
this.browser.setVisible(false);
this.browserScriptRunner = new BrowserScriptRunner(this.browser) {
@Override
public void scriptAboutToBeSentToBrowser(String script) {
Browser.this.scriptAboutToBeSentToBrowser(script);
}
@Override
public void scriptReturnValueReceived(Object returnValue) {
Browser.this.scriptReturnValueReceived(returnValue);
}
};
new BrowserFunction(this.browser, "__mouseenter") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
Browser.this.fireAnkerHover((String) arguments[0], true);
}
return null;
}
};
new BrowserFunction(this.browser, "__mouseleave") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
Browser.this.fireAnkerHover((String) arguments[0], false);
}
return null;
}
};
new BrowserFunction(this.browser, "__mousemove") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 2
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)) {
Browser.this.fireMouseMove((Double) arguments[0],
(Double) arguments[1]);
}
return null;
}
};
new BrowserFunction(this.browser, "__mousedown") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireMouseDown((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__mouseup") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireMouseUp((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__click") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 3
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof String)) {
Browser.this.fireClicked((Double) arguments[0],
(Double) arguments[1], (String) arguments[2]);
}
return null;
}
};
new BrowserFunction(this.browser, "__focusgained") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
final IElement element = new Element((String) arguments[0]);
Browser.this.fireFocusGained(element);
}
return null;
}
};
new BrowserFunction(this.browser, "__focuslost") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 1 && arguments[0] instanceof String) {
final IElement element = new Element((String) arguments[0]);
Browser.this.fireFocusLost(element);
}
return null;
}
};
new BrowserFunction(this.browser, "__resize") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4
&& (arguments[0] == null || arguments[0] instanceof Double)
&& (arguments[1] == null || arguments[1] instanceof Double)
&& (arguments[2] == null || arguments[2] instanceof Double)
&& (arguments[3] == null || arguments[3] instanceof Double)) {
Browser.this.cachedContentBounds = new Rectangle(
arguments[0] != null ? (int) Math.round((Double) arguments[0])
: 0,
arguments[1] != null ? (int) Math
.round((Double) arguments[1]) : 0,
arguments[2] != null ? (int) Math
.round((Double) arguments[2])
: Integer.MAX_VALUE,
arguments[3] != null ? (int) Math
.round((Double) arguments[3])
: Integer.MAX_VALUE);
}
return null;
}
};
new BrowserFunction(this.browser, "__dragStart") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4 && arguments[0] instanceof Double
&& arguments[1] instanceof Double
&& arguments[2] instanceof String
&& arguments[3] instanceof String) {
long offsetX = Math.round((Double) arguments[0]);
long offsetY = Math.round((Double) arguments[1]);
String mimeType = (String) arguments[2];
String data = (String) arguments[3];
Browser.this
.fireDragStart(offsetX, offsetY, mimeType, data);
}
return null;
}
};
new BrowserFunction(this.browser, "__drop") {
@Override
public Object function(Object[] arguments) {
if (arguments.length == 4 && arguments[0] instanceof Double
&& arguments[1] instanceof Double
&& arguments[2] instanceof String
&& arguments[3] instanceof String) {
long offsetX = Math.round((Double) arguments[0]);
long offsetY = Math.round((Double) arguments[1]);
String mimeType = (String) arguments[2];
String data = (String) arguments[3];
Browser.this.fireDrop(offsetX, offsetY, mimeType, data);
}
return null;
}
};
this.browser.addLocationListener(new LocationAdapter() {
@Override
public void changing(LocationEvent event) {
if (!Browser.this.settingUri) {
event.doit = Browser.this.allowLocationChange
|| Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADING;
}
}
});
HandlerUtils.activateCustomPasteHandlerConsideration(this.browser,
FOCUS_CONTROL_ID, "application/x-java-file-list", "image");
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
HandlerUtils
.deactivateCustomPasteHandlerConsideration(Browser.this.browser);
}
});
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADING) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.CANCELLED);
}
Browser.this.browserScriptRunner.dispose();
Browser.this.monitor.notifyAll();
}
}
});
}
private boolean eventCatchScriptInjected = false;
/**
* Injects the code needed for {@link #addAnkerListener(IAnkerListener)},
* {@link #addFokusListener(IFocusListener)} and
* {@link #addDNDListener(IFocusListener)} to work.
* <p>
* The JavaScript remembers a successful injection in case to consecutive
* calls are made.
* <p>
* As soon as a successful injection has been registered,
* {@link #eventCatchScriptInjected} is set so no unnecessary further
* injection is made.
*/
private void injectEventCatchScript() {
if (this.eventCatchScriptInjected) {
return;
}
File events = BrowserUtils.getFile(Browser.class, "events.js");
try {
Browser.this.runImmediately(events);
} catch (Exception e) {
LOGGER.error("Could not inject events catch script in "
+ Browser.this.getClass().getSimpleName(), e);
}
File dnd = BrowserUtils.getFile(Browser.class, "dnd.js");
File dndCss = BrowserUtils.getFile(Browser.class, "dnd.css");
try {
Browser.this.runImmediately(dnd);
Browser.this.injectCssFile(new URI("file://" + dndCss));
} catch (Exception e) {
LOGGER.error("Could not inject drop catch script in "
+ Browser.this.getClass().getSimpleName(), e);
}
Browser.this.eventCatchScriptInjected = true;
}
/**
* This method waits for the {@link Browser} to complete loading.
* <p>
* It has been observed that the
* {@link ProgressListener#completed(ProgressEvent)} fires to early. This
* method uses JavaScript to reliably detect the completed state.
*
* @param pageLoadCheckExpression
*/
private void waitAndComplete(String pageLoadCheckExpression) {
if (Browser.this.browser == null || Browser.this.browser.isDisposed()) {
return;
}
if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.LOADING) {
if (Browser.this.browserScriptRunner.getBrowserStatus() != BrowserStatus.CANCELLED) {
LOGGER.error("State Error: "
+ Browser.this.browserScriptRunner.getBrowserStatus());
}
return;
}
String completedCallbackFunctionName = BrowserUtils
.createRandomFunctionName();
String completedCheckScript = "(function() { "
+ "function test() { if(document.readyState == 'complete'"
+ (pageLoadCheckExpression != null ? " && ("
+ pageLoadCheckExpression + ")" : "") + ") { "
+ completedCallbackFunctionName
+ "(); } else { window.setTimeout(test, 50); } } "
+ "test(); })()";
final AtomicReference<BrowserFunction> completedCallback = new AtomicReference<BrowserFunction>();
completedCallback.set(new BrowserFunction(this.browser,
completedCallbackFunctionName) {
@Override
public Object function(Object[] arguments) {
Browser.this.complete();
completedCallback.get().dispose();
return null;
}
});
try {
this.runImmediately(completedCheckScript, IConverter.CONVERTER_VOID);
} catch (Exception e) {
LOGGER.error(
"An error occurred while checking the page load state", e);
synchronized (Browser.this.monitor) {
Browser.this.monitor.notifyAll();
}
}
}
/**
* This method is called by {@link #waitAndComplete(String)} and post
* processes the loaded page.
* <ol>
* <li>calls {@link #beforeCompletion(String)}</li>
* <li>injects necessary scripts</li>
* <li>runs the scheduled user scripts</li>
* </ol>
*/
private void complete() {
final String uri = Browser.this.browser.getUrl();
if (this.initWithSystemBackgroundColor) {
this.setBackground(SWTUtils.getEffectiveBackground(Browser.this));
}
if (this.textSelectionsDisabled) {
try {
this.injectCssImmediately("* { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }");
} catch (Exception e) {
LOGGER.error(e);
}
}
final Future<Void> finished = Browser.this.beforeCompletion(uri);
ExecUtils.nonUISyncExec(Browser.class, "Progress Check for " + uri,
new Runnable() {
@Override
public void run() {
try {
if (finished != null) {
finished.get();
}
} catch (Exception e) {
LOGGER.error(e);
}
Browser.this.injectEventCatchScript();
ExecUtils.asyncExec(new Runnable() {
@Override
public void run() {
if (!Browser.this.browser.isDisposed()) {
Browser.this.browser.setVisible(true);
}
}
});
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() != BrowserStatus.CANCELLED) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.LOADED);
}
Browser.this.monitor.notifyAll();
}
}
});
}
@Override
public Future<Boolean> open(final String uri, final Integer timeout,
final String pageLoadCheckExpression) {
if (this.browser.isDisposed()) {
throw new SWTException(SWT.ERROR_WIDGET_DISPOSED);
}
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.LOADING);
this.browser.addProgressListener(new ProgressAdapter() {
@Override
public void completed(ProgressEvent event) {
Browser.this.waitAndComplete(pageLoadCheckExpression);
}
});
return ExecUtils.nonUIAsyncExec(Browser.class, "Opening " + uri,
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// stops waiting after timeout
Future<Void> timeoutMonitor = null;
if (timeout != null && timeout > 0) {
timeoutMonitor = ExecUtils.nonUIAsyncExec(
Browser.class,
"Timeout Watcher for " + uri,
new Runnable() {
@Override
public void run() {
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() != BrowserStatus.LOADED) {
Browser.this.browserScriptRunner
.setBrowserStatus(BrowserStatus.CANCELLED);
}
Browser.this.monitor
.notifyAll();
}
}
}, timeout);
} else {
LOGGER.warn("timeout must be greater or equal 0. Ignoring timeout.");
}
Browser.this.beforeLoad(uri);
ExecUtils.syncExec(new Runnable() {
@Override
public void run() {
Browser.this.settingUri = true;
if (!Browser.this.browser.isDisposed()) {
Browser.this.browser.setUrl(uri.toString());
}
Browser.this.settingUri = false;
}
});
Browser.this.afterLoad(uri);
synchronized (Browser.this.monitor) {
if (Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADING) {
LOGGER.debug("Waiting for "
+ uri
+ " to be loaded (Thread: "
+ Thread.currentThread()
+ "; status: "
+ Browser.this.browserScriptRunner
.getBrowserStatus() + ")");
Browser.this.monitor.wait();
// notified by progresslistener or by timeout
}
if (timeoutMonitor != null) {
timeoutMonitor.cancel(true);
}
switch (Browser.this.browserScriptRunner
.getBrowserStatus()) {
case LOADED:
LOGGER.debug("Successfully loaded " + uri);
break;
case CANCELLED:
if (!Browser.this.browser.isDisposed()) {
LOGGER.warn("Aborted loading " + uri
+ " due to timeout");
}
break;
default:
throw new RuntimeException(
"Implementation error");
}
return Browser.this.browserScriptRunner
.getBrowserStatus() == BrowserStatus.LOADED;
}
}
});
}
@Override
public Future<Boolean> open(String address, Integer timeout) {
return this.open(address, timeout, null);
}
@Override
public Future<Boolean> open(URI uri, Integer timeout) {
return this.open(uri.toString(), timeout, null);
}
@Override
public Future<Boolean> open(URI uri, Integer timeout,
String pageLoadCheckExpression) {
return this.open(uri.toString(), timeout, pageLoadCheckExpression);
}
@Override
public Future<Boolean> openBlank() {
try {
File empty = File.createTempFile("blank", ".html");
FileUtils.writeStringToFile(empty,
"<html><head></head><body></body></html>", "UTF-8");
return this.open(new URI("file://" + empty.getAbsolutePath()),
60000);
} catch (Exception e) {
return new CompletedFuture<Boolean>(false, e);
}
}
@Override
public void setAllowLocationChange(boolean allow) {
this.allowLocationChange = allow;
}
@Override
public void beforeLoad(String uri) {
}
@Override
public void afterLoad(String uri) {
}
@Override
public Future<Void> beforeCompletion(String uri) {
return null;
}
@Override
public void addListener(int eventType, Listener listener) {
// TODO evtl. erst ausführen, wenn alles wirklich geladen wurde, um
// evtl. falsche Mauskoordinaten zu verhindern und so ein Fehlverhalten
// im InformationControl vorzeugen
if (EventDelegator.mustDelegate(eventType, this)) {
this.browser.addListener(eventType, listener);
} else {
super.addListener(eventType, listener);
}
}
/**
* Deactivate browser's native context/popup menu. Doing so allows the
* definition of menus in an inheriting composite via setMenu.
*/
public void deactivateNativeMenu() {
this.browser.addListener(SWT.MenuDetect, new Listener() {
@Override
public void handleEvent(Event event) {
event.doit = false;
}
});
}
public void deactivateTextSelections() {
this.textSelectionsDisabled = true;
}
@Override
public org.eclipse.swt.browser.Browser getBrowser() {
return this.browser;
}
public boolean isLoadingCompleted() {
return this.browserScriptRunner.getBrowserStatus() == BrowserStatus.LOADED;
}
private final Object monitor = new Object();
@Override
public Future<Boolean> inject(URI script) {
return this.browserScriptRunner.inject(script);
}
@Override
public Future<Boolean> run(final File script) {
return this.browserScriptRunner.run(script);
}
@Override
public Future<Boolean> run(final URI script) {
return this.browserScriptRunner.run(script);
}
@Override
public Future<Object> run(final String script) {
return this.browserScriptRunner.run(script);
}
@Override
public <DEST> Future<DEST> run(final String script,
final IConverter<Object, DEST> converter) {
return this.browserScriptRunner.run(script, converter);
}
@Override
public <DEST> DEST runImmediately(String script,
IConverter<Object, DEST> converter) throws Exception {
return this.browserScriptRunner.runImmediately(script, converter);
}
@Override
public void runImmediately(File script) throws Exception {
this.browserScriptRunner.runImmediately(script);
}
@Override
public void scriptAboutToBeSentToBrowser(String script) {
return;
}
@Override
public void scriptReturnValueReceived(Object returnValue) {
return;
}
private static String createJsFileInjectionScript(File file) {
return "var script=document.createElement(\"script\"); script.type=\"text/javascript\"; script.src=\""
+ "file://"
+ file
+ "\"; document.getElementsByTagName(\"head\")[0].appendChild(script);";
}
@Override
public Future<Void> injectJsFile(File file) {
return this.run(createJsFileInjectionScript(file),
IConverter.CONVERTER_VOID);
}
@Override
public void injectJsFileImmediately(File file) throws Exception {
this.runImmediately(createJsFileInjectionScript(file),
IConverter.CONVERTER_VOID);
}
private static String createCssFileInjectionScript(URI uri) {
return "if(document.createStyleSheet){document.createStyleSheet(\""
+ uri.toString()
+ "\")}else{ var link=document.createElement(\"link\"); link.rel=\"stylesheet\"; link.type=\"text/css\"; link.href=\""
+ uri.toString()
+ "\"; document.getElementsByTagName(\"head\")[0].appendChild(link); }";
}
@Override
public Future<Void> injectCssFile(URI uri) {
return this.run(createCssFileInjectionScript(uri),
IConverter.CONVERTER_VOID);
}
public void injectCssFileImmediately(URI uri) throws Exception {
this.runImmediately(createCssFileInjectionScript(uri),
IConverter.CONVERTER_VOID);
}
private static String createCssInjectionScript(String css) {
return "(function(){var style=document.createElement(\"style\");style.appendChild(document.createTextNode(\""
+ css
+ "\"));(document.getElementsByTagName(\"head\")[0]||document.documentElement).appendChild(style)})()";
}
@Override
public Future<Void> injectCss(String css) {
return this.run(createCssInjectionScript(css),
IConverter.CONVERTER_VOID);
}
@Override
public void injectCssImmediately(String css) throws Exception {
this.runImmediately(createCssInjectionScript(css),
IConverter.CONVERTER_VOID);
}
@Override
public void addAnkerListener(IAnkerListener ankerListener) {
this.ankerListeners.add(ankerListener);
}
@Override
public void removeAnkerListener(IAnkerListener ankerListener) {
this.ankerListeners.remove(ankerListener);
}
@Override
public void addMouseListener(IMouseListener mouseListener) {
this.mouseListeners.add(mouseListener);
}
@Override
public void removeMouseListener(IMouseListener mouseListener) {
this.mouseListeners.remove(mouseListener);
}
/**
*
* @param string
* @param mouseEnter
* true if mouseenter; false otherwise
*/
protected void fireAnkerHover(String html, boolean mouseEnter) {
IElement element = BrowserUtils.extractElement(html);
IAnker anker = new Anker(element.getAttributes(), element.getContent());
for (IAnkerListener ankerListener : Browser.this.ankerListeners) {
ankerListener.ankerHovered(anker, mouseEnter);
}
}
/**
*
* @param x
* @param y
*/
protected void fireMouseMove(double x, double y) {
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseMove(x, y);
}
}
/**
*
* @param x
* @param y
* @param element
* on which the mouse went down
*/
protected void fireMouseDown(double x, double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseDown(x, y, element);
}
}
/**
*
* @param x
* @param y
* @param arguments
* on which the mouse went up
*/
protected void fireMouseUp(double x, double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.mouseUp(x, y, element);
}
}
/**
*
* @param y
* @param x
* @param string
*/
protected void fireClicked(Double x, Double y, String html) {
IElement element = BrowserUtils.extractElement(html);
for (IMouseListener mouseListener : Browser.this.mouseListeners) {
mouseListener.clicked(x, y, element);
}
if (element.getName().equals("a")) {
IAnker anker = new Anker(element.getAttributes(),
element.getContent());
for (IAnkerListener ankerListener : Browser.this.ankerListeners) {
ankerListener.ankerClicked(anker);
}
}
}
@Override
public void addFocusListener(IFocusListener focusListener) {
this.focusListeners.add(focusListener);
}
@Override
public void removeFocusListener(IFocusListener focusListener) {
this.focusListeners.remove(focusListener);
}
synchronized protected void fireFocusGained(IElement element) {
for (IFocusListener focusListener : this.focusListeners) {
focusListener.focusGained(element);
}
}
synchronized protected void fireFocusLost(IElement element) {
for (IFocusListener focusListener : this.focusListeners) {
focusListener.focusLost(element);
}
}
@Override
public void addDNDListener(IDNDListener dndListener) {
this.dndListeners.add(dndListener);
}
@Override
public void removeDNDListener(IDNDListener dndListener) {
this.dndListeners.remove(dndListener);
}
synchronized protected void fireDragStart(long offsetX, long offsetY,
String mimeType, String data) {
for (IDNDListener dndListener : this.dndListeners) {
dndListener.dragStart(offsetX, offsetY, mimeType, data);
}
}
synchronized protected void fireDrop(long offsetX, long offsetY,
String mimeType, String data) {
for (IDNDListener dndListener : this.dndListeners) {
dndListener.drop(offsetX, offsetY, mimeType, data);
}
}
@Override
public Future<Boolean> containsElementWithID(String id) {
return this.run("return document.getElementById('" + id + "') != null",
IConverter.CONVERTER_BOOLEAN);
}
@Override
public Future<Boolean> containsElementsWithName(String name) {
return this.run("return document.getElementsByName('" + name
+ "').length > 0", IConverter.CONVERTER_BOOLEAN);
}
private String escape(String html) {
return html.replace("\n", "<br>").replace("
", "")
.replace("\r", "").replace("\"", "\\\"").replace("'", "\\'");
}
@Override
public Future<Void> setBodyHtml(String html) {
return this.run("document.body.innerHTML = ('" + this.escape(html)
+ "');", IConverter.CONVERTER_VOID);
}
@Override
public Future<String> getBodyHtml() {
return this.run("return document.body.innerHTML",
IConverter.CONVERTER_STRING);
}
@Override
public Future<String> getHtml() {
return this.run("return document.documentElement.outerHTML",
IConverter.CONVERTER_STRING);
}
@Override
public void setBackground(Color color) {
super.setBackground(color);
String hex = color != null ? new RGB(color.getRGB()).toHexString()
: "transparent";
try {
this.injectCssImmediately("html, body { background-color: " + hex
+ "; }");
} catch (Exception e) {
LOGGER.error("Error setting background color to " + color, e);
}
}
@Override
public Future<Void> pasteHtmlAtCaret(String html) {
String escapedHtml = this.escape(html);
try {
File js = File.createTempFile("paste", ".js");
FileUtils
.write(js,
"if(['input','textarea'].indexOf(document.activeElement.tagName.toLowerCase()) != -1) { document.activeElement.value = '");
FileOutputStream outStream = new FileOutputStream(js, true);
IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
IOUtils.copy(
IOUtils.toInputStream("';} else { var t,n;if(window.getSelection){t=window.getSelection();if(t.getRangeAt&&t.rangeCount){n=t.getRangeAt(0);n.deleteContents();var r=document.createElement(\"div\");r.innerHTML='"),
outStream);
IOUtils.copy(IOUtils.toInputStream(escapedHtml), outStream);
IOUtils.copy(
IOUtils.toInputStream("';var i=document.createDocumentFragment(),s,o;while(s=r.firstChild){o=i.appendChild(s)}n.insertNode(i);if(o){n=n.cloneRange();n.setStartAfter(o);n.collapse(true);t.removeAllRanges();t.addRange(n)}}}else if(document.selection&&document.selection.type!=\"Control\"){document.selection.createRange().pasteHTML('"),
outStream);
IOUtils.copy(IOUtils.toInputStream(escapedHtml + "')}}"), outStream);
return this.injectJsFile(js);
} catch (Exception e) {
return new CompletedFuture<Void>(null, e);
}
}
@Override
public Point computeSize(int wHint, int hHint, boolean changed) {
try {
this.browser
.execute("if (window[\"__notifySize\"] && typeof window[\"__notifySize\"]) window[\"__notifySize\"]();");
} catch (Exception e) {
LOGGER.error("Error computing size for "
+ Browser.class.getSimpleName());
}
Rectangle bounds = this.cachedContentBounds;
if (bounds == null) {
return super.computeSize(wHint, hHint, changed);
}
return new Point(bounds.x + bounds.width, bounds.y + bounds.height);
}
}
|
[FIX] Removed problem that could result in a deadlock of the composer
|
src/com/bkahlert/nebula/widgets/browser/Browser.java
|
[FIX] Removed problem that could result in a deadlock of the composer
|
|
Java
|
mit
|
16da81c6b4f2042c5e97de7a0b958a654ccfd146
| 0
|
j6k1/FunctionalMatcher
|
package FunctionalMatcher;
import java.util.ArrayList;
import java.util.Optional;
public class MatcherExecutor {
public static <T> Optional<MatchResult<T>> exec(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
return matcher.match(str, 0, false);
}
public static <T> Optional<MatchResult<T>> find(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
Optional<MatchResult<T>> result = Optional.empty();
for(int i=0, l=str.length(); i <= l && !(result = matcher.match(str, i, false)).isPresent(); i++);
return result;
}
public static <T> Optional<ArrayList<MatchResult<T>>> findAll(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
ArrayList<MatchResult<T>> results = new ArrayList<>();
for(int i=0, l=str.length(); i <= l; i++)
{
Optional<MatchResult<T>> result = Optional.empty();
while(i <= l && !(result = matcher.match(str, i, false)).isPresent())
{
i++;
}
result.ifPresent(r -> results.add(r));
}
return results.size() > 0 ? Optional.of(results) : Optional.empty();
}
}
|
src/main/java/FunctionalMatcher/MatcherExecutor.java
|
package FunctionalMatcher;
import java.util.ArrayList;
import java.util.Optional;
public class MatcherExecutor {
public static <T> Optional<MatchResult<T>> exec(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
return matcher.match(str, 0, false);
}
public static <T> Optional<MatchResult<T>> find(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
Optional<MatchResult<T>> result = Optional.empty();
for(int i=0, l=str.length(); i <= l && !(result = matcher.match(str, i, false)).isPresent(); i++);
return result;
}
public static <T> Optional<ArrayList<MatchResult<T>>> findAll(String str, IMatcher<T> matcher)
{
if(str == null)
{
throw new NullReferenceNotAllowedException("A null value was passed as a reference to the content string.");
}
else if(matcher == null)
{
throw new NullReferenceNotAllowedException("The reference to the argument matcher is null.");
}
ArrayList<MatchResult<T>> results = new ArrayList<>();
for(int i=0, l=str.length(); i <= l; i++);
{
Optional<MatchResult<T>> result = Optional.empty();
for(int i=0, l=str.length(); i <= l && !(result = matcher.match(str, i, false)).isPresent(); i++);
result.ifPresent(r -> results.add(r));
}
return results.size() > 0 ? Optional.of(results) : Optional.empty();
}
}
|
MatcherExecutor.findAllのループ処理の記述がおかしかったので修正。
|
src/main/java/FunctionalMatcher/MatcherExecutor.java
|
MatcherExecutor.findAllのループ処理の記述がおかしかったので修正。
|
|
Java
|
mit
|
01080bd59eb52071055233aeb8ee5afef2df29c0
| 0
|
maslowis/crmka
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ivan Maslov
*
* 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 ru.itpgrad.crmka.model.dao.imp;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.itpgrad.crmka.model.dao.Dao;
import ru.itpgrad.crmka.model.entity.Entity;
import java.io.Serializable;
import java.util.List;
/**
* Parent for all DAO implementations
*
* @author Ivan Maslov
*/
class AbstractHibernateDao<E extends Entity, ID extends Serializable> implements Dao<E, ID> {
protected final Logger logger;
private final SessionFactory sessionFactory;
private final Class<E> targetClass;
protected AbstractHibernateDao(SessionFactory sessionFactory, Class<E> targetClass) {
logger = Logger.getLogger(getClass());
this.sessionFactory = sessionFactory;
this.targetClass = targetClass;
}
protected final Session getSession() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
@Override
public ID create(E newInstance) {
return (ID) getSession().save(newInstance);
}
@SuppressWarnings("unchecked")
@Override
public E read(ID id) {
return (E) getSession().get(targetClass, id);
}
@SuppressWarnings("unchecked")
@Override
public List<E> readAll() {
return (List<E>) getSession().createCriteria(targetClass).list();
}
@Override
public void update(E transientObject) {
getSession().update(transientObject);
}
@Override
public void delete(E persistentObject) {
getSession().delete(persistentObject);
}
}
|
model/src/main/java/ru/itpgrad/crmka/model/dao/imp/AbstractHibernateDao.java
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ivan Maslov
*
* 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 ru.itpgrad.crmka.model.dao.imp;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import ru.itpgrad.crmka.model.dao.Dao;
import ru.itpgrad.crmka.model.entity.Entity;
import java.io.Serializable;
import java.util.List;
/**
* Parent for all DAO implementations
*
* @author Ivan Maslov
*/
class AbstractHibernateDao<E extends Entity, ID extends Serializable> implements Dao<E, ID> {
protected final Logger logger;
private final SessionFactory sessionFactory;
private final Class<E> targetClass;
protected AbstractHibernateDao(SessionFactory sessionFactory, Class<E> targetClass) {
logger = Logger.getLogger(targetClass);
this.sessionFactory = sessionFactory;
this.targetClass = targetClass;
}
protected final Session getSession() {
return sessionFactory.getCurrentSession();
}
@SuppressWarnings("unchecked")
@Override
public ID create(E newInstance) {
return (ID) getSession().save(newInstance);
}
@SuppressWarnings("unchecked")
@Override
public E read(ID id) {
return (E) getSession().get(targetClass, id);
}
@SuppressWarnings("unchecked")
@Override
public List<E> readAll() {
return (List<E>) getSession().createCriteria(targetClass).list();
}
@Override
public void update(E transientObject) {
getSession().update(transientObject);
}
@Override
public void delete(E persistentObject) {
getSession().delete(persistentObject);
}
}
|
Fix mistake of logger
|
model/src/main/java/ru/itpgrad/crmka/model/dao/imp/AbstractHibernateDao.java
|
Fix mistake of logger
|
|
Java
|
mit
|
6d4de80c78c5fc0257f09870b7bb9a780d901387
| 0
|
npomfret/XChange,TSavo/XChange,Panchen/XChange,douggie/XChange,stachon/XChange,nopy/XChange,evdubs/XChange,andre77/XChange,timmolter/XChange,LeonidShamis/XChange,chrisrico/XChange,ww3456/XChange
|
package org.knowm.xchange.dsx.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dsx.DSXAdapters;
import org.knowm.xchange.dsx.DSXAuthenticatedV2;
import org.knowm.xchange.dsx.DSXExchange;
import org.knowm.xchange.dsx.dto.marketdata.DSXExchangeInfo;
import org.knowm.xchange.dsx.dto.trade.DSXCancelAllOrdersResult;
import org.knowm.xchange.dsx.dto.trade.DSXOrder;
import org.knowm.xchange.dsx.dto.trade.DSXTradeHistoryResult;
import org.knowm.xchange.dsx.dto.trade.DSXTradeResult;
import org.knowm.xchange.dsx.dto.trade.DSXTransHistoryResult;
import org.knowm.xchange.dsx.service.trade.params.DSXTradeHistoryParams;
import org.knowm.xchange.dsx.service.trade.params.DSXTransHistoryParams;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.*;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.CancelOrderByIdParams;
import org.knowm.xchange.service.trade.params.CancelOrderParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsIdSpan;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsSorted;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
import org.knowm.xchange.utils.DateUtils;
/**
* @author Mikhail Wall
*/
public class DSXTradeService extends DSXTradeServiceRaw implements TradeService {
/**
* Constructor
*
* @param exchange
*/
public DSXTradeService(Exchange exchange) {
super(exchange);
}
@Override
public OpenOrders getOpenOrders() throws IOException {
return getOpenOrders(createOpenOrdersParams());
}
@Override
public OpenOrders getOpenOrders(OpenOrdersParams params)
throws IOException {
Map<Long, DSXOrder> orders = getDSXActiveOrders(null);
return DSXAdapters.adaptOrders(orders);
}
@Override
public String placeMarketOrder(MarketOrder marketOrder) throws IOException {
DSXExchangeInfo dsxExchangeInfo = ((DSXExchange) exchange).getDsxExchangeInfo();
LimitOrder order = DSXAdapters.createLimitOrder(marketOrder, dsxExchangeInfo);
return placeLimitOrder(order);
}
@Override
public String placeLimitOrder(LimitOrder limitOrder) throws IOException {
DSXOrder.Type type = limitOrder.getType() == Order.OrderType.BID ? DSXOrder.Type.buy : DSXOrder.Type.sell;
String pair = DSXAdapters.getPair(limitOrder.getCurrencyPair());
DSXOrder dsxOrder = new DSXOrder(pair, type, limitOrder.getOriginalAmount(), limitOrder.getOriginalAmount(), limitOrder.getLimitPrice(),
3, DSXOrder.OrderType.limit, null);
DSXTradeResult result = tradeDSX(dsxOrder);
return Long.toString(result.getOrderId());
}
@Override
public String placeStopOrder(StopOrder stopOrder) throws IOException {
throw new NotYetImplementedForExchangeException();
}
@Override
public boolean cancelOrder(String orderId) throws IOException {
return cancelDSXOrder(Long.parseLong(orderId));
}
@Override
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException {
if (orderParams instanceof CancelOrderByIdParams) {
return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId());
} else {
return false;
}
}
public boolean cancelAllOrders() throws IOException {
DSXCancelAllOrdersResult ret = cancelAllDSXOrders();
return (ret != null);
}
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
int count = 1000;//this is the max
Long fromId = null;
Long endId = null;
DSXAuthenticatedV2.SortOrder sort = DSXAuthenticatedV2.SortOrder.DESC;
Long since = null;
Long end = null;
String dsxpair = null;
if (params instanceof TradeHistoryParamLimit) {
TradeHistoryParamLimit pagingParams = (TradeHistoryParamLimit) params;
Integer limit = pagingParams.getLimit();
if (limit != null)
count = limit;
}
if (params instanceof TradeHistoryParamsIdSpan) {
TradeHistoryParamsIdSpan idParams = (TradeHistoryParamsIdSpan) params;
fromId = nullSafeToLong(idParams.getStartId());
endId = nullSafeToLong(idParams.getEndId());
}
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan timeParams = (TradeHistoryParamsTimeSpan) params;
since = DateUtils.toMillisNullSafe(timeParams.getStartTime());
end = DateUtils.toMillisNullSafe(timeParams.getEndTime());
}
if (params instanceof TradeHistoryParamCurrencyPair) {
CurrencyPair pair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair();
if (pair != null) {
dsxpair = DSXAdapters.getPair(pair);
}
}
if (params instanceof TradeHistoryParamsSorted) {
TradeHistoryParamsSorted tradeHistoryParamsSorted = (TradeHistoryParamsSorted) params;
TradeHistoryParamsSorted.Order order = tradeHistoryParamsSorted.getOrder();
if (order != null)
sort = order.equals(TradeHistoryParamsSorted.Order.desc) ? DSXAuthenticatedV2.SortOrder.DESC : DSXAuthenticatedV2.SortOrder.ASC;
}
Map<Long, DSXTradeHistoryResult> resultMap = getDSXTradeHistory(count, fromId, endId, sort, since, end, dsxpair);
return DSXAdapters.adaptTradeHistory(resultMap);
}
private static Long nullSafeToLong(String str) {
try {
return (str == null || str.isEmpty()) ? null : Long.valueOf(str);
} catch (NumberFormatException e) {
return null;
}
}
private static Long nullSafeUnixTime(Date time) {
return time != null ? DateUtils.toUnixTime(time) : null;
}
@Override
public TradeHistoryParams createTradeHistoryParams() {
return new DSXTradeHistoryParams();
}
@Override
public OpenOrdersParams createOpenOrdersParams() {
return new DefaultOpenOrdersParamCurrencyPair();
}
@Override
public Collection<Order> getOrder(String... orderIds) throws IOException {
throw new NotYetImplementedForExchangeException();
}
public Map<Long, DSXTransHistoryResult> getTransHistory(DSXTransHistoryParams params) throws ExchangeException, IOException {
Integer count = params.getLimit();
Long startId = nullSafeToLong(params.getStartId());
Long endId = nullSafeToLong(params.getEndId());
Long startTime = nullSafeUnixTime(params.getStartTime());
Long endTime = nullSafeUnixTime(params.getEndTime());
DSXAuthenticatedV2.SortOrder sort = params.getOrder().equals(TradeHistoryParamsSorted.Order.desc) ? DSXAuthenticatedV2.SortOrder.DESC : DSXAuthenticatedV2.SortOrder.ASC;
DSXTransHistoryResult.Status status = params.getStatus();
DSXTransHistoryResult.Type type = params.getType();
Currency c = params.getCurrency();
String currency = c == null ? null : c.getCurrencyCode();
return getDSXTransHistory(count, startId, endId, sort, startTime, endTime, type, status, currency);
}
}
|
xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/DSXTradeService.java
|
package org.knowm.xchange.dsx.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dsx.DSXAdapters;
import org.knowm.xchange.dsx.DSXAuthenticatedV2;
import org.knowm.xchange.dsx.DSXExchange;
import org.knowm.xchange.dsx.dto.marketdata.DSXExchangeInfo;
import org.knowm.xchange.dsx.dto.trade.DSXCancelAllOrdersResult;
import org.knowm.xchange.dsx.dto.trade.DSXOrder;
import org.knowm.xchange.dsx.dto.trade.DSXTradeHistoryResult;
import org.knowm.xchange.dsx.dto.trade.DSXTradeResult;
import org.knowm.xchange.dsx.dto.trade.DSXTransHistoryResult;
import org.knowm.xchange.dsx.service.trade.params.DSXTradeHistoryParams;
import org.knowm.xchange.dsx.service.trade.params.DSXTransHistoryParams;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotYetImplementedForExchangeException;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.CancelOrderByIdParams;
import org.knowm.xchange.service.trade.params.CancelOrderParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsIdSpan;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsSorted;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;
import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair;
import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams;
import org.knowm.xchange.utils.DateUtils;
/**
* @author Mikhail Wall
*/
public class DSXTradeService extends DSXTradeServiceRaw implements TradeService {
/**
* Constructor
*
* @param exchange
*/
public DSXTradeService(Exchange exchange) {
super(exchange);
}
@Override
public OpenOrders getOpenOrders() throws IOException {
return getOpenOrders(createOpenOrdersParams());
}
@Override
public OpenOrders getOpenOrders(OpenOrdersParams params)
throws IOException {
Map<Long, DSXOrder> orders = getDSXActiveOrders(null);
return DSXAdapters.adaptOrders(orders);
}
@Override
public String placeMarketOrder(MarketOrder marketOrder) throws IOException {
DSXExchangeInfo dsxExchangeInfo = ((DSXExchange) exchange).getDsxExchangeInfo();
LimitOrder order = DSXAdapters.createLimitOrder(marketOrder, dsxExchangeInfo);
return placeLimitOrder(order);
}
@Override
public String placeLimitOrder(LimitOrder limitOrder) throws IOException {
DSXOrder.Type type = limitOrder.getType() == Order.OrderType.BID ? DSXOrder.Type.buy : DSXOrder.Type.sell;
String pair = DSXAdapters.getPair(limitOrder.getCurrencyPair());
DSXOrder dsxOrder = new DSXOrder(pair, type, limitOrder.getOriginalAmount(), limitOrder.getOriginalAmount(), limitOrder.getLimitPrice(),
3, DSXOrder.OrderType.limit, null);
DSXTradeResult result = tradeDSX(dsxOrder);
return Long.toString(result.getOrderId());
}
@Override
public boolean cancelOrder(String orderId) throws IOException {
return cancelDSXOrder(Long.parseLong(orderId));
}
@Override
public boolean cancelOrder(CancelOrderParams orderParams) throws IOException {
if (orderParams instanceof CancelOrderByIdParams) {
return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId());
} else {
return false;
}
}
public boolean cancelAllOrders() throws IOException {
DSXCancelAllOrdersResult ret = cancelAllDSXOrders();
return (ret != null);
}
@Override
public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException {
int count = 1000;//this is the max
Long fromId = null;
Long endId = null;
DSXAuthenticatedV2.SortOrder sort = DSXAuthenticatedV2.SortOrder.DESC;
Long since = null;
Long end = null;
String dsxpair = null;
if (params instanceof TradeHistoryParamLimit) {
TradeHistoryParamLimit pagingParams = (TradeHistoryParamLimit) params;
Integer limit = pagingParams.getLimit();
if (limit != null)
count = limit;
}
if (params instanceof TradeHistoryParamsIdSpan) {
TradeHistoryParamsIdSpan idParams = (TradeHistoryParamsIdSpan) params;
fromId = nullSafeToLong(idParams.getStartId());
endId = nullSafeToLong(idParams.getEndId());
}
if (params instanceof TradeHistoryParamsTimeSpan) {
TradeHistoryParamsTimeSpan timeParams = (TradeHistoryParamsTimeSpan) params;
since = DateUtils.toMillisNullSafe(timeParams.getStartTime());
end = DateUtils.toMillisNullSafe(timeParams.getEndTime());
}
if (params instanceof TradeHistoryParamCurrencyPair) {
CurrencyPair pair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair();
if (pair != null) {
dsxpair = DSXAdapters.getPair(pair);
}
}
if (params instanceof TradeHistoryParamsSorted) {
TradeHistoryParamsSorted tradeHistoryParamsSorted = (TradeHistoryParamsSorted) params;
TradeHistoryParamsSorted.Order order = tradeHistoryParamsSorted.getOrder();
if (order != null)
sort = order.equals(TradeHistoryParamsSorted.Order.desc) ? DSXAuthenticatedV2.SortOrder.DESC : DSXAuthenticatedV2.SortOrder.ASC;
}
Map<Long, DSXTradeHistoryResult> resultMap = getDSXTradeHistory(count, fromId, endId, sort, since, end, dsxpair);
return DSXAdapters.adaptTradeHistory(resultMap);
}
private static Long nullSafeToLong(String str) {
try {
return (str == null || str.isEmpty()) ? null : Long.valueOf(str);
} catch (NumberFormatException e) {
return null;
}
}
private static Long nullSafeUnixTime(Date time) {
return time != null ? DateUtils.toUnixTime(time) : null;
}
@Override
public TradeHistoryParams createTradeHistoryParams() {
return new DSXTradeHistoryParams();
}
@Override
public OpenOrdersParams createOpenOrdersParams() {
return new DefaultOpenOrdersParamCurrencyPair();
}
@Override
public Collection<Order> getOrder(String... orderIds) throws IOException {
throw new NotYetImplementedForExchangeException();
}
public Map<Long, DSXTransHistoryResult> getTransHistory(DSXTransHistoryParams params) throws ExchangeException, IOException {
Integer count = params.getLimit();
Long startId = nullSafeToLong(params.getStartId());
Long endId = nullSafeToLong(params.getEndId());
Long startTime = nullSafeUnixTime(params.getStartTime());
Long endTime = nullSafeUnixTime(params.getEndTime());
DSXAuthenticatedV2.SortOrder sort = params.getOrder().equals(TradeHistoryParamsSorted.Order.desc) ? DSXAuthenticatedV2.SortOrder.DESC : DSXAuthenticatedV2.SortOrder.ASC;
DSXTransHistoryResult.Status status = params.getStatus();
DSXTransHistoryResult.Type type = params.getType();
Currency c = params.getCurrency();
String currency = c == null ? null : c.getCurrencyCode();
return getDSXTransHistory(count, startId, endId, sort, startTime, endTime, type, status, currency);
}
}
|
[DSX] implemented @Override placeStopOrder
|
xchange-dsx/src/main/java/org/knowm/xchange/dsx/service/DSXTradeService.java
|
[DSX] implemented @Override placeStopOrder
|
|
Java
|
mit
|
56a5426f63817085586e2f1752b272d0f3b29de3
| 0
|
BFriedland/star-trees,BFriedland/star-trees,BFriedland/star-trees
|
import java.util.ArrayList;
public class StarTree {
public static void main(String[] args) {
String completed_tree = "incomplete";
Integer number_of_levels = 3;
if (args.length > 0) {
// Exception handling while parsing CLI arguments, courtesy of:
// https://docs.oracle.com/javase/tutorial/
// essential/environment/cmdLineArgs.html
try {
number_of_levels = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("The first supplied argument must be an integer.");
System.exit(1);
}
}
completed_tree = build_tree(number_of_levels);
System.out.println(completed_tree);
}
private static String build_tree(Integer levels) {
String current_line = "";
ArrayList<String> full_tree;
String completed_tree = "";
String spaces = "";
String stars = "";
Integer number_of_spaces_on_this_line = 0;
Integer number_of_stars_on_this_line = 0;
full_tree = new ArrayList<String>();
for (Integer each_level = 1; each_level <= levels; each_level++) {
for (Integer current_tier = 0; current_tier <= each_level; current_tier++) {
number_of_spaces_on_this_line = levels - current_tier;
number_of_stars_on_this_line = (current_tier * 2) + 1;
// number_of_stars_on_this_line = ((levels - number_of_spaces_on_this_line) * 2) + 1;
// Reference:
// http://stackoverflow.com/a/16812721
// This one is complicated to explain at first.
// This puts a new String object into current_line.
// The first parameter of this String object is
// whatever the String contains, such as:
// new String("Hello")
// So, this String contains an array full of chars.
// This array full of chars is initialized with a
// number; this number will populate the char array
// with a number of null characters (ie, "\0").
// These null characters are then all replaced with
// spaces (ie, " ") using the String class's replace
// method. ... I chose this because I wanted to
// understand why String formatting wasn't easy by
// default. It sort of is; it just isn't obvious.
spaces = new String(
new char[number_of_spaces_on_this_line]
).replace("\0", " ");
stars = new String(
new char[number_of_stars_on_this_line]
).replace("\0", "*");
current_line = spaces + stars;
full_tree.add(current_line);
}
}
// Reference:
// http://stackoverflow.com/a/599181
for (String each_row : full_tree) {
completed_tree += "\n" + each_row;
}
return completed_tree;
}
}
|
StarTree.java
|
import java.util.ArrayList;
public class StarTree {
public static void main(String[] args) {
String completed_tree = "incomplete";
completed_tree = build_tree(3);
System.out.println(completed_tree);
}
private static String build_tree(Integer levels) {
String current_line = "";
ArrayList<String> full_tree;
String completed_tree = "";
String spaces = "";
String stars = "";
Integer number_of_spaces_on_this_line = 0;
Integer number_of_stars_on_this_line = 0;
full_tree = new ArrayList<String>();
for (Integer each_level = 1; each_level <= levels; each_level++) {
for (Integer current_tier = 0; current_tier <= each_level; current_tier++) {
number_of_spaces_on_this_line = levels - current_tier;
number_of_stars_on_this_line = (current_tier * 2) + 1;
// number_of_stars_on_this_line = ((levels - number_of_spaces_on_this_line) * 2) + 1;
// Reference:
// http://stackoverflow.com/a/16812721
// This one is complicated to explain at first.
// This puts a new String object into current_line.
// The first parameter of this String object is
// whatever the String contains, such as:
// new String("Hello")
// So, this String contains an array full of chars.
// This array full of chars is initialized with a
// number; this number will populate the char array
// with a number of null characters (ie, "\0").
// These null characters are then all replaced with
// spaces (ie, " ") using the String class's replace
// method. ... I chose this because I wanted to
// understand why String formatting wasn't easy by
// default. It sort of is; it just isn't obvious.
spaces = new String(
new char[number_of_spaces_on_this_line]
).replace("\0", " ");
stars = new String(
new char[number_of_stars_on_this_line]
).replace("\0", "*");
current_line = spaces + stars;
full_tree.add(current_line);
}
}
// Reference:
// http://stackoverflow.com/a/599181
for (String each_row : full_tree) {
completed_tree += "\n" + each_row;
}
return completed_tree;
}
}
|
Add CLI arg support to StarTree.java
|
StarTree.java
|
Add CLI arg support to StarTree.java
|
|
Java
|
epl-1.0
|
1d2521945c159f7f686b171cbac899d32ba989cd
| 0
|
gnodet/wikitext
|
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.mylar.internal.tasks.ui.TaskListImages;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListContentProvider;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListView;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
/**
* @author Rob Elves
*/
public class ModelDropDownSelectionAction extends Action implements IMenuCreator {
private static final String LABEL_NAME = "Task List Mode";
public static final String ID = "org.eclipse.mylar.tasklist.actions.modelselection";
private TaskListView view;
protected Menu dropDownMenu = null;
private TaskListContentProvider[] contentProviders;
public ModelDropDownSelectionAction(TaskListView view, TaskListContentProvider[] contentProviders) {
super();
this.view = view;
setMenuCreator(this);
setText(LABEL_NAME);
setToolTipText(LABEL_NAME);
setId(ID);
setEnabled(true);
setImageDescriptor(TaskListImages.TASKLIST_MODE);
this.contentProviders = contentProviders;
}
protected void addActionsToMenu() {
for (TaskListContentProvider provider : contentProviders) {
ModelSelectionAction action = new ModelSelectionAction(provider);
ActionContributionItem item = new ActionContributionItem(action);
action.setText(provider.getLabel());
action.setChecked(view.getViewer().getContentProvider().equals(provider));
item.fill(dropDownMenu, -1);
}
}
@Override
public void run() {
// ignore
}
public void dispose() {
if (dropDownMenu != null) {
dropDownMenu.dispose();
dropDownMenu = null;
}
}
public Menu getMenu(Control parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public Menu getMenu(Menu parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
private class ModelSelectionAction extends Action {
private TaskListContentProvider provider;
public ModelSelectionAction(TaskListContentProvider provider) {
this.provider = provider;
setText(provider.getLabel());
}
@Override
public void run() {
try {
view.getViewer().getControl().setRedraw(false);
view.getViewer().setContentProvider(provider);
view.refreshAndFocus(view.isFocusedMode());
} finally {
view.getViewer().getControl().setRedraw(true);
}
}
}
}
|
org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/ModelDropDownSelectionAction.java
|
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.tasks.ui.actions;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.mylar.internal.tasks.ui.TaskListImages;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListContentProvider;
import org.eclipse.mylar.internal.tasks.ui.views.TaskListView;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
/**
* @author Rob Elves
*/
public class ModelDropDownSelectionAction extends Action implements IMenuCreator {
private static final String LABEL_NAME = "Task List Mode";
public static final String ID = "org.eclipse.mylar.tasklist.actions.modelselection";
private TaskListView view;
protected Menu dropDownMenu = null;
private TaskListContentProvider[] contentProviders;
public ModelDropDownSelectionAction(TaskListView view, TaskListContentProvider[] contentProviders) {
super();
this.view = view;
setMenuCreator(this);
setText(LABEL_NAME);
setToolTipText(LABEL_NAME);
setId(ID);
setEnabled(true);
setImageDescriptor(TaskListImages.TASKLIST_MODE);
this.contentProviders = contentProviders;
}
protected void addActionsToMenu() {
for (TaskListContentProvider provider : contentProviders) {
ModelSelectionAction action = new ModelSelectionAction(provider);
ActionContributionItem item = new ActionContributionItem(action);
action.setText(provider.getLabel());
action.setChecked(view.getViewer().getContentProvider().equals(provider));
item.fill(dropDownMenu, -1);
}
}
@Override
public void run() {
// ignore for now
}
public void dispose() {
if (dropDownMenu != null) {
dropDownMenu.dispose();
dropDownMenu = null;
}
}
public Menu getMenu(Control parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public Menu getMenu(Menu parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
private class ModelSelectionAction extends Action {
private TaskListContentProvider provider;
public ModelSelectionAction(TaskListContentProvider provider) {
this.provider = provider;
setText(provider.getLabel());
}
@Override
public void run() {
view.getViewer().setContentProvider(provider);
view.refreshAndFocus(view.isFocusedMode());
}
}
}
|
NEW - bug 147084: merge Task List and Task Activity views
https://bugs.eclipse.org/bugs/show_bug.cgi?id=147084
|
org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/ModelDropDownSelectionAction.java
|
NEW - bug 147084: merge Task List and Task Activity views https://bugs.eclipse.org/bugs/show_bug.cgi?id=147084
|
|
Java
|
epl-1.0
|
72bd9a8014a2b695112ccab755d573aa04955ba8
| 0
|
ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio
|
package org.csstudio.utility.nameSpaceBrowser;
import org.csstudio.platform.ui.AbstractCssUiPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractCssUiPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.csstudio.utility.nameSpaceBrowser"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void doStart(BundleContext context) throws Exception {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void doStop(BundleContext context) throws Exception {
plugin = null;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
@Override
public String getPluginId() {
return PLUGIN_ID;
}
}
|
applications/plugins/org.csstudio.utility.nameSpaceBrowser/src/org/csstudio/utility/nameSpaceBrowser/Activator.java
|
package org.csstudio.utility.nameSpaceBrowser;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.csstudio.utility.nameSpaceBrowser"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
|
AbstractUIPlugin -> AbstractCssUiPlugin
|
applications/plugins/org.csstudio.utility.nameSpaceBrowser/src/org/csstudio/utility/nameSpaceBrowser/Activator.java
|
AbstractUIPlugin -> AbstractCssUiPlugin
|
|
Java
|
epl-1.0
|
8e5f09dedad0a3fadc7aa400d4c47268b763bf3b
| 0
|
Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1
|
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and
* the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html Contributors: Actuate Corporation -
* initial API and implementation
******************************************************************************/
package org.eclipse.birt.report.engine.api.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.DataEngine;
import org.eclipse.birt.data.engine.api.IPreparedQuery;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.ReportEngine;
import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.ParameterHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SelectionChoiceHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
/**
* Defines an engine task that handles parameter definition retrieval
*/
public class GetParameterDefinitionTask extends EngineTask
implements
IGetParameterDefinitionTask
{
// stores all parameter definitions. Each task clones the parameter
// definition information
// so that Engine IR (repor runnable) can keep a task-independent of the
// parameter definitions.
protected Collection parameterDefns = null;
protected HashMap dataCache = null;
protected HashMap labelMap = null;
protected HashMap valueMap = null;
/**
* @param engine
* reference to the report engine
* @param runnable
* the runnable report design
*/
public GetParameterDefinitionTask( ReportEngine engine,
IReportRunnable runnable )
{
super( engine, runnable );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#getParameterDefns(boolean)
*/
public Collection getParameterDefns( boolean includeParameterGroups )
{
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( includeParameterGroups );
Iterator iter = original.iterator( );
// Clone parameter definitions, fill in locale and report dsign
// information
parameterDefns = new ArrayList( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
try
{
parameterDefns.add( pBase.clone( ) );
}
catch ( CloneNotSupportedException e ) // This is a Java exception
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
if ( parameterDefns != null )
{
iter = parameterDefns.iterator( );
while ( iter.hasNext( ) )
{
IParameterDefnBase pBase = (IParameterDefnBase) iter.next( );
if ( pBase instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) pBase ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) pBase ).setLocale( locale );
( (ScalarParameterDefn) pBase ).evaluateSelectionList( );
}
else if ( pBase instanceof ParameterGroupDefn )
{
Iterator iter2 = ( (ParameterGroupDefn) pBase )
.getContents( ).iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2
.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p )
.setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
}
return parameterDefns;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#evaluateDefaults()
*/
public void evaluateDefaults( ) throws EngineException
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#setValue(java.lang.String,
* java.lang.Object)
*/
public void setValue( String name, Object value )
{
setParameterValue( name, value );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getDefaultValues()
*/
public HashMap getDefaultValues( )
{
return getDefaultParameterValues( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#getDefaultValue(org.eclipse.birt.report.engine.api2.IParameterDefnBase)
*/
public Object getDefaultValue( IParameterDefnBase param )
{
return getDefaultParameterValue( param.getName( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getParameterDefn(java.lang.String)
*/
public IParameterDefnBase getParameterDefn( String name )
{
IParameterDefnBase ret = null;
if ( name == null )
{
return ret;
}
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( false );
Iterator iter = original.iterator( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
if ( name.equals( pBase.getName( ) ) )
{
try
{
ret = (IParameterDefnBase) pBase.clone( );
break;
}
catch ( CloneNotSupportedException e ) // This is a Java
// exception
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
}
if ( ret != null )
{
if ( ret instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) ret ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) ret ).setLocale( locale );
( (ScalarParameterDefn) ret ).evaluateSelectionList( );
}
else if ( ret instanceof ParameterGroupDefn )
{
Iterator iter2 = ( (ParameterGroupDefn) ret ).getContents( )
.iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
return ret;
}
public SlotHandle getParameters( )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.getParameters( );
}
public ParameterHandle getParameter( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findParameter( name );
}
public HashMap getDefaultParameterValues()
{
//using current parameter settings to evaluate the default parameters
usingParameterValues();
final HashMap values = new HashMap( );
//reset the context parameters
new ParameterVisitor( ) {
boolean visitScalarParameter( ScalarParameterHandle param )
{
String name = param.getName( );
String expr = param.getDefaultValue( );
String type = param.getDataType( );
Object value = evaluate( expr, type );
values.put( name, value );
return true;
}
boolean visitParameterGroup( ParameterGroupHandle group )
{
return visitParametersInGroup( group );
}
}.visit( );
return values;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getDefaultParameter(java.lang.String)
*/
public Object getDefaultParameterValue( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return null;
}
usingParameterValues();
//using the current setting to evaluate the parameter values.
String expr = parameter.getDefaultValue( );
if ( expr == null || expr.length( ) == 0 )
{
return null;
}
return evaluate( expr, parameter.getDataType( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getSelectionChoice(java.lang.String)
*/
public Collection getSelectionChoice( String name )
{
usingParameterValues();
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return null;
}
String selectionType = parameter.getValueType();
String dataType = parameter.getDataType( );
if (DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC.equals(selectionType))
{
String dataSetName = parameter.getDataSetName();
String labelExpr = parameter.getLabelExpr();
String valueExpr = parameter.getValueExpr();
return createDynamicSelectionChoices(dataSetName, labelExpr, valueExpr);
}
else if (DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC.equals(selectionType))
{
Iterator iter = parameter.choiceIterator( );
ArrayList choices = new ArrayList( );
while ( iter.hasNext( ) )
{
SelectionChoiceHandle choice = (SelectionChoiceHandle) iter.next( );
String label = report.getMessage( choice.getLabelKey( ), locale );
if ( label != null )
{
label = choice.getLabel( );
}
Object value = getStringValue( choice.getValue( ), dataType );
choices.add( new SelectionChoice( label, value ) );
}
return choices;
}
return null;
}
/**
* convert the string to value.
* @param value value string
* @param valueType value type
* @return object with the specified value
*/
private Object getStringValue( String value, String valueType )
{
try
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( valueType ) )
return DataTypeUtil.toBoolean( value );
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( valueType ) )
return DataTypeUtil.toDate( value );
if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( valueType ) )
return DataTypeUtil.toBigDecimal( value );
if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( valueType ) )
return DataTypeUtil.toDouble( value );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getLocalizedMessage( ), e );
}
return value;
}
/**
* get selection choices from the data set.
* @param dataSetName data set name
* @param labelStmt label statement
* @param valueStmt value statement
* @return
*/
private Collection createDynamicSelectionChoices(String dataSetName, String labelStmt, String valueStmt)
{
ArrayList choices = new ArrayList();
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
DataSetHandle dataSet = report.findDataSet(dataSetName);
if (dataSet != null)
{
try
{
DataEngine dataEngine = getDataEngine();
// Define data source and data set
DataSourceHandle dataSource = dataSet.getDataSource();
try
{
dataEngine.defineDataSource( ModelDteApiAdapter.getInstance( )
.createDataSourceDesign(dataSource));
dataEngine.defineDataSet( ModelDteApiAdapter.getInstance( )
.createDataSetDesign(dataSet) );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getMessage());
}
ScriptExpression labelExpr = new ScriptExpression(labelStmt);
ScriptExpression valueExpr = new ScriptExpression(valueStmt);
QueryDefinition queryDefn = new QueryDefinition();
queryDefn.setDataSetName(dataSetName);
//add parameters if have any
Iterator paramIter = dataSet.paramBindingsIterator();
while (paramIter.hasNext())
{
ParamBindingHandle binding = (ParamBindingHandle)paramIter.next();
String paramName = binding.getParamName();
String paramExpr = binding.getExpression();
queryDefn.getInputParamBindings().add(new InputParameterBinding( paramName, new ScriptExpression(paramExpr)));
}
queryDefn.getRowExpressions().add(labelExpr);
queryDefn.getRowExpressions().add(valueExpr);
// Create a group to skip all of the duplicate values
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyExpression( valueStmt );
queryDefn.addGroup( groupDef );
IPreparedQuery query = dataEngine.prepare(queryDefn);
IQueryResults result = query.execute(executionContext.getSharedScope());
IResultIterator iter = result.getResultIterator();
while (iter.next())
{
String label = iter.getString(labelExpr);
Object value = iter.getValue(valueExpr);
choices.add(new SelectionChoice(label, value));
iter.skipToEnd( 1 ); // Skip all of the duplicate values
}
}
catch(BirtException ex)
{
ex.printStackTrace();
}
}
return choices;
}
/**
* The first step to work with the cascading parameters.
* Create the query definition, prepare and execute the query.
* Cache the iterator of the result set and also cache the IBaseExpression used in the prepare.
*
* @param parameterGroupName - the cascading parameter group name
*/
public void evaluateQuery( String parameterGroupName )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( dataCache == null )
dataCache = new HashMap();
if ( parameterGroup == null )
return;
DataSetHandle dataSet = parameterGroup.getDataSet();
if (dataSet != null)
{
try
{
// Handle data source and data set
DataEngine dataEngine = getDataEngine();
DataSourceHandle dataSource = dataSet.getDataSource();
try
{
dataEngine.defineDataSource( ModelDteApiAdapter.getInstance( )
.createDataSourceDesign(dataSource));
dataEngine.defineDataSet( ModelDteApiAdapter.getInstance( )
.createDataSetDesign(dataSet) );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getMessage());
}
QueryDefinition queryDefn = new QueryDefinition();
queryDefn.setDataSetName( dataSet.getName() );
SlotHandle parameters = parameterGroup.getParameters( );
Iterator iter = parameters.iterator( );
if ( labelMap == null )
labelMap = new HashMap();
if ( valueMap == null )
valueMap = new HashMap();
while ( iter.hasNext( ) )
{
Object param = iter.next( );
if ( param instanceof ScalarParameterHandle )
{
String valueExpString = ((ScalarParameterHandle)param).getValueExpr();
Object valueExpObject = new ScriptExpression(valueExpString);
valueMap.put(parameterGroup.getName() + "_" + ((ScalarParameterHandle)param).getName(), valueExpObject);
queryDefn.getRowExpressions().add( valueExpObject );
String labelExpString = ((ScalarParameterHandle)param).getLabelExpr();
if (labelExpString == null)
{
labelExpString = valueExpString;
}
Object labelExpObject = new ScriptExpression(labelExpString);
labelMap.put(parameterGroup.getName() + "_" + ((ScalarParameterHandle)param).getName(), labelExpObject);
queryDefn.getRowExpressions().add( labelExpObject );
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyExpression( valueExpString );
queryDefn.addGroup( groupDef );
}
}
IPreparedQuery query = dataEngine.prepare(queryDefn);
IQueryResults result = query.execute(executionContext.getSharedScope());
IResultIterator resultIter = result.getResultIterator();
dataCache.put( parameterGroup.getName(), resultIter );
return;
}
catch(BirtException ex)
{
ex.printStackTrace();
}
}
dataCache.put( parameterGroup.getName(), null );
}
/**
* The second step to work with the cascading parameters.
* Get the selection choices for a parameter in the cascading group.
* The parameter to work on is the parameter on the next level in the parameter cascading hierarchy.
* For the "parameter to work on", please see the following example.
* Assume we have a cascading parameter group as Country - State - City.
* If user specified an empty array in groupKeyValues (meaning user doesn't have any parameter value),
* the parameter to work on will be the first level which is Country in this case.
* If user specified groupKeyValues as Object[]{"USA"} (meaning user has set the value of the top level),
* the parameter to work on will be the second level which is State in "USA" in this case.
* If user specified groupKeyValues as Object[]{"USA", "CA"} (meaning user has set the values of the top and the second level),
* the parameter to work on will be the third level which is City in "USA, CA" in this case.
*
* @param parameterGroupName - the cascading parameter group name
* @param groupKeyValues - the array of known parameter values (see the example above)
* @return the selection list of the parameter to work on
*/
public Collection getSelectionChoicesForCascadingGroup( String parameterGroupName, Object[] groupKeyValues )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( parameterGroup == null )
return null;
IResultIterator iter = (IResultIterator) dataCache.get( parameterGroup.getName() );
if ( iter == null )
return null;
SlotHandle slotHandle = parameterGroup.getParameters();
assert ( groupKeyValues.length < slotHandle.getCount() );
int skipLevel = groupKeyValues.length + 1;
ScalarParameterHandle requestedParam = (ScalarParameterHandle) slotHandle.get( groupKeyValues.length ); // The parameters in parameterGroup must be scalar parameters.
int listLimit = requestedParam.getListlimit();
// We need to cache the expression object in function evaluateQuery and
// use the cached object here instead of creating a new one because
// according to DtE API for IResultIterator.getString,
// the expression object must be the same object created at the time of preparation.
// Actually, the prepare process will modify the expression object , only after which
// the expression object can be used to get the real value from the result set.
// If we create a new expression object here, it won't work.
ScriptExpression labelExpr = (ScriptExpression)labelMap.get(parameterGroup.getName() + "_" + requestedParam.getName());
ScriptExpression valueExpr = (ScriptExpression)valueMap.get(parameterGroup.getName() + "_" + requestedParam.getName());
ArrayList choices = new ArrayList();
try
{
if ( skipLevel > 1 )
iter.findGroup( groupKeyValues );
int count = 0;
while ( iter.next() )
{
String label = iter.getString( labelExpr );
Object value = iter.getValue( valueExpr );
choices.add( new SelectionChoice(label, value) );
count++;
if ( (listLimit != 0) &&
(count >= listLimit) )
break;
iter.skipToEnd( skipLevel );
}
}
catch (BirtException e)
{
e.printStackTrace();
}
return choices;
}
private CascadingParameterGroupHandle getCascadingParameterGroup( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findCascadingParameterGroup(name);
}
static class SelectionChoice implements IParameterSelectionChoice
{
String label;
Object value;
SelectionChoice( String label, Object value )
{
this.label = label;
this.value = value;
}
public String getLabel( )
{
return this.label;
}
public Object getValue( )
{
return this.value;
}
}
}
|
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/GetParameterDefinitionTask.java
|
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and
* the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html Contributors: Actuate Corporation -
* initial API and implementation
******************************************************************************/
package org.eclipse.birt.report.engine.api.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.DataEngine;
import org.eclipse.birt.data.engine.api.IPreparedQuery;
import org.eclipse.birt.data.engine.api.IQueryResults;
import org.eclipse.birt.data.engine.api.IResultIterator;
import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition;
import org.eclipse.birt.data.engine.api.querydefn.InputParameterBinding;
import org.eclipse.birt.data.engine.api.querydefn.QueryDefinition;
import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression;
import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IParameterDefnBase;
import org.eclipse.birt.report.engine.api.IParameterSelectionChoice;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.ReportEngine;
import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.ParamBindingHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.ParameterHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SelectionChoiceHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
/**
* Defines an engine task that handles parameter definition retrieval
*/
public class GetParameterDefinitionTask extends EngineTask
implements
IGetParameterDefinitionTask
{
// stores all parameter definitions. Each task clones the parameter
// definition information
// so that Engine IR (repor runnable) can keep a task-independent of the
// parameter definitions.
protected Collection parameterDefns = null;
protected HashMap dataCache = null;
protected HashMap labelMap = null;
protected HashMap valueMap = null;
/**
* @param engine
* reference to the report engine
* @param runnable
* the runnable report design
*/
public GetParameterDefinitionTask( ReportEngine engine,
IReportRunnable runnable )
{
super( engine, runnable );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#getParameterDefns(boolean)
*/
public Collection getParameterDefns( boolean includeParameterGroups )
{
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( includeParameterGroups );
Iterator iter = original.iterator( );
// Clone parameter definitions, fill in locale and report dsign
// information
parameterDefns = new ArrayList( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
try
{
parameterDefns.add( pBase.clone( ) );
}
catch ( CloneNotSupportedException e ) // This is a Java exception
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
if ( parameterDefns != null )
{
iter = parameterDefns.iterator( );
while ( iter.hasNext( ) )
{
IParameterDefnBase pBase = (IParameterDefnBase) iter.next( );
if ( pBase instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) pBase ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) pBase ).setLocale( locale );
( (ScalarParameterDefn) pBase ).evaluateSelectionList( );
}
else if ( pBase instanceof ParameterGroupDefn )
{
Iterator iter2 = ( (ParameterGroupDefn) pBase )
.getContents( ).iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2
.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p )
.setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
}
return parameterDefns;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#evaluateDefaults()
*/
public void evaluateDefaults( ) throws EngineException
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#setValue(java.lang.String,
* java.lang.Object)
*/
public void setValue( String name, Object value )
{
setParameterValue( name, value );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getDefaultValues()
*/
public HashMap getDefaultValues( )
{
return getDefaultParameterValues( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api2.IGetParameterDefinitionTask#getDefaultValue(org.eclipse.birt.report.engine.api2.IParameterDefnBase)
*/
public Object getDefaultValue( IParameterDefnBase param )
{
return getDefaultParameterValue( param.getName( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getParameterDefn(java.lang.String)
*/
public IParameterDefnBase getParameterDefn( String name )
{
IParameterDefnBase ret = null;
if ( name == null )
{
return ret;
}
Collection original = ( (ReportRunnable) runnable )
.getParameterDefns( false );
Iterator iter = original.iterator( );
while ( iter.hasNext( ) )
{
ParameterDefnBase pBase = (ParameterDefnBase) iter.next( );
if ( name.equals( pBase.getName( ) ) )
{
try
{
ret = (IParameterDefnBase) pBase.clone( );
break;
}
catch ( CloneNotSupportedException e ) // This is a Java
// exception
{
log.log( Level.SEVERE, e.getMessage( ), e );
}
}
}
if ( ret != null )
{
if ( ret instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) ret ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) ret ).setLocale( locale );
( (ScalarParameterDefn) ret ).evaluateSelectionList( );
}
else if ( ret instanceof ParameterGroupDefn )
{
Iterator iter2 = ( (ParameterGroupDefn) ret ).getContents( )
.iterator( );
while ( iter2.hasNext( ) )
{
IParameterDefnBase p = (IParameterDefnBase) iter2.next( );
if ( p instanceof ScalarParameterDefn )
{
( (ScalarParameterDefn) p ).setReportDesign( runnable
.getDesignHandle( ).getDesign( ) );
( (ScalarParameterDefn) p ).setLocale( locale );
( (ScalarParameterDefn) p ).evaluateSelectionList( );
}
}
}
}
return ret;
}
public SlotHandle getParameters( )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.getParameters( );
}
public ParameterHandle getParameter( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findParameter( name );
}
public HashMap getDefaultParameterValues()
{
//using current parameter settings to evaluate the default parameters
usingParameterValues();
final HashMap values = new HashMap( );
//reset the context parameters
new ParameterVisitor( ) {
boolean visitScalarParameter( ScalarParameterHandle param )
{
String name = param.getName( );
String expr = param.getDefaultValue( );
String type = param.getDataType( );
Object value = evaluate( expr, type );
values.put( name, value );
return true;
}
boolean visitParameterGroup( ParameterGroupHandle group )
{
return visitParametersInGroup( group );
}
}.visit( );
return values;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getDefaultParameter(java.lang.String)
*/
public Object getDefaultParameterValue( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return null;
}
usingParameterValues();
//using the current setting to evaluate the parameter values.
String expr = parameter.getDefaultValue( );
if ( expr == null || expr.length( ) == 0 )
{
return null;
}
return evaluate( expr, parameter.getDataType( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask#getSelectionChoice(java.lang.String)
*/
public Collection getSelectionChoice( String name )
{
usingParameterValues();
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
ScalarParameterHandle parameter = (ScalarParameterHandle) report
.findParameter( name );
if ( parameter == null )
{
return null;
}
String selectionType = parameter.getValueType();
String dataType = parameter.getDataType( );
if (DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC.equals(selectionType))
{
String dataSetName = parameter.getDataSetName();
String labelExpr = parameter.getLabelExpr();
String valueExpr = parameter.getValueExpr();
return createDynamicSelectionChoices(dataSetName, labelExpr, valueExpr);
}
else if (DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC.equals(selectionType))
{
Iterator iter = parameter.choiceIterator( );
ArrayList choices = new ArrayList( );
while ( iter.hasNext( ) )
{
SelectionChoiceHandle choice = (SelectionChoiceHandle) iter.next( );
String label = report.getMessage( choice.getLabelKey( ), locale );
if ( label != null )
{
label = choice.getLabel( );
}
Object value = getStringValue( choice.getValue( ), dataType );
choices.add( new SelectionChoice( label, value ) );
}
return choices;
}
return null;
}
/**
* convert the string to value.
* @param value value string
* @param valueType value type
* @return object with the specified value
*/
private Object getStringValue( String value, String valueType )
{
try
{
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( valueType ) )
return DataTypeUtil.toBoolean( value );
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( valueType ) )
return DataTypeUtil.toDate( value );
if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( valueType ) )
return DataTypeUtil.toBigDecimal( value );
if ( DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( valueType ) )
return DataTypeUtil.toDouble( value );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getLocalizedMessage( ), e );
}
return value;
}
/**
* get selection choices from the data set.
* @param dataSetName data set name
* @param labelStmt label statement
* @param valueStmt value statement
* @return
*/
private Collection createDynamicSelectionChoices(String dataSetName, String labelStmt, String valueStmt)
{
ArrayList choices = new ArrayList();
ReportDesignHandle report = (ReportDesignHandle) this.runnable
.getDesignHandle( );
DataSetHandle dataSet = report.findDataSet(dataSetName);
if (dataSet != null)
{
try
{
DataEngine dataEngine = getDataEngine();
// Define data source and data set
DataSourceHandle dataSource = dataSet.getDataSource();
try
{
dataEngine.defineDataSource( ModelDteApiAdapter.getInstance( )
.createDataSourceDesign(dataSource));
dataEngine.defineDataSet( ModelDteApiAdapter.getInstance( )
.createDataSetDesign(dataSet) );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getMessage());
}
ScriptExpression labelExpr = new ScriptExpression(labelStmt);
ScriptExpression valueExpr = new ScriptExpression(valueStmt);
QueryDefinition queryDefn = new QueryDefinition();
queryDefn.setDataSetName(dataSetName);
//add parameters if have any
Iterator paramIter = dataSet.paramBindingsIterator();
while (paramIter.hasNext())
{
ParamBindingHandle binding = (ParamBindingHandle)paramIter.next();
String paramName = binding.getParamName();
String paramExpr = binding.getExpression();
queryDefn.getInputParamBindings().add(new InputParameterBinding( paramName, new ScriptExpression(paramExpr)));
}
queryDefn.getRowExpressions().add(labelExpr);
queryDefn.getRowExpressions().add(valueExpr);
// Create a group to skip all of the duplicate values
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyExpression( valueStmt );
queryDefn.addGroup( groupDef );
IPreparedQuery query = dataEngine.prepare(queryDefn);
IQueryResults result = query.execute(executionContext.getSharedScope());
IResultIterator iter = result.getResultIterator();
while (iter.next())
{
String label = iter.getString(labelExpr);
Object value = iter.getValue(valueExpr);
choices.add(new SelectionChoice(label, value));
iter.skipToEnd( 1 ); // Skip all of the duplicate values
}
}
catch(BirtException ex)
{
ex.printStackTrace();
}
}
return choices;
}
/**
* The first step to work with the cascading parameters.
* Create the query definition, prepare and execute the query.
* Cache the iterator of the result set and also cache the IBaseExpression used in the prepare.
*
* @param parameterGroupName - the cascading parameter group name
*/
public void evaluateQuery( String parameterGroupName )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( dataCache == null )
dataCache = new HashMap();
if ( parameterGroup == null )
return;
DataSetHandle dataSet = parameterGroup.getDataSet();
if (dataSet != null)
{
try
{
// Handle data source and data set
DataEngine dataEngine = getDataEngine();
DataSourceHandle dataSource = dataSet.getDataSource();
try
{
dataEngine.defineDataSource( ModelDteApiAdapter.getInstance( )
.createDataSourceDesign(dataSource));
dataEngine.defineDataSet( ModelDteApiAdapter.getInstance( )
.createDataSetDesign(dataSet) );
}
catch ( BirtException e )
{
log.log( Level.SEVERE, e.getMessage());
}
QueryDefinition queryDefn = new QueryDefinition();
queryDefn.setDataSetName( dataSet.getName() );
SlotHandle parameters = parameterGroup.getParameters( );
Iterator iter = parameters.iterator( );
if ( labelMap == null )
labelMap = new HashMap();
if ( valueMap == null )
valueMap = new HashMap();
while ( iter.hasNext( ) )
{
Object param = iter.next( );
if ( param instanceof ScalarParameterHandle )
{
String labelExpString = ((ScalarParameterHandle)param).getLabelExpr();
Object labelExpObject = new ScriptExpression(labelExpString);
labelMap.put(parameterGroup.getName() + "_" + ((ScalarParameterHandle)param).getName(), labelExpObject);
queryDefn.getRowExpressions().add( labelExpObject );
String valueExpString = ((ScalarParameterHandle)param).getValueExpr();
Object valueExpObject = new ScriptExpression(valueExpString);
valueMap.put(parameterGroup.getName() + "_" + ((ScalarParameterHandle)param).getName(), valueExpObject);
queryDefn.getRowExpressions().add( valueExpObject );
GroupDefinition groupDef = new GroupDefinition( );
groupDef.setKeyExpression( valueExpString );
queryDefn.addGroup( groupDef );
}
}
IPreparedQuery query = dataEngine.prepare(queryDefn);
IQueryResults result = query.execute(executionContext.getSharedScope());
IResultIterator resultIter = result.getResultIterator();
dataCache.put( parameterGroup.getName(), resultIter );
return;
}
catch(BirtException ex)
{
ex.printStackTrace();
}
}
dataCache.put( parameterGroup.getName(), null );
}
/**
* The second step to work with the cascading parameters.
* Get the selection choices for a parameter in the cascading group.
* The parameter to work on is the parameter on the next level in the parameter cascading hierarchy.
* For the "parameter to work on", please see the following example.
* Assume we have a cascading parameter group as Country - State - City.
* If user specified an empty array in groupKeyValues (meaning user doesn't have any parameter value),
* the parameter to work on will be the first level which is Country in this case.
* If user specified groupKeyValues as Object[]{"USA"} (meaning user has set the value of the top level),
* the parameter to work on will be the second level which is State in "USA" in this case.
* If user specified groupKeyValues as Object[]{"USA", "CA"} (meaning user has set the values of the top and the second level),
* the parameter to work on will be the third level which is City in "USA, CA" in this case.
*
* @param parameterGroupName - the cascading parameter group name
* @param groupKeyValues - the array of known parameter values (see the example above)
* @return the selection list of the parameter to work on
*/
public Collection getSelectionChoicesForCascadingGroup( String parameterGroupName, Object[] groupKeyValues )
{
CascadingParameterGroupHandle parameterGroup = getCascadingParameterGroup( parameterGroupName );
if ( parameterGroup == null )
return null;
IResultIterator iter = (IResultIterator) dataCache.get( parameterGroup.getName() );
if ( iter == null )
return null;
SlotHandle slotHandle = parameterGroup.getParameters();
assert ( groupKeyValues.length < slotHandle.getCount() );
int skipLevel = groupKeyValues.length + 1;
ScalarParameterHandle requestedParam = (ScalarParameterHandle) slotHandle.get( groupKeyValues.length ); // The parameters in parameterGroup must be scalar parameters.
int listLimit = requestedParam.getListlimit();
// We need to cache the expression object in function evaluateQuery and
// use the cached object here instead of creating a new one because
// according to DtE API for IResultIterator.getString,
// the expression object must be the same object created at the time of preparation.
// Actually, the prepare process will modify the expression object , only after which
// the expression object can be used to get the real value from the result set.
// If we create a new expression object here, it won't work.
ScriptExpression labelExpr = (ScriptExpression)labelMap.get(parameterGroup.getName() + "_" + requestedParam.getName());
ScriptExpression valueExpr = (ScriptExpression)valueMap.get(parameterGroup.getName() + "_" + requestedParam.getName());
ArrayList choices = new ArrayList();
try
{
if ( skipLevel > 1 )
iter.findGroup( groupKeyValues );
int count = 0;
while ( iter.next() )
{
String label = iter.getString( labelExpr );
Object value = iter.getValue( valueExpr );
choices.add( new SelectionChoice(label, value) );
count++;
if ( (listLimit != 0) &&
(count >= listLimit) )
break;
iter.skipToEnd( skipLevel );
}
}
catch (BirtException e)
{
e.printStackTrace();
}
return choices;
}
private CascadingParameterGroupHandle getCascadingParameterGroup( String name )
{
ReportDesignHandle report = (ReportDesignHandle) runnable
.getDesignHandle( );
return report.findCascadingParameterGroup(name);
}
static class SelectionChoice implements IParameterSelectionChoice
{
String label;
Object value;
SelectionChoice( String label, Object value )
{
this.label = label;
this.value = value;
}
public String getLabel( )
{
return this.label;
}
public Object getValue( )
{
return this.value;
}
}
}
|
use the value as the labe if the lable is null in cascading paramters
|
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/api/impl/GetParameterDefinitionTask.java
|
use the value as the labe if the lable is null in cascading paramters
|
|
Java
|
epl-1.0
|
a35ef16ea1758e16c2883327e73c3e81be3c586e
| 0
|
Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts,Yakindu/statecharts
|
/**
* Copyright (c) 2012 committers of YAKINDU 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:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.model.stext.ui.validation;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.ResourceValidatorImpl;
import org.yakindu.sct.model.sgraph.resource.AbstractSCTResource;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class SCTResourceValidatorImpl extends ResourceValidatorImpl {
@Override
protected void resolveProxies(final Resource resource, final CancelIndicator monitor) {
if (resource instanceof AbstractSCTResource) {
((AbstractSCTResource) resource).resolveLazyCrossReferences(monitor);
} else
super.resolveProxies(resource, monitor);
}
}
|
plugins/org.yakindu.sct.model.stext.ui/src/org/yakindu/sct/model/stext/ui/validation/SCTResourceValidatorImpl.java
|
/**
* Copyright (c) 2012 committers of YAKINDU 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:
* committers of YAKINDU - initial API and implementation
*
*/
package org.yakindu.sct.model.stext.ui.validation;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.validation.ResourceValidatorImpl;
import org.yakindu.sct.model.sgraph.resource.AbstractSCTResource;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class SCTResourceValidatorImpl extends ResourceValidatorImpl {
@Override
protected void resolveProxies(final Resource resource,
final CancelIndicator monitor) {
if (resource instanceof AbstractSCTResource) {
((AbstractSCTResource) resource)
.resolveLazyCrossReferences(monitor);
}
}
}
|
Call super.resolveProxies when loaded with another resource than AbstractSCtResource
|
plugins/org.yakindu.sct.model.stext.ui/src/org/yakindu/sct/model/stext/ui/validation/SCTResourceValidatorImpl.java
|
Call super.resolveProxies when loaded with another resource than AbstractSCtResource
|
|
Java
|
agpl-3.0
|
f2fbe5ce3599b59de2c02d3a7db3f051872bcbfb
| 0
|
zuowang/voltdb,paulmartel/voltdb,creative-quant/voltdb,ingted/voltdb,paulmartel/voltdb,paulmartel/voltdb,creative-quant/voltdb,kumarrus/voltdb,flybird119/voltdb,creative-quant/voltdb,wolffcm/voltdb,simonzhangsm/voltdb,zuowang/voltdb,wolffcm/voltdb,zuowang/voltdb,ingted/voltdb,ingted/voltdb,migue/voltdb,VoltDB/voltdb,VoltDB/voltdb,deerwalk/voltdb,zuowang/voltdb,paulmartel/voltdb,flybird119/voltdb,migue/voltdb,deerwalk/voltdb,wolffcm/voltdb,kumarrus/voltdb,VoltDB/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,migue/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,flybird119/voltdb,wolffcm/voltdb,zuowang/voltdb,migue/voltdb,migue/voltdb,flybird119/voltdb,zuowang/voltdb,kumarrus/voltdb,zuowang/voltdb,wolffcm/voltdb,kumarrus/voltdb,ingted/voltdb,VoltDB/voltdb,creative-quant/voltdb,ingted/voltdb,kumarrus/voltdb,paulmartel/voltdb,VoltDB/voltdb,wolffcm/voltdb,simonzhangsm/voltdb,zuowang/voltdb,deerwalk/voltdb,deerwalk/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,creative-quant/voltdb,migue/voltdb,ingted/voltdb,flybird119/voltdb,migue/voltdb,simonzhangsm/voltdb,flybird119/voltdb,ingted/voltdb,creative-quant/voltdb,flybird119/voltdb,creative-quant/voltdb,kumarrus/voltdb,deerwalk/voltdb,wolffcm/voltdb,flybird119/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,paulmartel/voltdb,paulmartel/voltdb,migue/voltdb,ingted/voltdb,kumarrus/voltdb,paulmartel/voltdb,creative-quant/voltdb
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.compiler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.hsqldb_voltpatches.HSQLInterface;
import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException;
import org.hsqldb_voltpatches.VoltXMLElement;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONStringer;
import org.voltdb.VoltType;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Group;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.MaterializedViewInfo;
import org.voltdb.catalog.Table;
import org.voltdb.compiler.VoltCompiler.ProcedureDescriptor;
import org.voltdb.compiler.VoltCompiler.VoltCompilerException;
import org.voltdb.compilereport.TableAnnotation;
import org.voltdb.expressions.AbstractExpression;
import org.voltdb.expressions.TupleValueExpression;
import org.voltdb.planner.AbstractParsedStmt;
import org.voltdb.planner.ParsedSelectStmt;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.ExpressionType;
import org.voltdb.types.IndexType;
import org.voltdb.utils.BuildDirectoryUtils;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.VoltTypeUtil;
/**
* Compiles schema (SQL DDL) text files and stores the results in a given catalog.
*
*/
public class DDLCompiler {
static final int MAX_COLUMNS = 1024;
static final int MAX_ROW_SIZE = 1024 * 1024 * 2;
/**
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ one or more spaces
* (PROCEDURE|TABLE) -- either PROCEDURE or TABLE token
* \\s+ -- one or more spaces
* .+ -- one or more of any characters
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern prePartitionPattern = Pattern.compile(
"(?i)\\APARTITION\\s+(PROCEDURE|TABLE)\\s+.+;\\z"
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [table name capture group 1]
* [\\w$]+ -- 1 or more identifier character
* (letters, numbers, dollar sign ($) underscore (_))
* \\s+ -- one or more spaces
* ON -- token
* \\s+ -- one or more spaces
* COLUMN -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [column name capture group 2]
* [\\w$]+ -- 1 or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s* -- 0 or more spaces
* ; a -- semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern partitionTablePattern = Pattern.compile(
"(?i)\\APARTITION\\s+TABLE\\s+([\\w$]+)\\s+ON\\s+COLUMN\\s+([\\w$]+)\\s*;\\z"
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ -- one or more spaces
* PROCEDURE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [procedure name capture group 1]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s+ -- one or more spaces
* ON -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [table name capture group 2]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s+ -- one or more spaces
* COLUMN -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [column name capture group 3]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* (?:\\s+PARAMETER\\s+(\\d+))? 0 or 1 parameter clause [non-capturing]
* \\s+ -- one or more spaces
* PARAMETER -- token
* \\s+ -- one or more spaces
* \\d+ -- one ore more number digits [parameter index capture group 4]
* \\s* -- 0 or more spaces
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern partitionProcedurePattern = Pattern.compile(
"(?i)\\APARTITION\\s+PROCEDURE\\s+([\\w$]+)\\s+ON\\s+TABLE\\s+" +
"([\\w$]+)\\s+COLUMN\\s+([\\w$]+)(?:\\s+PARAMETER\\s+(\\d+))?\\s*;\\z"
);
/**
* CREATE PROCEDURE from Java class statement regex
* NB supports only unquoted table and column names
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern procedureClassPattern = Pattern.compile(
"(?i)" + // ignore case
"\\A" + // beginning of statement
"CREATE" + // CREATE token
"\\s+" + // one or more spaces
"PROCEDURE" + // PROCEDURE token
"(?:" + // begin optional ALLOW clause
"\\s+" + // one or more spaces
"ALLOW" + // ALLOW token
"\\s+" + // one or more spaces
"([\\w.$]+(?:\\s*,\\s*[\\w.$]+)*)" + // (1) comma-separated role list
")?" + // end optional ALLOW clause
"\\s+" + // one or more spaces
"FROM" + // FROM token
"\\s+" + // one or more spaces
"CLASS" + // CLASS token
"\\s+" + // one or more spaces
"([\\w$.]+)" + // (2) class name
"\\s*" + // zero or more spaces
";" + // semi-colon terminator
"\\z" // end of statement
);
/**
* CREATE PROCEDURE with single SELECT or DML statement regex
* NB supports only unquoted table and column names
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern procedureSingleStatementPattern = Pattern.compile(
"(?i)" + // ignore case
"\\A" + // beginning of DDL statement
"CREATE" + // CREATE token
"\\s+" + // one or more spaces
"PROCEDURE" + // PROCEDURE token
"\\s+" + // one or more spaces
"([\\w.$]+)" + // (1) procedure name
"(?:" + // begin optional ALLOW clause
"\\s+" + // one or more spaces
"ALLOW" + // ALLOW token
"\\s+" + // one or more spaces
"([\\w.$]+(?:\\s*,\\s*[\\w.$]+)*)" + // (2) comma-separated role list
")?" + // end optional ALLOW clause
"\\s+" + // one or more spaces
"AS" + // AS token
"\\s+" + // one or more spaces
"(" + // (3) begin SELECT or DML statement
"(?:SELECT|INSERT|UPDATE|DELETE)" + // valid DML start tokens (not captured)
"\\s+" + // one or more spaces
".+)" + // end SELECT or DML statement
";" + // semi-colon terminator
"\\z" // end of DDL statement
);
/**
* Regex to parse the CREATE ROLE statement with optional WITH clause.
* Leave the WITH clause argument as a single group because regexes
* aren't capable of producing a variable number of groups.
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern createRolePattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // (start statement)
"CREATE\\s+ROLE\\s+" + // CREATE ROLE
"([\\w.$]+)" + // (1) <role name>
"(?:\\s+WITH\\s+" + // (start optional WITH clause block)
"(\\w+(?:\\s*,\\s*\\w+)*)" + // (2) <comma-separated argument string>
")?" + // (end optional WITH clause block)
";\\z" // (end statement)
);
/**
* Regex to match CREATE TABLE or CREATE VIEW statements.
* Unlike the other matchers, this is just designed to pull out the
* name of the table or view, not the whole statement.
* It's used to preserve as-entered schema for each table/view
* for the catalog report generator for the moment.
* Capture group (1) is ignored, but (2) is used.
*/
static final Pattern createTablePattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // (start statement)
"CREATE\\s+(TABLE|VIEW)\\s+" + // (1) CREATE TABLE
"([\\w.$]+)" // (2) <table name>
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* REPLICATE -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$.]+) -- [table name capture group 1]
* [\\w$]+ -- one or more identifier character (letters, numbers, dollar sign ($) or underscore (_))
* \\s* -- 0 or more spaces
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern replicatePattern = Pattern.compile(
"(?i)\\AREPLICATE\\s+TABLE\\s+([\\w$]+)\\s*;\\z"
);
/**
* EXPORT TABLE statement regex
* NB supports only unquoted table names
* Capture groups are tagged as (1) in comments below.
*/
static final Pattern exportPattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // start statement
"EXPORT\\s+TABLE\\s+" + // EXPORT TABLE
"([\\w.$]+)" + // (1) <table name>
"\\s*;\\z" // (end statement)
);
/**
* Regex Description:
*
* if the statement starts with either create procedure, partition,
* replicate, or role the first match group is set to respectively procedure,
* partition, replicate, or role.
* <pre>
* (?i) -- ignore case
* ((?<=\\ACREATE\\s{0,1024})(?:PROCEDURE|ROLE)|\\APARTITION|\\AREPLICATE\\AEXPORT) -- voltdb ddl
* [capture group 1]
* (?<=\\ACREATE\\s{1,1024})(?:PROCEDURE|ROLE) -- create procedure or role ddl
* (?<=\\ACREATE\\s{0,1024}) -- CREATE zero-width positive lookbehind
* \\A -- beginning of statement
* CREATE -- token
* \\s{1,1024} -- one or up to 1024 spaces
* (?:PROCEDURE|ROLE) -- procedure or role token
* | -- or
* \\A -- beginning of statement
* -- PARTITION token
* | -- or
* \\A -- beginning of statement
* REPLICATE -- token
* | -- or
* \\A -- beginning of statement
* EXPORT -- token
* \\s -- one space
* </pre>
*/
static final Pattern voltdbStatementPrefixPattern = Pattern.compile(
"(?i)((?<=\\ACREATE\\s{0,1024})(?:PROCEDURE|ROLE)|\\APARTITION|\\AREPLICATE|\\AEXPORT)\\s"
);
static final String TABLE = "TABLE";
static final String PROCEDURE = "PROCEDURE";
static final String PARTITION = "PARTITION";
static final String REPLICATE = "REPLICATE";
static final String EXPORT = "EXPORT";
static final String ROLE = "ROLE";
enum Permission {
adhoc,
sysproc,
defaultproc,
export;
static String toListString() {
return Arrays.asList(values()).toString();
}
}
HSQLInterface m_hsql;
VoltCompiler m_compiler;
String m_fullDDL = "";
int m_currLineNo = 1;
/// Partition descriptors parsed from DDL PARTITION or REPLICATE statements.
final VoltDDLElementTracker m_tracker;
HashMap<String, Column> columnMap = new HashMap<String, Column>();
HashMap<String, Index> indexMap = new HashMap<String, Index>();
HashMap<Table, String> matViewMap = new HashMap<Table, String>();
// Track the original CREATE TABLE statement for each table
// Currently used for catalog report generation.
// There's specifically no cleanup here because I don't think
// any is needed.
Map<String, String> m_tableNameToDDL = new TreeMap<String, String>();
private class DDLStatement {
public DDLStatement() {
}
String statement = "";
int lineNo;
}
public DDLCompiler(VoltCompiler compiler, HSQLInterface hsql, VoltDDLElementTracker tracker) {
assert(compiler != null);
assert(hsql != null);
assert(tracker != null);
this.m_hsql = hsql;
this.m_compiler = compiler;
this.m_tracker = tracker;
}
/**
* Compile a DDL schema from a file on disk
* @param path
* @param db
* @throws VoltCompiler.VoltCompilerException
*/
public void loadSchema(String path, Database db)
throws VoltCompiler.VoltCompilerException {
File inputFile = new File(path);
FileReader reader = null;
try {
reader = new FileReader(inputFile);
} catch (FileNotFoundException e) {
throw m_compiler.new VoltCompilerException("Unable to open schema file for reading");
}
m_currLineNo = 1;
loadSchema(path, db, reader);
}
/**
* Compile a file from an open input stream
* @param path
* @param db
* @param reader
* @throws VoltCompiler.VoltCompilerException
*/
private void loadSchema(String path, Database db, FileReader reader)
throws VoltCompiler.VoltCompilerException {
DDLStatement stmt = getNextStatement(reader, m_compiler);
while (stmt != null) {
// Some statements are processed by VoltDB and the rest are handled by HSQL.
boolean processed = false;
try {
processed = processVoltDBStatement(stmt.statement, db);
} catch (VoltCompilerException e) {
// Reformat the message thrown by VoltDB DDL processing to have a line number.
String msg = "VoltDB DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo;
throw m_compiler.new VoltCompilerException(msg);
}
if (!processed) {
try {
// Check for CREATE TABLE or CREATE VIEW.
// We sometimes choke at parsing statements with newlines, so
// check against a newline free version of the stmt.
String oneLinerStmt = stmt.statement.replace("\n", " ");
Matcher tableMatcher = createTablePattern.matcher(oneLinerStmt);
if (tableMatcher.find()) {
String tableName = tableMatcher.group(2);
m_tableNameToDDL.put(tableName.toUpperCase(), stmt.statement);
}
// kind of ugly. We hex-encode each statement so we can
// avoid embedded newlines so we can delimit statements
// with newline.
m_fullDDL += Encoder.hexEncode(stmt.statement) + "\n";
m_hsql.runDDLCommand(stmt.statement);
} catch (HSQLParseException e) {
String msg = "DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo;
throw m_compiler.new VoltCompilerException(msg, stmt.lineNo);
}
}
stmt = getNextStatement(reader, m_compiler);
}
try {
reader.close();
} catch (IOException e) {
throw m_compiler.new VoltCompilerException("Error closing schema file");
}
}
/**
* Checks whether or not the start of the given identifier is java (and
* thus DDL) compliant. An identifier may start with: _ [a-zA-Z] $
* @param identifier the identifier to check
* @param statement the statement where the identifier is
* @return the given identifier unmodified
* @throws VoltCompilerException when it is not compliant
*/
private String checkIdentifierStart(
final String identifier, final String statement
) throws VoltCompilerException {
assert identifier != null && ! identifier.trim().isEmpty();
assert statement != null && ! statement.trim().isEmpty();
int loc = 0;
do {
if( ! Character.isJavaIdentifierStart(identifier.charAt(loc))) {
String msg = "Unknown indentifier in DDL: \"" +
statement.substring(0,statement.length()-1) +
"\" contains invalid identifier \"" + identifier + "\"";
throw m_compiler.new VoltCompilerException(msg);
}
loc = identifier.indexOf('.', loc) + 1;
}
while( loc > 0 && loc < identifier.length());
return identifier;
}
/**
* Process a VoltDB-specific DDL statement, like PARTITION, REPLICATE,
* CREATE PROCEDURE, and CREATE ROLE.
* @param statement DDL statement string
* @param db
* @return true if statement was handled, otherwise it should be passed to HSQL
* @throws VoltCompilerException
*/
private boolean processVoltDBStatement(String statement, Database db) throws VoltCompilerException {
if (statement == null || statement.trim().isEmpty()) {
return false;
}
statement = statement.trim();
// matches if it is the beginning of a voltDB statement
Matcher statementMatcher = voltdbStatementPrefixPattern.matcher(statement);
if( ! statementMatcher.find()) {
return false;
}
// either PROCEDURE, REPLICATE, PARTITION, ROLE, or EXPORT
String commandPrefix = statementMatcher.group(1).toUpperCase();
// matches if it is CREATE PROCEDURE [ALLOW <role> ...] FROM CLASS <class-name>;
statementMatcher = procedureClassPattern.matcher(statement);
if( statementMatcher.matches()) {
String clazz = checkIdentifierStart(statementMatcher.group(2), statement);
ProcedureDescriptor descriptor = m_compiler.new ProcedureDescriptor(
new ArrayList<String>(), clazz);
// Add roles if specified.
if (statementMatcher.group(1) != null) {
for (String roleName : StringUtils.split(statementMatcher.group(1), ',')) {
// Don't put the same role in the list more than once.
String roleNameFixed = roleName.trim().toLowerCase();
if (!descriptor.m_authGroups.contains(roleNameFixed)) {
descriptor.m_authGroups.add(roleNameFixed);
}
}
}
// track the defined procedure
m_tracker.add(descriptor);
return true;
}
// matches if it is CREATE PROCEDURE <proc-name> [ALLOW <role> ...] AS <select-or-dml-statement>
statementMatcher = procedureSingleStatementPattern.matcher(statement);
if( statementMatcher.matches()) {
String clazz = checkIdentifierStart(statementMatcher.group(1), statement);
String sqlStatement = statementMatcher.group(3);
ProcedureDescriptor descriptor = m_compiler.new ProcedureDescriptor(
new ArrayList<String>(), clazz, sqlStatement, null, null, false);
// Add roles if specified.
if (statementMatcher.group(2) != null) {
for (String roleName : StringUtils.split(statementMatcher.group(2), ',')) {
descriptor.m_authGroups.add(roleName.trim().toLowerCase());
}
}
m_tracker.add(descriptor);
return true;
}
// matches if it is the beginning of a partition statement
statementMatcher = prePartitionPattern.matcher(statement);
if( statementMatcher.matches()) {
// either TABLE or PROCEDURE
String partitionee = statementMatcher.group(1).toUpperCase();
if( TABLE.equals(partitionee)) {
// matches if it is PARTITION TABLE <table> ON COLUMN <column>
statementMatcher = partitionTablePattern.matcher(statement);
if( ! statementMatcher.matches()) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: PARTITION TABLE <table> ON COLUMN <column>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// group(1) -> table, group(2) -> column
m_tracker.put(
checkIdentifierStart(statementMatcher.group(1),statement),
checkIdentifierStart(statementMatcher.group(2),statement)
);
return true;
}
else if( PROCEDURE.equals(partitionee)) {
// matches if it is
// PARTITION PROCEDURE <procedure>
// ON TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]
statementMatcher = partitionProcedurePattern.matcher(statement);
if( ! statementMatcher.matches()) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: PARTITION PROCEDURE <procedure> ON "+
"TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// check the table portion of the partition info
String tableName = checkIdentifierStart(statementMatcher.group(2), statement);
// check the column portion of the partition info
String columnName = checkIdentifierStart(statementMatcher.group(3), statement);
// if not specified default parameter index to 0
String parameterNo = statementMatcher.group(4);
if( parameterNo == null) {
parameterNo = "0";
}
String partitionInfo = String.format("%s.%s: %s", tableName, columnName, parameterNo);
// procedureName -> group(1), partitionInfo -> group(2)
m_tracker.addProcedurePartitionInfoTo(
checkIdentifierStart(statementMatcher.group(1), statement),
partitionInfo
);
return true;
}
// can't get here as regex only matches for PROCEDURE or TABLE
}
// matches if it is REPLICATE TABLE <table-name>
statementMatcher = replicatePattern.matcher(statement);
if( statementMatcher.matches()) {
// group(1) -> table
m_tracker.put(
checkIdentifierStart(statementMatcher.group(1), statement),
null
);
return true;
}
// matches if it is CREATE ROLE [WITH <permission> [, <permission> ...]]
// group 1 is role name
// group 2 is comma-separated permission list or null if there is no WITH clause
statementMatcher = createRolePattern.matcher(statement);
if( statementMatcher.matches()) {
String roleName = statementMatcher.group(1);
CatalogMap<Group> groupMap = db.getGroups();
if (groupMap.get(roleName) != null) {
throw m_compiler.new VoltCompilerException(String.format(
"Role name \"%s\" in CREATE ROLE statement already exists.",
roleName));
}
org.voltdb.catalog.Group catGroup = groupMap.add(roleName);
if (statementMatcher.group(2) != null) {
for (String tokenRaw : StringUtils.split(statementMatcher.group(2), ',')) {
String token = tokenRaw.trim().toLowerCase();
Permission permission;
try {
permission = Permission.valueOf(token);
}
catch (IllegalArgumentException iaex) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid permission \"%s\" in CREATE ROLE statement: \"%s\", " +
"available permissions: %s", token,
statement.substring(0,statement.length()-1), // remove trailing semicolon
Permission.toListString()));
}
switch( permission) {
case adhoc:
catGroup.setAdhoc(true);
break;
case sysproc:
catGroup.setSysproc(true);
break;
case defaultproc:
catGroup.setDefaultproc(true);
break;
case export:
m_compiler.grantExportToGroup(roleName, db);
break;
}
}
}
return true;
}
statementMatcher = exportPattern.matcher(statement);
if( statementMatcher.matches()) {
// check the table portion
String tableName = checkIdentifierStart(statementMatcher.group(1), statement);
m_tracker.addExportedTable(tableName);
return true;
}
/*
* if no correct syntax regex matched above then at this juncture
* the statement is syntax incorrect
*/
if( PARTITION.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: \"PARTITION TABLE <table> ON COLUMN <column>\" or " +
"\"PARTITION PROCEDURE <procedure> ON " +
"TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]\"",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( REPLICATE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid REPLICATE statement: \"%s\", " +
"expected syntax: REPLICATE TABLE <table>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( PROCEDURE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid CREATE PROCEDURE statement: \"%s\", " +
"expected syntax: \"CREATE PROCEDURE [ALLOW <role> [, <role> ...] FROM CLASS <class-name>\" " +
"or: \"CREATE PROCEDURE <name> [ALLOW <role> [, <role> ...] AS <single-select-or-dml-statement>\"",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( ROLE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid CREATE ROLE statement: \"%s\", " +
"expected syntax: CREATE ROLE <role>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( EXPORT.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid EXPORT TABLE statement: \"%s\", " +
"expected syntax: EXPORT TABLE <table>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// Not a VoltDB-specific DDL statement.
return false;
}
public void compileToCatalog(Database db) throws VoltCompilerException {
String hexDDL = Encoder.hexEncode(m_fullDDL);
db.getCatalog().execute("set " + db.getPath() + " schema \"" + hexDDL + "\"");
VoltXMLElement xmlCatalog;
try
{
xmlCatalog = m_hsql.getXMLFromCatalog();
}
catch (HSQLParseException e)
{
String msg = "DDL Error: " + e.getMessage();
throw m_compiler.new VoltCompilerException(msg);
}
// output the xml catalog to disk
BuildDirectoryUtils.writeFile("schema-xml", "hsql-catalog-output.xml", xmlCatalog.toString(), true);
// build the local catalog from the xml catalog
fillCatalogFromXML(db, xmlCatalog);
}
/**
* Read until the next newline
* @throws IOException
*/
String readToEndOfLine(FileReader reader) throws IOException {
LineNumberReader lnr = new LineNumberReader(reader);
String retval = lnr.readLine();
m_currLineNo++;
return retval;
}
// Parsing states. Start in kStateInvalid
private static int kStateInvalid = 0; // have not yet found start of statement
private static int kStateReading = 1; // normal reading state
private static int kStateReadingCommentDelim = 2; // dealing with first -
private static int kStateReadingComment = 3; // parsing after -- for a newline
private static int kStateReadingStringLiteralSpecialChar = 4; // dealing with one or more single quotes
private static int kStateReadingStringLiteral = 5; // in the middle of a string literal
private static int kStateCompleteStatement = 6; // found end of statement
private int readingState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '-') {
// remember that a possible '--' is being examined
return kStateReadingCommentDelim;
}
else if (nchar[0] == '\n') {
// normalize newlines to spaces
m_currLineNo += 1;
retval.statement += " ";
}
else if (nchar[0] == '\r') {
// ignore carriage returns
}
else if (nchar[0] == ';') {
// end of the statement
retval.statement += nchar[0];
return kStateCompleteStatement;
}
else if (nchar[0] == '\'') {
retval.statement += nchar[0];
return kStateReadingStringLiteral;
}
else {
// accumulate and continue
retval.statement += nchar[0];
}
return kStateReading;
}
private int readingStringLiteralState(char[] nchar, DDLStatement retval) {
// all characters in the literal are accumulated. keep track of
// newlines for error messages.
retval.statement += nchar[0];
if (nchar[0] == '\n') {
m_currLineNo += 1;
}
// if we see a SINGLE_QUOTE, change states to check for terminating literal
if (nchar[0] != '\'') {
return kStateReadingStringLiteral;
}
else {
return kStateReadingStringLiteralSpecialChar;
}
}
private int readingStringLiteralSpecialChar(char[] nchar, DDLStatement retval) {
// if this is an escaped quote, return kReadingStringLiteral.
// otherwise, the string is complete. Parse nchar as a non-literal
if (nchar[0] == '\'') {
retval.statement += nchar[0];
return kStateReadingStringLiteral;
}
else {
return readingState(nchar, retval);
}
}
private int readingCommentDelimState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '-') {
// confirmed that a comment is being read
return kStateReadingComment;
}
else {
// need to append the previously skipped '-' to the statement
// and process the current character
retval.statement += '-';
return readingState(nchar, retval);
}
}
private int readingCommentState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '\n') {
// a comment is continued until a newline is found.
m_currLineNo += 1;
return kStateReading;
}
return kStateReadingComment;
}
DDLStatement getNextStatement(FileReader reader, VoltCompiler compiler)
throws VoltCompiler.VoltCompilerException {
int state = kStateInvalid;
char[] nchar = new char[1];
@SuppressWarnings("synthetic-access")
DDLStatement retval = new DDLStatement();
retval.lineNo = m_currLineNo;
try {
// find the start of a statement and break out of the loop
// or return null if there is no next statement to be found
do {
if (reader.read(nchar) == -1) {
return null;
}
// trim leading whitespace outside of a statement
if (nchar[0] == '\n') {
m_currLineNo++;
}
else if (nchar[0] == '\r') {
}
else if (nchar[0] == ' ') {
}
// trim leading comments outside of a statement
else if (nchar[0] == '-') {
// The next character must be a comment because no valid
// statement will start with "-<foo>". If a comment was
// found, read until the next newline.
if (reader.read(nchar) == -1) {
// garbage at the end of a file but easy to tolerable?
return null;
}
if (nchar[0] != '-') {
String msg = "Invalid content before or between DDL statements.";
throw compiler.new VoltCompilerException(msg, m_currLineNo);
}
else {
do {
if (reader.read(nchar) == -1) {
// a comment extending to EOF means no statement
return null;
}
} while (nchar[0] != '\n');
// process the newline and loop
m_currLineNo++;
}
}
// not whitespace or comment: start of a statement.
else {
retval.statement += nchar[0];
state = kStateReading;
// Set the line number to the start of the real statement.
retval.lineNo = m_currLineNo;
break;
}
} while (true);
while (state != kStateCompleteStatement) {
if (reader.read(nchar) == -1) {
String msg = "Schema file ended mid-statement (no semicolon found).";
throw compiler.new VoltCompilerException(msg, retval.lineNo);
}
if (state == kStateReading) {
state = readingState(nchar, retval);
}
else if (state == kStateReadingCommentDelim) {
state = readingCommentDelimState(nchar, retval);
}
else if (state == kStateReadingComment) {
state = readingCommentState(nchar, retval);
}
else if (state == kStateReadingStringLiteral) {
state = readingStringLiteralState(nchar, retval);
}
else if (state == kStateReadingStringLiteralSpecialChar) {
state = readingStringLiteralSpecialChar(nchar, retval);
}
else {
throw compiler.new VoltCompilerException("Unrecoverable error parsing DDL.");
}
}
return retval;
}
catch (IOException e) {
throw compiler.new VoltCompilerException("Unable to read from file");
}
}
public void fillCatalogFromXML(Database db, VoltXMLElement xml)
throws VoltCompiler.VoltCompilerException {
if (xml == null)
throw m_compiler.new VoltCompilerException("Unable to parse catalog xml file from hsqldb");
assert xml.name.equals("databaseschema");
for (VoltXMLElement node : xml.children) {
if (node.name.equals("table"))
addTableToCatalog(db, node);
}
processMaterializedViews(db);
}
void addTableToCatalog(Database db, VoltXMLElement node) throws VoltCompilerException {
assert node.name.equals("table");
// clear these maps, as they're table specific
columnMap.clear();
indexMap.clear();
String name = node.attributes.get("name");
// create a table node in the catalog
Table table = db.getTables().add(name);
// add the original DDL to the table (or null if it's not there)
TableAnnotation annotation = new TableAnnotation();
table.setAnnotation(annotation);
annotation.ddl = m_tableNameToDDL.get(name.toUpperCase());
// handle the case where this is a materialized view
String query = node.attributes.get("query");
if (query != null) {
assert(query.length() > 0);
matViewMap.put(table, query);
}
// all tables start replicated
// if a partition is found in the project file later,
// then this is reversed
table.setIsreplicated(true);
// map of index replacements for later constraint fixup
Map<String, String> indexReplacementMap = new TreeMap<String, String>();
ArrayList<VoltType> columnTypes = new ArrayList<VoltType>();
for (VoltXMLElement subNode : node.children) {
if (subNode.name.equals("columns")) {
int colIndex = 0;
for (VoltXMLElement columnNode : subNode.children) {
if (columnNode.name.equals("column"))
addColumnToCatalog(table, columnNode, colIndex++, columnTypes);
}
// limit the total number of columns in a table
if (colIndex > MAX_COLUMNS) {
String msg = "Table " + name + " has " +
colIndex + " columns (max is " + MAX_COLUMNS + ")";
throw m_compiler.new VoltCompilerException(msg);
}
}
if (subNode.name.equals("indexes")) {
// do non-system indexes first so they get priority when the compiler
// starts throwing out duplicate indexes
for (VoltXMLElement indexNode : subNode.children) {
if (indexNode.name.equals("index") == false) continue;
String indexName = indexNode.attributes.get("name");
if (indexName.startsWith("SYS_IDX_SYS_") == false) {
addIndexToCatalog(db, table, indexNode, indexReplacementMap);
}
}
// now do system indexes
for (VoltXMLElement indexNode : subNode.children) {
if (indexNode.name.equals("index") == false) continue;
String indexName = indexNode.attributes.get("name");
if (indexName.startsWith("SYS_IDX_SYS_") == true) {
addIndexToCatalog(db, table, indexNode, indexReplacementMap);
}
}
}
if (subNode.name.equals("constraints")) {
for (VoltXMLElement constraintNode : subNode.children) {
if (constraintNode.name.equals("constraint"))
addConstraintToCatalog(table, constraintNode, indexReplacementMap);
}
}
}
table.setSignature(VoltTypeUtil.getSignatureForTable(name, columnTypes));
/*
* Validate that the total size
*/
int maxRowSize = 0;
for (Column c : columnMap.values()) {
VoltType t = VoltType.get((byte)c.getType());
if ((t == VoltType.STRING) || (t == VoltType.VARBINARY)) {
if (c.getSize() > VoltType.MAX_VALUE_LENGTH) {
throw m_compiler.new VoltCompilerException("Table name " + name + " column " + c.getName() +
" has a maximum size of " + c.getSize() + " bytes" +
" but the maximum supported size is " + VoltType.humanReadableSize(VoltType.MAX_VALUE_LENGTH));
}
maxRowSize += 4 + c.getSize();
} else {
maxRowSize += t.getLengthInBytesForFixedTypes();
}
}
if (maxRowSize > MAX_ROW_SIZE) {
throw m_compiler.new VoltCompilerException("Table name " + name + " has a maximum row size of " + maxRowSize +
" but the maximum supported row size is " + MAX_ROW_SIZE);
}
}
void addColumnToCatalog(Table table, VoltXMLElement node, int index, ArrayList<VoltType> columnTypes) throws VoltCompilerException {
assert node.name.equals("column");
String name = node.attributes.get("name");
String typename = node.attributes.get("valuetype");
String nullable = node.attributes.get("nullable");
String sizeString = node.attributes.get("size");
String defaultvalue = null;
String defaulttype = null;
// throws an exception if string isn't an int (i think)
Integer.parseInt(sizeString);
// Default Value
for (VoltXMLElement child : node.children) {
if (child.name.equals("default")) {
for (VoltXMLElement inner_child : child.children) {
// Value
if (inner_child.name.equals("value")) {
assert(defaulttype == null); // There should be only one default value/type.
defaultvalue = inner_child.attributes.get("value");
defaulttype = inner_child.attributes.get("valuetype");
assert(defaulttype != null);
}
}
}
}
if (defaultvalue != null && defaultvalue.equals("NULL"))
defaultvalue = null;
if (defaulttype != null) {
// fyi: Historically, VoltType class initialization errors get reported on this line (?).
defaulttype = Integer.toString(VoltType.typeFromString(defaulttype).getValue());
}
// replace newlines in default values
if (defaultvalue != null) {
defaultvalue = defaultvalue.replace('\n', ' ');
defaultvalue = defaultvalue.replace('\r', ' ');
}
// fyi: Historically, VoltType class initialization errors get reported on this line (?).
VoltType type = VoltType.typeFromString(typename);
columnTypes.add(type);
if (defaultvalue != null && (type == VoltType.DECIMAL || type == VoltType.NUMERIC))
{
// Until we support deserializing scientific notation in the EE, we'll
// coerce default values to plain notation here. See ENG-952 for more info.
BigDecimal temp = new BigDecimal(defaultvalue);
defaultvalue = temp.toPlainString();
}
Column column = table.getColumns().add(name);
// need to set other column data here (default, nullable, etc)
column.setName(name);
column.setIndex(index);
column.setType(type.getValue());
column.setNullable(nullable.toLowerCase().startsWith("t") ? true : false);
int size = type.getMaxLengthInBytes();
// Require a valid length if variable length is supported for a type
if (type == VoltType.STRING || type == VoltType.VARBINARY) {
size = Integer.parseInt(sizeString);
if ((size == 0) || (size > VoltType.MAX_VALUE_LENGTH)) {
String msg = type.toSQLString() + " column " + name + " in table " + table.getTypeName() + " has unsupported length " + sizeString;
throw m_compiler.new VoltCompilerException(msg);
}
}
column.setSize(size);
column.setDefaultvalue(defaultvalue);
if (defaulttype != null)
column.setDefaulttype(Integer.parseInt(defaulttype));
columnMap.put(name, column);
}
/**
* Return true if the two indexes are identical with a different name.
*/
boolean indexesAreDups(Index idx1, Index idx2) {
// same attributes?
if (idx1.getType() != idx2.getType()) {
return false;
}
if (idx1.getCountable() != idx2.getCountable()) {
return false;
}
if (idx1.getUnique() != idx2.getUnique()) {
return false;
}
// same column count?
if (idx1.getColumns().size() != idx2.getColumns().size()) {
return false;
}
//TODO: For index types like HASH that support only random access vs. scanned ranges, indexes on different
// permutations of the same list of columns/expressions could be considered dupes. This code skips that edge
// case optimization in favor of using a simpler more exact permutation-sensitive algorithm for all indexes.
if ( ! (idx1.getExpressionsjson().equals(idx2.getExpressionsjson()))) {
return false;
}
// Simple column indexes have identical empty expression strings so need to be distinguished other ways.
// More complex expression indexes that have the same expression strings always have the same set of (base)
// columns referenced in the same order, but we fall through and check them, anyway.
// sort in index order the columns of idx1, each identified by its index in the base table
int[] idx1baseTableOrder = new int[idx1.getColumns().size()];
for (ColumnRef cref : idx1.getColumns()) {
int index = cref.getIndex();
int baseTableIndex = cref.getColumn().getIndex();
idx1baseTableOrder[index] = baseTableIndex;
}
// sort in index order the columns of idx2, each identified by its index in the base table
int[] idx2baseTableOrder = new int[idx2.getColumns().size()];
for (ColumnRef cref : idx2.getColumns()) {
int index = cref.getIndex();
int baseTableIndex = cref.getColumn().getIndex();
idx2baseTableOrder[index] = baseTableIndex;
}
// Duplicate indexes have identical columns in identical order.
return Arrays.equals(idx1baseTableOrder, idx2baseTableOrder);
}
void addIndexToCatalog(Database db, Table table, VoltXMLElement node, Map<String, String> indexReplacementMap)
throws VoltCompilerException
{
assert node.name.equals("index");
String name = node.attributes.get("name");
boolean unique = Boolean.parseBoolean(node.attributes.get("unique"));
AbstractParsedStmt dummy = new ParsedSelectStmt(null, db);
dummy.setTable(table);
// "parse" the expression trees for an expression-based index (vs. a simple column value index)
AbstractExpression[] exprs = null;
for (VoltXMLElement subNode : node.children) {
if (subNode.name.equals("exprs")) {
exprs = new AbstractExpression[subNode.children.size()];
int j = 0;
for (VoltXMLElement exprNode : subNode.children) {
exprs[j] = dummy.parseExpressionTree(exprNode);
exprs[j].resolveForTable(table);
exprs[j].finalizeValueTypes();
++j;
}
}
}
String colList = node.attributes.get("columns");
String[] colNames = colList.split(",");
Column[] columns = new Column[colNames.length];
boolean has_nonint_col = false;
String nonint_col_name = null;
for (int i = 0; i < colNames.length; i++) {
columns[i] = columnMap.get(colNames[i]);
if (columns[i] == null) {
return;
}
}
if (exprs == null) {
for (int i = 0; i < colNames.length; i++) {
VoltType colType = VoltType.get((byte)columns[i].getType());
if (colType == VoltType.DECIMAL || colType == VoltType.FLOAT || colType == VoltType.STRING) {
has_nonint_col = true;
nonint_col_name = colNames[i];
}
// disallow columns from VARBINARYs
if (colType == VoltType.VARBINARY) {
String msg = "VARBINARY values are not currently supported as index keys: '" + colNames[i] + "'";
throw this.m_compiler.new VoltCompilerException(msg);
}
}
} else {
for (AbstractExpression expression : exprs) {
VoltType colType = expression.getValueType();
if (colType == VoltType.DECIMAL || colType == VoltType.FLOAT || colType == VoltType.STRING) {
has_nonint_col = true;
nonint_col_name = "<expression>";
}
// disallow expressions of type VARBINARY
if (colType == VoltType.VARBINARY) {
String msg = "VARBINARY expressions are not currently supported as index keys.";
throw this.m_compiler.new VoltCompilerException(msg);
}
}
}
Index index = table.getIndexes().add(name);
index.setCountable(false);
// set the type of the index based on the index name and column types
// Currently, only int types can use hash or array indexes
String indexNameNoCase = name.toLowerCase();
if (indexNameNoCase.contains("tree"))
{
index.setType(IndexType.BALANCED_TREE.getValue());
index.setCountable(true);
}
else if (indexNameNoCase.contains("hash"))
{
if (!has_nonint_col)
{
index.setType(IndexType.HASH_TABLE.getValue());
}
else
{
String msg = "Index " + name + " in table " + table.getTypeName() +
" uses a non-hashable column " + nonint_col_name;
throw m_compiler.new VoltCompilerException(msg);
}
} else {
index.setType(IndexType.BALANCED_TREE.getValue());
index.setCountable(true);
}
// Countable is always on right now. Fix it when VoltDB can pack memory for TreeNode.
// if (indexNameNoCase.contains("NoCounter")) {
// index.setType(IndexType.BALANCED_TREE.getValue());
// index.setCountable(false);
// }
// need to set other index data here (column, etc)
// For expression indexes, the columns listed in the catalog do not correspond to the values in the index,
// but they still represent the columns that will trigger an index update when their values change.
for (int i = 0; i < columns.length; i++) {
ColumnRef cref = index.getColumns().add(columns[i].getTypeName());
cref.setColumn(columns[i]);
cref.setIndex(i);
}
if (exprs != null) {
try {
index.setExpressionsjson(convertToJSONArray(exprs));
} catch (JSONException e) {
throw m_compiler.new VoltCompilerException("Unexpected error serializing non-column expressions for index '" +
name + "' on type '" + table.getTypeName() + "': " + e.toString());
}
}
index.setUnique(unique);
// check if an existing index duplicates another index (if so, drop it)
// note that this is an exact dup... uniqueness, counting-ness and type
// will make two indexes different
for (Index existingIndex : table.getIndexes()) {
// skip thineself
if (existingIndex == index) {
continue;
}
if (indexesAreDups(existingIndex, index)) {
// replace any constraints using one index with the other
//for () TODO
// get ready for replacements from constraints created later
indexReplacementMap.put(index.getTypeName(), existingIndex.getTypeName());
// if the index is a user-named index...
if (index.getTypeName().startsWith("SYS_IDX_") == false) {
// on dup-detection, add a warning but don't fail
String msg = String.format("Dropping index %s on table %s because it duplicates index %s.",
index.getTypeName(), table.getTypeName(), existingIndex.getTypeName());
m_compiler.addWarn(msg);
}
// drop the index and GTFO
table.getIndexes().delete(index.getTypeName());
return;
}
}
String msg = "Created index: " + name + " on table: " +
table.getTypeName() + " of type: " + IndexType.get(index.getType()).name();
m_compiler.addInfo(msg);
indexMap.put(name, index);
}
private static String convertToJSONArray(AbstractExpression[] exprs) throws JSONException {
JSONStringer stringer = new JSONStringer();
stringer.array();
for (AbstractExpression abstractExpression : exprs) {
stringer.object();
abstractExpression.toJSONString(stringer);
stringer.endObject();
}
stringer.endArray();
return stringer.toString();
}
/**
* Add a constraint on a given table to the catalog
* @param table
* @param node
* @throws VoltCompilerException
*/
void addConstraintToCatalog(Table table, VoltXMLElement node, Map<String, String> indexReplacementMap)
throws VoltCompilerException
{
assert node.name.equals("constraint");
String name = node.attributes.get("name");
String typeName = node.attributes.get("constrainttype");
ConstraintType type = ConstraintType.valueOf(typeName);
if (type == ConstraintType.CHECK) {
String msg = "VoltDB does not enforce check constraints. ";
msg += "Constraint on table " + table.getTypeName() + " will be ignored.";
m_compiler.addWarn(msg);
return;
}
else if (type == ConstraintType.FOREIGN_KEY) {
String msg = "VoltDB does not enforce foreign key references and constraints. ";
msg += "Constraint on table " + table.getTypeName() + " will be ignored.";
m_compiler.addWarn(msg);
return;
}
else if (type == ConstraintType.MAIN) {
// should never see these
assert(false);
}
else if (type == ConstraintType.NOT_NULL) {
// these get handled by table metadata inspection
return;
}
else if (type != ConstraintType.PRIMARY_KEY && type != ConstraintType.UNIQUE) {
throw m_compiler.new VoltCompilerException("Invalid constraint type '" + typeName + "'");
}
// else, create the unique index below
// primary key code is in other places as well
// The constraint is backed by an index, therefore we need to create it
// TODO: We need to be able to use indexes for foreign keys. I am purposely
// leaving those out right now because HSQLDB just makes too many of them.
Constraint catalog_const = table.getConstraints().add(name);
String indexName = node.attributes.get("index");
assert(indexName != null);
// handle replacements from duplicate index pruning
if (indexReplacementMap.containsKey(indexName)) {
indexName = indexReplacementMap.get(indexName);
}
Index catalog_index = indexMap.get(indexName);
if (catalog_index != null) {
// if the constraint name contains index type hints, exercise them (giant hack)
String constraintNameNoCase = name.toLowerCase();
if (constraintNameNoCase.contains("tree"))
catalog_index.setType(IndexType.BALANCED_TREE.getValue());
if (constraintNameNoCase.contains("hash"))
catalog_index.setType(IndexType.HASH_TABLE.getValue());
catalog_const.setIndex(catalog_index);
catalog_index.setUnique(true);
}
catalog_const.setType(type.getValue());
}
/**
* Add materialized view info to the catalog for the tables that are
* materialized views.
*/
void processMaterializedViews(Database db) throws VoltCompiler.VoltCompilerException {
for (Entry<Table, String> entry : matViewMap.entrySet()) {
Table destTable = entry.getKey();
String query = entry.getValue();
// get the xml for the query
VoltXMLElement xmlquery = null;
try {
xmlquery = m_hsql.getXMLCompiledStatement(query);
}
catch (HSQLParseException e) {
e.printStackTrace();
}
assert(xmlquery != null);
// parse the xml like any other sql statement
ParsedSelectStmt stmt = null;
try {
stmt = (ParsedSelectStmt) AbstractParsedStmt.parse(query, xmlquery, null, db, null);
}
catch (Exception e) {
throw m_compiler.new VoltCompilerException(e.getMessage());
}
assert(stmt != null);
// throw an error if the view isn't within voltdb's limited worldview
checkViewMeetsSpec(destTable.getTypeName(), stmt);
// create the materializedviewinfo catalog node for the source table
Table srcTable = stmt.tableList.get(0);
MaterializedViewInfo matviewinfo = srcTable.getViews().add(destTable.getTypeName());
matviewinfo.setDest(destTable);
AbstractExpression where = stmt.getCombinedFilterExpression();
if (where != null) {
String hex = Encoder.hexEncode(where.toJSONString());
matviewinfo.setPredicate(hex);
} else {
matviewinfo.setPredicate("");
}
destTable.setMaterializer(srcTable);
List<Column> srcColumnArray = CatalogUtil.getSortedCatalogItems(srcTable.getColumns(), "index");
List<Column> destColumnArray = CatalogUtil.getSortedCatalogItems(destTable.getColumns(), "index");
// add the group by columns from the src table
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i);
Column srcCol = srcColumnArray.get(gbcol.index);
ColumnRef cref = matviewinfo.getGroupbycols().add(srcCol.getTypeName());
// groupByColumns is iterating in order of groups. Store that grouping order
// in the column ref index. When the catalog is serialized, it will, naturally,
// scramble this order like a two year playing dominos, presenting the data
// in a meaningless sequence.
cref.setIndex(i); // the column offset in the view's grouping order
cref.setColumn(srcCol); // the source column from the base (non-view) table
}
ParsedSelectStmt.ParsedColInfo countCol = stmt.displayColumns.get(stmt.groupByColumns.size());
assert(countCol.expression.getExpressionType() == ExpressionType.AGGREGATE_COUNT_STAR);
assert(countCol.expression.getLeft() == null);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumnArray.get(stmt.groupByColumns.size()),
ExpressionType.AGGREGATE_COUNT_STAR, null);
// create an index and constraint for the table
Index pkIndex = destTable.getIndexes().add("MATVIEW_PK_INDEX");
pkIndex.setType(IndexType.BALANCED_TREE.getValue());
pkIndex.setUnique(true);
// add the group by columns from the src table
// assume index 1 throuh #grpByCols + 1 are the cols
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ColumnRef c = pkIndex.getColumns().add(String.valueOf(i));
c.setColumn(destColumnArray.get(i));
c.setIndex(i);
}
Constraint pkConstraint = destTable.getConstraints().add("MATVIEW_PK_CONSTRAINT");
pkConstraint.setType(ConstraintType.PRIMARY_KEY.getValue());
pkConstraint.setIndex(pkIndex);
// parse out the group by columns into the dest table
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i);
Column destColumn = destColumnArray.get(i);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn,
ExpressionType.VALUE_TUPLE, (TupleValueExpression)col.expression);
}
// parse out the aggregation columns into the dest table
for (int i = stmt.groupByColumns.size() + 1; i < stmt.displayColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i);
Column destColumn = destColumnArray.get(i);
AbstractExpression colExpr = col.expression.getLeft();
assert(colExpr.getExpressionType() == ExpressionType.VALUE_TUPLE);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn,
col.expression.getExpressionType(), (TupleValueExpression)colExpr);
// Correctly set the type of the column so that it's consistent.
// Otherwise HSQLDB might promote types differently than Volt.
destColumn.setType(col.expression.getValueType().getValue());
}
}
}
/**
* Verify the materialized view meets our arcane rules about what can and can't
* go in a materialized view. Throw hopefully helpful error messages when these
* rules are inevitably borked.
*
* @param viewName The name of the view being checked.
* @param stmt The output from the parser describing the select statement that creates the view.
* @throws VoltCompilerException
*/
private void checkViewMeetsSpec(String viewName, ParsedSelectStmt stmt) throws VoltCompilerException {
int groupColCount = stmt.groupByColumns.size();
int displayColCount = stmt.displayColumns.size();
String msg = "Materialized view \"" + viewName + "\" ";
if (stmt.tableList.size() != 1) {
msg += "has " + String.valueOf(stmt.tableList.size()) + " sources. " +
"Only one source view or source table is allowed.";
throw m_compiler.new VoltCompilerException(msg);
}
if (displayColCount <= groupColCount) {
msg += "has too few columns.";
throw m_compiler.new VoltCompilerException(msg);
}
if (stmt.hasComplexGroupby()) {
msg += "contains an expression involving a group by. " +
"Expressions with group by are not currently supported in views.";
throw m_compiler.new VoltCompilerException(msg);
}
if (stmt.hasComplexAgg()) {
msg += "contains an expression involving an aggregate function. " +
"Expressions with aggregate functions are not currently supported in views.";
throw m_compiler.new VoltCompilerException(msg);
}
int i;
for (i = 0; i < groupColCount; i++) {
ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i);
ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i);
if (outcol.expression.getExpressionType() != ExpressionType.VALUE_TUPLE) {
msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias;
throw m_compiler.new VoltCompilerException(msg);
}
TupleValueExpression expr = (TupleValueExpression) outcol.expression;
if (expr.getColumnIndex() != gbcol.index) {
msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias;
throw m_compiler.new VoltCompilerException(msg);
}
}
AbstractExpression coli = stmt.displayColumns.get(i).expression;
if (coli.getExpressionType() != ExpressionType.AGGREGATE_COUNT_STAR) {
msg += "is missing count(*) as the column after the group by columns, a materialized view requirement.";
throw m_compiler.new VoltCompilerException(msg);
}
for (i++; i < displayColCount; i++) {
ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i);
if ((outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_COUNT) &&
(outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_SUM)) {
msg += "must have non-group by columns aggregated by sum or count.";
throw m_compiler.new VoltCompilerException(msg);
}
if (outcol.expression.getLeft().getExpressionType() != ExpressionType.VALUE_TUPLE) {
msg += "must have non-group by columns use only one level of aggregation.";
throw m_compiler.new VoltCompilerException(msg);
}
}
}
void processMaterializedViewColumn(MaterializedViewInfo info, Table srcTable, Table destTable,
Column destColumn, ExpressionType type, TupleValueExpression colExpr)
throws VoltCompiler.VoltCompilerException {
if (colExpr != null) {
assert(colExpr.getTableName().equalsIgnoreCase(srcTable.getTypeName()));
String srcColName = colExpr.getColumnName();
Column srcColumn = srcTable.getColumns().getIgnoreCase(srcColName);
destColumn.setMatviewsource(srcColumn);
}
destColumn.setMatview(info);
destColumn.setAggregatetype(type.getValue());
}
}
|
src/frontend/org/voltdb/compiler/DDLCompiler.java
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.compiler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.hsqldb_voltpatches.HSQLInterface;
import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException;
import org.hsqldb_voltpatches.VoltXMLElement;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONStringer;
import org.voltdb.VoltType;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Group;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.MaterializedViewInfo;
import org.voltdb.catalog.Table;
import org.voltdb.compiler.VoltCompiler.ProcedureDescriptor;
import org.voltdb.compiler.VoltCompiler.VoltCompilerException;
import org.voltdb.compilereport.TableAnnotation;
import org.voltdb.expressions.AbstractExpression;
import org.voltdb.expressions.TupleValueExpression;
import org.voltdb.planner.AbstractParsedStmt;
import org.voltdb.planner.ParsedSelectStmt;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.ExpressionType;
import org.voltdb.types.IndexType;
import org.voltdb.utils.BuildDirectoryUtils;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.VoltTypeUtil;
/**
* Compiles schema (SQL DDL) text files and stores the results in a given catalog.
*
*/
public class DDLCompiler {
static final int MAX_COLUMNS = 1024;
static final int MAX_ROW_SIZE = 1024 * 1024 * 2;
/**
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ one or more spaces
* (PROCEDURE|TABLE) -- either PROCEDURE or TABLE token
* \\s+ -- one or more spaces
* .+ -- one or more of any characters
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern prePartitionPattern = Pattern.compile(
"(?i)\\APARTITION\\s+(PROCEDURE|TABLE)\\s+.+;\\z"
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [table name capture group 1]
* [\\w$]+ -- 1 or more identifier character
* (letters, numbers, dollar sign ($) underscore (_))
* \\s+ -- one or more spaces
* ON -- token
* \\s+ -- one or more spaces
* COLUMN -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [column name capture group 2]
* [\\w$]+ -- 1 or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s* -- 0 or more spaces
* ; a -- semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern partitionTablePattern = Pattern.compile(
"(?i)\\APARTITION\\s+TABLE\\s+([\\w$]+)\\s+ON\\s+COLUMN\\s+([\\w$]+)\\s*;\\z"
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* PARTITION -- token
* \\s+ -- one or more spaces
* PROCEDURE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [procedure name capture group 1]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s+ -- one or more spaces
* ON -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [table name capture group 2]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* \\s+ -- one or more spaces
* COLUMN -- token
* \\s+ -- one or more spaces
* ([\\w$]+) -- [column name capture group 3]
* [\\w$]+ -- one or more identifier character
* (letters, numbers, dollar sign ($) or underscore (_))
* (?:\\s+PARAMETER\\s+(\\d+))? 0 or 1 parameter clause [non-capturing]
* \\s+ -- one or more spaces
* PARAMETER -- token
* \\s+ -- one or more spaces
* \\d+ -- one ore more number digits [parameter index capture group 4]
* \\s* -- 0 or more spaces
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern partitionProcedurePattern = Pattern.compile(
"(?i)\\APARTITION\\s+PROCEDURE\\s+([\\w$]+)\\s+ON\\s+TABLE\\s+" +
"([\\w$]+)\\s+COLUMN\\s+([\\w$]+)(?:\\s+PARAMETER\\s+(\\d+))?\\s*;\\z"
);
/**
* CREATE PROCEDURE from Java class statement regex
* NB supports only unquoted table and column names
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern procedureClassPattern = Pattern.compile(
"(?i)" + // ignore case
"\\A" + // beginning of statement
"CREATE" + // CREATE token
"\\s+" + // one or more spaces
"PROCEDURE" + // PROCEDURE token
"(?:" + // begin optional ALLOW clause
"\\s+" + // one or more spaces
"ALLOW" + // ALLOW token
"\\s+" + // one or more spaces
"([\\w.$]+(?:\\s*,\\s*[\\w.$]+)*)" + // (1) comma-separated role list
")?" + // end optional ALLOW clause
"\\s+" + // one or more spaces
"FROM" + // FROM token
"\\s+" + // one or more spaces
"CLASS" + // CLASS token
"\\s+" + // one or more spaces
"([\\w$.]+)" + // (2) class name
"\\s*" + // zero or more spaces
";" + // semi-colon terminator
"\\z" // end of statement
);
/**
* CREATE PROCEDURE with single SELECT or DML statement regex
* NB supports only unquoted table and column names
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern procedureSingleStatementPattern = Pattern.compile(
"(?i)" + // ignore case
"\\A" + // beginning of DDL statement
"CREATE" + // CREATE token
"\\s+" + // one or more spaces
"PROCEDURE" + // PROCEDURE token
"\\s+" + // one or more spaces
"([\\w.$]+)" + // (1) procedure name
"(?:" + // begin optional ALLOW clause
"\\s+" + // one or more spaces
"ALLOW" + // ALLOW token
"\\s+" + // one or more spaces
"([\\w.$]+(?:\\s*,\\s*[\\w.$]+)*)" + // (2) comma-separated role list
")?" + // end optional ALLOW clause
"\\s+" + // one or more spaces
"AS" + // AS token
"\\s+" + // one or more spaces
"(" + // (3) begin SELECT or DML statement
"(?:SELECT|INSERT|UPDATE|DELETE)" + // valid DML start tokens (not captured)
"\\s+" + // one or more spaces
".+)" + // end SELECT or DML statement
";" + // semi-colon terminator
"\\z" // end of DDL statement
);
/**
* Regex to parse the CREATE ROLE statement with optional WITH clause.
* Leave the WITH clause argument as a single group because regexes
* aren't capable of producing a variable number of groups.
* Capture groups are tagged as (1) and (2) in comments below.
*/
static final Pattern createRolePattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // (start statement)
"CREATE\\s+ROLE\\s+" + // CREATE ROLE
"([\\w.$]+)" + // (1) <role name>
"(?:\\s+WITH\\s+" + // (start optional WITH clause block)
"(\\w+(?:\\s*,\\s*\\w+)*)" + // (2) <comma-separated argument string>
")?" + // (end optional WITH clause block)
";\\z" // (end statement)
);
/**
* Regex to match CREATE TABLE or CREATE VIEW statements.
* Unlike the other matchers, this is just designed to pull out the
* name of the table or view, not the whole statement.
* It's used to preserve as-entered schema for each table/view
* for the catalog report generator for the moment.
* Capture group (1) is ignored, but (2) is used.
*/
static final Pattern createTablePattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // (start statement)
"CREATE\\s+(TABLE|VIEW)\\s+" + // (1) CREATE TABLE
"([\\w.$]+)" // (2) <table name>
);
/**
* NB supports only unquoted table and column names
*
* Regex Description:
* <pre>
* (?i) -- ignore case
* \\A -- beginning of statement
* REPLICATE -- token
* \\s+ -- one or more spaces
* TABLE -- token
* \\s+ -- one or more spaces
* ([\\w$.]+) -- [table name capture group 1]
* [\\w$]+ -- one or more identifier character (letters, numbers, dollar sign ($) or underscore (_))
* \\s* -- 0 or more spaces
* ; -- a semicolon
* \\z -- end of string
* </pre>
*/
static final Pattern replicatePattern = Pattern.compile(
"(?i)\\AREPLICATE\\s+TABLE\\s+([\\w$]+)\\s*;\\z"
);
/**
* EXPORT TABLE statement regex
* NB supports only unquoted table names
* Capture groups are tagged as (1) in comments below.
*/
static final Pattern exportPattern = Pattern.compile(
"(?i)" + // (ignore case)
"\\A" + // start statement
"EXPORT\\s+TABLE\\s+" + // EXPORT TABLE
"([\\w.$]+)" + // (1) <table name>
"\\s*;\\z" // (end statement)
);
/**
* Regex Description:
*
* if the statement starts with either create procedure, partition,
* replicate, or role the first match group is set to respectively procedure,
* partition, replicate, or role.
* <pre>
* (?i) -- ignore case
* ((?<=\\ACREATE\\s{0,1024})(?:PROCEDURE|ROLE)|\\APARTITION|\\AREPLICATE\\AEXPORT) -- voltdb ddl
* [capture group 1]
* (?<=\\ACREATE\\s{1,1024})(?:PROCEDURE|ROLE) -- create procedure or role ddl
* (?<=\\ACREATE\\s{0,1024}) -- CREATE zero-width positive lookbehind
* \\A -- beginning of statement
* CREATE -- token
* \\s{1,1024} -- one or up to 1024 spaces
* (?:PROCEDURE|ROLE) -- procedure or role token
* | -- or
* \\A -- beginning of statement
* -- PARTITION token
* | -- or
* \\A -- beginning of statement
* REPLICATE -- token
* | -- or
* \\A -- beginning of statement
* EXPORT -- token
* \\s -- one space
* </pre>
*/
static final Pattern voltdbStatementPrefixPattern = Pattern.compile(
"(?i)((?<=\\ACREATE\\s{0,1024})(?:PROCEDURE|ROLE)|\\APARTITION|\\AREPLICATE|\\AEXPORT)\\s"
);
static final String TABLE = "TABLE";
static final String PROCEDURE = "PROCEDURE";
static final String PARTITION = "PARTITION";
static final String REPLICATE = "REPLICATE";
static final String EXPORT = "EXPORT";
static final String ROLE = "ROLE";
enum Permission {
adhoc,
sysproc,
defaultproc,
export;
static String toListString() {
return Arrays.asList(values()).toString();
}
}
HSQLInterface m_hsql;
VoltCompiler m_compiler;
String m_fullDDL = "";
int m_currLineNo = 1;
/// Partition descriptors parsed from DDL PARTITION or REPLICATE statements.
final VoltDDLElementTracker m_tracker;
HashMap<String, Column> columnMap = new HashMap<String, Column>();
HashMap<String, Index> indexMap = new HashMap<String, Index>();
HashMap<Table, String> matViewMap = new HashMap<Table, String>();
// Track the original CREATE TABLE statement for each table
// Currently used for catalog report generation.
// There's specifically no cleanup here because I don't think
// any is needed.
Map<String, String> m_tableNameToDDL = new TreeMap<String, String>();
private class DDLStatement {
public DDLStatement() {
}
String statement = "";
int lineNo;
}
public DDLCompiler(VoltCompiler compiler, HSQLInterface hsql, VoltDDLElementTracker tracker) {
assert(compiler != null);
assert(hsql != null);
assert(tracker != null);
this.m_hsql = hsql;
this.m_compiler = compiler;
this.m_tracker = tracker;
}
/**
* Compile a DDL schema from a file on disk
* @param path
* @param db
* @throws VoltCompiler.VoltCompilerException
*/
public void loadSchema(String path, Database db)
throws VoltCompiler.VoltCompilerException {
File inputFile = new File(path);
FileReader reader = null;
try {
reader = new FileReader(inputFile);
} catch (FileNotFoundException e) {
throw m_compiler.new VoltCompilerException("Unable to open schema file for reading");
}
m_currLineNo = 1;
loadSchema(path, db, reader);
}
/**
* Compile a file from an open input stream
* @param path
* @param db
* @param reader
* @throws VoltCompiler.VoltCompilerException
*/
private void loadSchema(String path, Database db, FileReader reader)
throws VoltCompiler.VoltCompilerException {
DDLStatement stmt = getNextStatement(reader, m_compiler);
while (stmt != null) {
// Some statements are processed by VoltDB and the rest are handled by HSQL.
boolean processed = false;
try {
processed = processVoltDBStatement(stmt.statement, db);
} catch (VoltCompilerException e) {
// Reformat the message thrown by VoltDB DDL processing to have a line number.
String msg = "VoltDB DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo;
throw m_compiler.new VoltCompilerException(msg);
}
if (!processed) {
try {
// Check for CREATE TABLE or CREATE VIEW.
// We sometimes choke at parsing statements with newlines, so
// check against a newline free version of the stmt.
String oneLinerStmt = stmt.statement.replace("\n", " ");
Matcher tableMatcher = createTablePattern.matcher(oneLinerStmt);
if (tableMatcher.find()) {
String tableName = tableMatcher.group(2);
m_tableNameToDDL.put(tableName.toUpperCase(), stmt.statement);
}
// kind of ugly. We hex-encode each statement so we can
// avoid embedded newlines so we can delimit statements
// with newline.
m_fullDDL += Encoder.hexEncode(stmt.statement) + "\n";
m_hsql.runDDLCommand(stmt.statement);
} catch (HSQLParseException e) {
String msg = "DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo;
throw m_compiler.new VoltCompilerException(msg, stmt.lineNo);
}
}
stmt = getNextStatement(reader, m_compiler);
}
try {
reader.close();
} catch (IOException e) {
throw m_compiler.new VoltCompilerException("Error closing schema file");
}
}
/**
* Checks whether or not the start of the given identifier is java (and
* thus DDL) compliant. An identifier may start with: _ [a-zA-Z] $
* @param identifier the identifier to check
* @param statement the statement where the identifier is
* @return the given identifier unmodified
* @throws VoltCompilerException when it is not compliant
*/
private String checkIdentifierStart(
final String identifier, final String statement
) throws VoltCompilerException {
assert identifier != null && ! identifier.trim().isEmpty();
assert statement != null && ! statement.trim().isEmpty();
int loc = 0;
do {
if( ! Character.isJavaIdentifierStart(identifier.charAt(loc))) {
String msg = "Unknown indentifier in DDL: \"" +
statement.substring(0,statement.length()-1) +
"\" contains invalid identifier \"" + identifier + "\"";
throw m_compiler.new VoltCompilerException(msg);
}
loc = identifier.indexOf('.', loc) + 1;
}
while( loc > 0 && loc < identifier.length());
return identifier;
}
/**
* Process a VoltDB-specific DDL statement, like PARTITION, REPLICATE,
* CREATE PROCEDURE, and CREATE ROLE.
* @param statement DDL statement string
* @param db
* @return true if statement was handled, otherwise it should be passed to HSQL
* @throws VoltCompilerException
*/
private boolean processVoltDBStatement(String statement, Database db) throws VoltCompilerException {
if (statement == null || statement.trim().isEmpty()) {
return false;
}
statement = statement.trim();
// matches if it is the beginning of a voltDB statement
Matcher statementMatcher = voltdbStatementPrefixPattern.matcher(statement);
if( ! statementMatcher.find()) {
return false;
}
// either PROCEDURE, REPLICATE, PARTITION, ROLE, or EXPORT
String commandPrefix = statementMatcher.group(1).toUpperCase();
// matches if it is CREATE PROCEDURE [ALLOW <role> ...] FROM CLASS <class-name>;
statementMatcher = procedureClassPattern.matcher(statement);
if( statementMatcher.matches()) {
String clazz = checkIdentifierStart(statementMatcher.group(2), statement);
ProcedureDescriptor descriptor = m_compiler.new ProcedureDescriptor(
new ArrayList<String>(), clazz);
// Add roles if specified.
if (statementMatcher.group(1) != null) {
for (String roleName : StringUtils.split(statementMatcher.group(1), ',')) {
// Don't put the same role in the list more than once.
String roleNameFixed = roleName.trim().toLowerCase();
if (!descriptor.m_authGroups.contains(roleNameFixed)) {
descriptor.m_authGroups.add(roleNameFixed);
}
}
}
// track the defined procedure
m_tracker.add(descriptor);
return true;
}
// matches if it is CREATE PROCEDURE <proc-name> [ALLOW <role> ...] AS <select-or-dml-statement>
statementMatcher = procedureSingleStatementPattern.matcher(statement);
if( statementMatcher.matches()) {
String clazz = checkIdentifierStart(statementMatcher.group(1), statement);
String sqlStatement = statementMatcher.group(3);
ProcedureDescriptor descriptor = m_compiler.new ProcedureDescriptor(
new ArrayList<String>(), clazz, sqlStatement, null, null, false);
// Add roles if specified.
if (statementMatcher.group(2) != null) {
for (String roleName : StringUtils.split(statementMatcher.group(2), ',')) {
descriptor.m_authGroups.add(roleName.trim().toLowerCase());
}
}
m_tracker.add(descriptor);
return true;
}
// matches if it is the beginning of a partition statement
statementMatcher = prePartitionPattern.matcher(statement);
if( statementMatcher.matches()) {
// either TABLE or PROCEDURE
String partitionee = statementMatcher.group(1).toUpperCase();
if( TABLE.equals(partitionee)) {
// matches if it is PARTITION TABLE <table> ON COLUMN <column>
statementMatcher = partitionTablePattern.matcher(statement);
if( ! statementMatcher.matches()) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: PARTITION TABLE <table> ON COLUMN <column>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// group(1) -> table, group(2) -> column
m_tracker.put(
checkIdentifierStart(statementMatcher.group(1),statement),
checkIdentifierStart(statementMatcher.group(2),statement)
);
return true;
}
else if( PROCEDURE.equals(partitionee)) {
// matches if it is
// PARTITION PROCEDURE <procedure>
// ON TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]
statementMatcher = partitionProcedurePattern.matcher(statement);
if( ! statementMatcher.matches()) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: PARTITION PROCEDURE <procedure> ON "+
"TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// check the table portion of the partition info
String tableName = checkIdentifierStart(statementMatcher.group(2), statement);
// check the column portion of the partition info
String columnName = checkIdentifierStart(statementMatcher.group(3), statement);
// if not specified default parameter index to 0
String parameterNo = statementMatcher.group(4);
if( parameterNo == null) {
parameterNo = "0";
}
String partitionInfo = String.format("%s.%s: %s", tableName, columnName, parameterNo);
// procedureName -> group(1), partitionInfo -> group(2)
m_tracker.addProcedurePartitionInfoTo(
checkIdentifierStart(statementMatcher.group(1), statement),
partitionInfo
);
return true;
}
// can't get here as regex only matches for PROCEDURE or TABLE
}
// matches if it is REPLICATE TABLE <table-name>
statementMatcher = replicatePattern.matcher(statement);
if( statementMatcher.matches()) {
// group(1) -> table
m_tracker.put(
checkIdentifierStart(statementMatcher.group(1), statement),
null
);
return true;
}
// matches if it is CREATE ROLE [WITH <permission> [, <permission> ...]]
// group 1 is role name
// group 2 is comma-separated permission list or null if there is no WITH clause
statementMatcher = createRolePattern.matcher(statement);
if( statementMatcher.matches()) {
String roleName = statementMatcher.group(1);
CatalogMap<Group> groupMap = db.getGroups();
if (groupMap.get(roleName) != null) {
throw m_compiler.new VoltCompilerException(String.format(
"Role name \"%s\" in CREATE ROLE statement already exists.",
roleName));
}
org.voltdb.catalog.Group catGroup = groupMap.add(roleName);
if (statementMatcher.group(2) != null) {
for (String tokenRaw : StringUtils.split(statementMatcher.group(2), ',')) {
String token = tokenRaw.trim().toLowerCase();
Permission permission;
try {
permission = Permission.valueOf(token);
}
catch (IllegalArgumentException iaex) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid permission \"%s\" in CREATE ROLE statement: \"%s\", " +
"available permissions: %s", token,
statement.substring(0,statement.length()-1), // remove trailing semicolon
Permission.toListString()));
}
switch( permission) {
case adhoc:
catGroup.setAdhoc(true);
break;
case sysproc:
catGroup.setSysproc(true);
break;
case defaultproc:
catGroup.setDefaultproc(true);
break;
case export:
m_compiler.grantExportToGroup(roleName, db);
break;
}
}
}
return true;
}
statementMatcher = exportPattern.matcher(statement);
if( statementMatcher.matches()) {
// check the table portion
String tableName = checkIdentifierStart(statementMatcher.group(1), statement);
m_tracker.addExportedTable(tableName);
return true;
}
/*
* if no correct syntax regex matched above then at this juncture
* the statement is syntax incorrect
*/
if( PARTITION.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid PARTITION statement: \"%s\", " +
"expected syntax: \"PARTITION TABLE <table> ON COLUMN <column>\" or " +
"\"PARTITION PROCEDURE <procedure> ON " +
"TABLE <table> COLUMN <column> [PARAMETER <parameter-index-no>]\"",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( REPLICATE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid REPLICATE statement: \"%s\", " +
"expected syntax: REPLICATE TABLE <table>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( PROCEDURE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid CREATE PROCEDURE statement: \"%s\", " +
"expected syntax: \"CREATE PROCEDURE [ALLOW <role> [, <role> ...] FROM CLASS <class-name>\" " +
"or: \"CREATE PROCEDURE <name> [ALLOW <role> [, <role> ...] AS <single-select-or-dml-statement>\"",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( ROLE.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid CREATE ROLE statement: \"%s\", " +
"expected syntax: CREATE ROLE <role>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
if( EXPORT.equals(commandPrefix)) {
throw m_compiler.new VoltCompilerException(String.format(
"Invalid EXPORT TABLE statement: \"%s\", " +
"expected syntax: EXPORT TABLE <table>",
statement.substring(0,statement.length()-1))); // remove trailing semicolon
}
// Not a VoltDB-specific DDL statement.
return false;
}
public void compileToCatalog(Database db) throws VoltCompilerException {
String hexDDL = Encoder.hexEncode(m_fullDDL);
db.getCatalog().execute("set " + db.getPath() + " schema \"" + hexDDL + "\"");
VoltXMLElement xmlCatalog;
try
{
xmlCatalog = m_hsql.getXMLFromCatalog();
}
catch (HSQLParseException e)
{
String msg = "DDL Error: " + e.getMessage();
throw m_compiler.new VoltCompilerException(msg);
}
// output the xml catalog to disk
BuildDirectoryUtils.writeFile("schema-xml", "hsql-catalog-output.xml", xmlCatalog.toString(), true);
// build the local catalog from the xml catalog
fillCatalogFromXML(db, xmlCatalog);
}
/**
* Read until the next newline
* @throws IOException
*/
String readToEndOfLine(FileReader reader) throws IOException {
LineNumberReader lnr = new LineNumberReader(reader);
String retval = lnr.readLine();
m_currLineNo++;
return retval;
}
// Parsing states. Start in kStateInvalid
private static int kStateInvalid = 0; // have not yet found start of statement
private static int kStateReading = 1; // normal reading state
private static int kStateReadingCommentDelim = 2; // dealing with first -
private static int kStateReadingComment = 3; // parsing after -- for a newline
private static int kStateReadingStringLiteralSpecialChar = 4; // dealing with one or more single quotes
private static int kStateReadingStringLiteral = 5; // in the middle of a string literal
private static int kStateCompleteStatement = 6; // found end of statement
private int readingState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '-') {
// remember that a possible '--' is being examined
return kStateReadingCommentDelim;
}
else if (nchar[0] == '\n') {
// normalize newlines to spaces
m_currLineNo += 1;
retval.statement += "\n";
}
else if (nchar[0] == '\r') {
// ignore carriage returns
}
else if (nchar[0] == ';') {
// end of the statement
retval.statement += nchar[0];
return kStateCompleteStatement;
}
else if (nchar[0] == '\'') {
retval.statement += nchar[0];
return kStateReadingStringLiteral;
}
else {
// accumulate and continue
retval.statement += nchar[0];
}
return kStateReading;
}
private int readingStringLiteralState(char[] nchar, DDLStatement retval) {
// all characters in the literal are accumulated. keep track of
// newlines for error messages.
retval.statement += nchar[0];
if (nchar[0] == '\n') {
m_currLineNo += 1;
}
// if we see a SINGLE_QUOTE, change states to check for terminating literal
if (nchar[0] != '\'') {
return kStateReadingStringLiteral;
}
else {
return kStateReadingStringLiteralSpecialChar;
}
}
private int readingStringLiteralSpecialChar(char[] nchar, DDLStatement retval) {
// if this is an escaped quote, return kReadingStringLiteral.
// otherwise, the string is complete. Parse nchar as a non-literal
if (nchar[0] == '\'') {
retval.statement += nchar[0];
return kStateReadingStringLiteral;
}
else {
return readingState(nchar, retval);
}
}
private int readingCommentDelimState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '-') {
// confirmed that a comment is being read
return kStateReadingComment;
}
else {
// need to append the previously skipped '-' to the statement
// and process the current character
retval.statement += '-';
return readingState(nchar, retval);
}
}
private int readingCommentState(char[] nchar, DDLStatement retval) {
if (nchar[0] == '\n') {
// a comment is continued until a newline is found.
m_currLineNo += 1;
return kStateReading;
}
return kStateReadingComment;
}
DDLStatement getNextStatement(FileReader reader, VoltCompiler compiler)
throws VoltCompiler.VoltCompilerException {
int state = kStateInvalid;
char[] nchar = new char[1];
@SuppressWarnings("synthetic-access")
DDLStatement retval = new DDLStatement();
retval.lineNo = m_currLineNo;
try {
// find the start of a statement and break out of the loop
// or return null if there is no next statement to be found
do {
if (reader.read(nchar) == -1) {
return null;
}
// trim leading whitespace outside of a statement
if (nchar[0] == '\n') {
m_currLineNo++;
}
else if (nchar[0] == '\r') {
}
else if (nchar[0] == ' ') {
}
// trim leading comments outside of a statement
else if (nchar[0] == '-') {
// The next character must be a comment because no valid
// statement will start with "-<foo>". If a comment was
// found, read until the next newline.
if (reader.read(nchar) == -1) {
// garbage at the end of a file but easy to tolerable?
return null;
}
if (nchar[0] != '-') {
String msg = "Invalid content before or between DDL statements.";
throw compiler.new VoltCompilerException(msg, m_currLineNo);
}
else {
do {
if (reader.read(nchar) == -1) {
// a comment extending to EOF means no statement
return null;
}
} while (nchar[0] != '\n');
// process the newline and loop
m_currLineNo++;
}
}
// not whitespace or comment: start of a statement.
else {
retval.statement += nchar[0];
state = kStateReading;
// Set the line number to the start of the real statement.
retval.lineNo = m_currLineNo;
break;
}
} while (true);
while (state != kStateCompleteStatement) {
if (reader.read(nchar) == -1) {
String msg = "Schema file ended mid-statement (no semicolon found).";
throw compiler.new VoltCompilerException(msg, retval.lineNo);
}
if (state == kStateReading) {
state = readingState(nchar, retval);
}
else if (state == kStateReadingCommentDelim) {
state = readingCommentDelimState(nchar, retval);
}
else if (state == kStateReadingComment) {
state = readingCommentState(nchar, retval);
}
else if (state == kStateReadingStringLiteral) {
state = readingStringLiteralState(nchar, retval);
}
else if (state == kStateReadingStringLiteralSpecialChar) {
state = readingStringLiteralSpecialChar(nchar, retval);
}
else {
throw compiler.new VoltCompilerException("Unrecoverable error parsing DDL.");
}
}
return retval;
}
catch (IOException e) {
throw compiler.new VoltCompilerException("Unable to read from file");
}
}
public void fillCatalogFromXML(Database db, VoltXMLElement xml)
throws VoltCompiler.VoltCompilerException {
if (xml == null)
throw m_compiler.new VoltCompilerException("Unable to parse catalog xml file from hsqldb");
assert xml.name.equals("databaseschema");
for (VoltXMLElement node : xml.children) {
if (node.name.equals("table"))
addTableToCatalog(db, node);
}
processMaterializedViews(db);
}
void addTableToCatalog(Database db, VoltXMLElement node) throws VoltCompilerException {
assert node.name.equals("table");
// clear these maps, as they're table specific
columnMap.clear();
indexMap.clear();
String name = node.attributes.get("name");
// create a table node in the catalog
Table table = db.getTables().add(name);
// add the original DDL to the table (or null if it's not there)
TableAnnotation annotation = new TableAnnotation();
table.setAnnotation(annotation);
annotation.ddl = m_tableNameToDDL.get(name.toUpperCase());
// handle the case where this is a materialized view
String query = node.attributes.get("query");
if (query != null) {
assert(query.length() > 0);
matViewMap.put(table, query);
}
// all tables start replicated
// if a partition is found in the project file later,
// then this is reversed
table.setIsreplicated(true);
// map of index replacements for later constraint fixup
Map<String, String> indexReplacementMap = new TreeMap<String, String>();
ArrayList<VoltType> columnTypes = new ArrayList<VoltType>();
for (VoltXMLElement subNode : node.children) {
if (subNode.name.equals("columns")) {
int colIndex = 0;
for (VoltXMLElement columnNode : subNode.children) {
if (columnNode.name.equals("column"))
addColumnToCatalog(table, columnNode, colIndex++, columnTypes);
}
// limit the total number of columns in a table
if (colIndex > MAX_COLUMNS) {
String msg = "Table " + name + " has " +
colIndex + " columns (max is " + MAX_COLUMNS + ")";
throw m_compiler.new VoltCompilerException(msg);
}
}
if (subNode.name.equals("indexes")) {
// do non-system indexes first so they get priority when the compiler
// starts throwing out duplicate indexes
for (VoltXMLElement indexNode : subNode.children) {
if (indexNode.name.equals("index") == false) continue;
String indexName = indexNode.attributes.get("name");
if (indexName.startsWith("SYS_IDX_SYS_") == false) {
addIndexToCatalog(db, table, indexNode, indexReplacementMap);
}
}
// now do system indexes
for (VoltXMLElement indexNode : subNode.children) {
if (indexNode.name.equals("index") == false) continue;
String indexName = indexNode.attributes.get("name");
if (indexName.startsWith("SYS_IDX_SYS_") == true) {
addIndexToCatalog(db, table, indexNode, indexReplacementMap);
}
}
}
if (subNode.name.equals("constraints")) {
for (VoltXMLElement constraintNode : subNode.children) {
if (constraintNode.name.equals("constraint"))
addConstraintToCatalog(table, constraintNode, indexReplacementMap);
}
}
}
table.setSignature(VoltTypeUtil.getSignatureForTable(name, columnTypes));
/*
* Validate that the total size
*/
int maxRowSize = 0;
for (Column c : columnMap.values()) {
VoltType t = VoltType.get((byte)c.getType());
if ((t == VoltType.STRING) || (t == VoltType.VARBINARY)) {
if (c.getSize() > VoltType.MAX_VALUE_LENGTH) {
throw m_compiler.new VoltCompilerException("Table name " + name + " column " + c.getName() +
" has a maximum size of " + c.getSize() + " bytes" +
" but the maximum supported size is " + VoltType.humanReadableSize(VoltType.MAX_VALUE_LENGTH));
}
maxRowSize += 4 + c.getSize();
} else {
maxRowSize += t.getLengthInBytesForFixedTypes();
}
}
if (maxRowSize > MAX_ROW_SIZE) {
throw m_compiler.new VoltCompilerException("Table name " + name + " has a maximum row size of " + maxRowSize +
" but the maximum supported row size is " + MAX_ROW_SIZE);
}
}
void addColumnToCatalog(Table table, VoltXMLElement node, int index, ArrayList<VoltType> columnTypes) throws VoltCompilerException {
assert node.name.equals("column");
String name = node.attributes.get("name");
String typename = node.attributes.get("valuetype");
String nullable = node.attributes.get("nullable");
String sizeString = node.attributes.get("size");
String defaultvalue = null;
String defaulttype = null;
// throws an exception if string isn't an int (i think)
Integer.parseInt(sizeString);
// Default Value
for (VoltXMLElement child : node.children) {
if (child.name.equals("default")) {
for (VoltXMLElement inner_child : child.children) {
// Value
if (inner_child.name.equals("value")) {
assert(defaulttype == null); // There should be only one default value/type.
defaultvalue = inner_child.attributes.get("value");
defaulttype = inner_child.attributes.get("valuetype");
assert(defaulttype != null);
}
}
}
}
if (defaultvalue != null && defaultvalue.equals("NULL"))
defaultvalue = null;
if (defaulttype != null) {
// fyi: Historically, VoltType class initialization errors get reported on this line (?).
defaulttype = Integer.toString(VoltType.typeFromString(defaulttype).getValue());
}
// replace newlines in default values
if (defaultvalue != null) {
defaultvalue = defaultvalue.replace('\n', ' ');
defaultvalue = defaultvalue.replace('\r', ' ');
}
// fyi: Historically, VoltType class initialization errors get reported on this line (?).
VoltType type = VoltType.typeFromString(typename);
columnTypes.add(type);
if (defaultvalue != null && (type == VoltType.DECIMAL || type == VoltType.NUMERIC))
{
// Until we support deserializing scientific notation in the EE, we'll
// coerce default values to plain notation here. See ENG-952 for more info.
BigDecimal temp = new BigDecimal(defaultvalue);
defaultvalue = temp.toPlainString();
}
Column column = table.getColumns().add(name);
// need to set other column data here (default, nullable, etc)
column.setName(name);
column.setIndex(index);
column.setType(type.getValue());
column.setNullable(nullable.toLowerCase().startsWith("t") ? true : false);
int size = type.getMaxLengthInBytes();
// Require a valid length if variable length is supported for a type
if (type == VoltType.STRING || type == VoltType.VARBINARY) {
size = Integer.parseInt(sizeString);
if ((size == 0) || (size > VoltType.MAX_VALUE_LENGTH)) {
String msg = type.toSQLString() + " column " + name + " in table " + table.getTypeName() + " has unsupported length " + sizeString;
throw m_compiler.new VoltCompilerException(msg);
}
}
column.setSize(size);
column.setDefaultvalue(defaultvalue);
if (defaulttype != null)
column.setDefaulttype(Integer.parseInt(defaulttype));
columnMap.put(name, column);
}
/**
* Return true if the two indexes are identical with a different name.
*/
boolean indexesAreDups(Index idx1, Index idx2) {
// same attributes?
if (idx1.getType() != idx2.getType()) {
return false;
}
if (idx1.getCountable() != idx2.getCountable()) {
return false;
}
if (idx1.getUnique() != idx2.getUnique()) {
return false;
}
// same column count?
if (idx1.getColumns().size() != idx2.getColumns().size()) {
return false;
}
//TODO: For index types like HASH that support only random access vs. scanned ranges, indexes on different
// permutations of the same list of columns/expressions could be considered dupes. This code skips that edge
// case optimization in favor of using a simpler more exact permutation-sensitive algorithm for all indexes.
if ( ! (idx1.getExpressionsjson().equals(idx2.getExpressionsjson()))) {
return false;
}
// Simple column indexes have identical empty expression strings so need to be distinguished other ways.
// More complex expression indexes that have the same expression strings always have the same set of (base)
// columns referenced in the same order, but we fall through and check them, anyway.
// sort in index order the columns of idx1, each identified by its index in the base table
int[] idx1baseTableOrder = new int[idx1.getColumns().size()];
for (ColumnRef cref : idx1.getColumns()) {
int index = cref.getIndex();
int baseTableIndex = cref.getColumn().getIndex();
idx1baseTableOrder[index] = baseTableIndex;
}
// sort in index order the columns of idx2, each identified by its index in the base table
int[] idx2baseTableOrder = new int[idx2.getColumns().size()];
for (ColumnRef cref : idx2.getColumns()) {
int index = cref.getIndex();
int baseTableIndex = cref.getColumn().getIndex();
idx2baseTableOrder[index] = baseTableIndex;
}
// Duplicate indexes have identical columns in identical order.
return Arrays.equals(idx1baseTableOrder, idx2baseTableOrder);
}
void addIndexToCatalog(Database db, Table table, VoltXMLElement node, Map<String, String> indexReplacementMap)
throws VoltCompilerException
{
assert node.name.equals("index");
String name = node.attributes.get("name");
boolean unique = Boolean.parseBoolean(node.attributes.get("unique"));
AbstractParsedStmt dummy = new ParsedSelectStmt(null, db);
dummy.setTable(table);
// "parse" the expression trees for an expression-based index (vs. a simple column value index)
AbstractExpression[] exprs = null;
for (VoltXMLElement subNode : node.children) {
if (subNode.name.equals("exprs")) {
exprs = new AbstractExpression[subNode.children.size()];
int j = 0;
for (VoltXMLElement exprNode : subNode.children) {
exprs[j] = dummy.parseExpressionTree(exprNode);
exprs[j].resolveForTable(table);
exprs[j].finalizeValueTypes();
++j;
}
}
}
String colList = node.attributes.get("columns");
String[] colNames = colList.split(",");
Column[] columns = new Column[colNames.length];
boolean has_nonint_col = false;
String nonint_col_name = null;
for (int i = 0; i < colNames.length; i++) {
columns[i] = columnMap.get(colNames[i]);
if (columns[i] == null) {
return;
}
}
if (exprs == null) {
for (int i = 0; i < colNames.length; i++) {
VoltType colType = VoltType.get((byte)columns[i].getType());
if (colType == VoltType.DECIMAL || colType == VoltType.FLOAT || colType == VoltType.STRING) {
has_nonint_col = true;
nonint_col_name = colNames[i];
}
// disallow columns from VARBINARYs
if (colType == VoltType.VARBINARY) {
String msg = "VARBINARY values are not currently supported as index keys: '" + colNames[i] + "'";
throw this.m_compiler.new VoltCompilerException(msg);
}
}
} else {
for (AbstractExpression expression : exprs) {
VoltType colType = expression.getValueType();
if (colType == VoltType.DECIMAL || colType == VoltType.FLOAT || colType == VoltType.STRING) {
has_nonint_col = true;
nonint_col_name = "<expression>";
}
// disallow expressions of type VARBINARY
if (colType == VoltType.VARBINARY) {
String msg = "VARBINARY expressions are not currently supported as index keys.";
throw this.m_compiler.new VoltCompilerException(msg);
}
}
}
Index index = table.getIndexes().add(name);
index.setCountable(false);
// set the type of the index based on the index name and column types
// Currently, only int types can use hash or array indexes
String indexNameNoCase = name.toLowerCase();
if (indexNameNoCase.contains("tree"))
{
index.setType(IndexType.BALANCED_TREE.getValue());
index.setCountable(true);
}
else if (indexNameNoCase.contains("hash"))
{
if (!has_nonint_col)
{
index.setType(IndexType.HASH_TABLE.getValue());
}
else
{
String msg = "Index " + name + " in table " + table.getTypeName() +
" uses a non-hashable column " + nonint_col_name;
throw m_compiler.new VoltCompilerException(msg);
}
} else {
index.setType(IndexType.BALANCED_TREE.getValue());
index.setCountable(true);
}
// Countable is always on right now. Fix it when VoltDB can pack memory for TreeNode.
// if (indexNameNoCase.contains("NoCounter")) {
// index.setType(IndexType.BALANCED_TREE.getValue());
// index.setCountable(false);
// }
// need to set other index data here (column, etc)
// For expression indexes, the columns listed in the catalog do not correspond to the values in the index,
// but they still represent the columns that will trigger an index update when their values change.
for (int i = 0; i < columns.length; i++) {
ColumnRef cref = index.getColumns().add(columns[i].getTypeName());
cref.setColumn(columns[i]);
cref.setIndex(i);
}
if (exprs != null) {
try {
index.setExpressionsjson(convertToJSONArray(exprs));
} catch (JSONException e) {
throw m_compiler.new VoltCompilerException("Unexpected error serializing non-column expressions for index '" +
name + "' on type '" + table.getTypeName() + "': " + e.toString());
}
}
index.setUnique(unique);
// check if an existing index duplicates another index (if so, drop it)
// note that this is an exact dup... uniqueness, counting-ness and type
// will make two indexes different
for (Index existingIndex : table.getIndexes()) {
// skip thineself
if (existingIndex == index) {
continue;
}
if (indexesAreDups(existingIndex, index)) {
// replace any constraints using one index with the other
//for () TODO
// get ready for replacements from constraints created later
indexReplacementMap.put(index.getTypeName(), existingIndex.getTypeName());
// if the index is a user-named index...
if (index.getTypeName().startsWith("SYS_IDX_") == false) {
// on dup-detection, add a warning but don't fail
String msg = String.format("Dropping index %s on table %s because it duplicates index %s.",
index.getTypeName(), table.getTypeName(), existingIndex.getTypeName());
m_compiler.addWarn(msg);
}
// drop the index and GTFO
table.getIndexes().delete(index.getTypeName());
return;
}
}
String msg = "Created index: " + name + " on table: " +
table.getTypeName() + " of type: " + IndexType.get(index.getType()).name();
m_compiler.addInfo(msg);
indexMap.put(name, index);
}
private static String convertToJSONArray(AbstractExpression[] exprs) throws JSONException {
JSONStringer stringer = new JSONStringer();
stringer.array();
for (AbstractExpression abstractExpression : exprs) {
stringer.object();
abstractExpression.toJSONString(stringer);
stringer.endObject();
}
stringer.endArray();
return stringer.toString();
}
/**
* Add a constraint on a given table to the catalog
* @param table
* @param node
* @throws VoltCompilerException
*/
void addConstraintToCatalog(Table table, VoltXMLElement node, Map<String, String> indexReplacementMap)
throws VoltCompilerException
{
assert node.name.equals("constraint");
String name = node.attributes.get("name");
String typeName = node.attributes.get("constrainttype");
ConstraintType type = ConstraintType.valueOf(typeName);
if (type == ConstraintType.CHECK) {
String msg = "VoltDB does not enforce check constraints. ";
msg += "Constraint on table " + table.getTypeName() + " will be ignored.";
m_compiler.addWarn(msg);
return;
}
else if (type == ConstraintType.FOREIGN_KEY) {
String msg = "VoltDB does not enforce foreign key references and constraints. ";
msg += "Constraint on table " + table.getTypeName() + " will be ignored.";
m_compiler.addWarn(msg);
return;
}
else if (type == ConstraintType.MAIN) {
// should never see these
assert(false);
}
else if (type == ConstraintType.NOT_NULL) {
// these get handled by table metadata inspection
return;
}
else if (type != ConstraintType.PRIMARY_KEY && type != ConstraintType.UNIQUE) {
throw m_compiler.new VoltCompilerException("Invalid constraint type '" + typeName + "'");
}
// else, create the unique index below
// primary key code is in other places as well
// The constraint is backed by an index, therefore we need to create it
// TODO: We need to be able to use indexes for foreign keys. I am purposely
// leaving those out right now because HSQLDB just makes too many of them.
Constraint catalog_const = table.getConstraints().add(name);
String indexName = node.attributes.get("index");
assert(indexName != null);
// handle replacements from duplicate index pruning
if (indexReplacementMap.containsKey(indexName)) {
indexName = indexReplacementMap.get(indexName);
}
Index catalog_index = indexMap.get(indexName);
if (catalog_index != null) {
// if the constraint name contains index type hints, exercise them (giant hack)
String constraintNameNoCase = name.toLowerCase();
if (constraintNameNoCase.contains("tree"))
catalog_index.setType(IndexType.BALANCED_TREE.getValue());
if (constraintNameNoCase.contains("hash"))
catalog_index.setType(IndexType.HASH_TABLE.getValue());
catalog_const.setIndex(catalog_index);
catalog_index.setUnique(true);
}
catalog_const.setType(type.getValue());
}
/**
* Add materialized view info to the catalog for the tables that are
* materialized views.
*/
void processMaterializedViews(Database db) throws VoltCompiler.VoltCompilerException {
for (Entry<Table, String> entry : matViewMap.entrySet()) {
Table destTable = entry.getKey();
String query = entry.getValue();
// get the xml for the query
VoltXMLElement xmlquery = null;
try {
xmlquery = m_hsql.getXMLCompiledStatement(query);
}
catch (HSQLParseException e) {
e.printStackTrace();
}
assert(xmlquery != null);
// parse the xml like any other sql statement
ParsedSelectStmt stmt = null;
try {
stmt = (ParsedSelectStmt) AbstractParsedStmt.parse(query, xmlquery, null, db, null);
}
catch (Exception e) {
throw m_compiler.new VoltCompilerException(e.getMessage());
}
assert(stmt != null);
// throw an error if the view isn't within voltdb's limited worldview
checkViewMeetsSpec(destTable.getTypeName(), stmt);
// create the materializedviewinfo catalog node for the source table
Table srcTable = stmt.tableList.get(0);
MaterializedViewInfo matviewinfo = srcTable.getViews().add(destTable.getTypeName());
matviewinfo.setDest(destTable);
AbstractExpression where = stmt.getCombinedFilterExpression();
if (where != null) {
String hex = Encoder.hexEncode(where.toJSONString());
matviewinfo.setPredicate(hex);
} else {
matviewinfo.setPredicate("");
}
destTable.setMaterializer(srcTable);
List<Column> srcColumnArray = CatalogUtil.getSortedCatalogItems(srcTable.getColumns(), "index");
List<Column> destColumnArray = CatalogUtil.getSortedCatalogItems(destTable.getColumns(), "index");
// add the group by columns from the src table
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i);
Column srcCol = srcColumnArray.get(gbcol.index);
ColumnRef cref = matviewinfo.getGroupbycols().add(srcCol.getTypeName());
// groupByColumns is iterating in order of groups. Store that grouping order
// in the column ref index. When the catalog is serialized, it will, naturally,
// scramble this order like a two year playing dominos, presenting the data
// in a meaningless sequence.
cref.setIndex(i); // the column offset in the view's grouping order
cref.setColumn(srcCol); // the source column from the base (non-view) table
}
ParsedSelectStmt.ParsedColInfo countCol = stmt.displayColumns.get(stmt.groupByColumns.size());
assert(countCol.expression.getExpressionType() == ExpressionType.AGGREGATE_COUNT_STAR);
assert(countCol.expression.getLeft() == null);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumnArray.get(stmt.groupByColumns.size()),
ExpressionType.AGGREGATE_COUNT_STAR, null);
// create an index and constraint for the table
Index pkIndex = destTable.getIndexes().add("MATVIEW_PK_INDEX");
pkIndex.setType(IndexType.BALANCED_TREE.getValue());
pkIndex.setUnique(true);
// add the group by columns from the src table
// assume index 1 throuh #grpByCols + 1 are the cols
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ColumnRef c = pkIndex.getColumns().add(String.valueOf(i));
c.setColumn(destColumnArray.get(i));
c.setIndex(i);
}
Constraint pkConstraint = destTable.getConstraints().add("MATVIEW_PK_CONSTRAINT");
pkConstraint.setType(ConstraintType.PRIMARY_KEY.getValue());
pkConstraint.setIndex(pkIndex);
// parse out the group by columns into the dest table
for (int i = 0; i < stmt.groupByColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i);
Column destColumn = destColumnArray.get(i);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn,
ExpressionType.VALUE_TUPLE, (TupleValueExpression)col.expression);
}
// parse out the aggregation columns into the dest table
for (int i = stmt.groupByColumns.size() + 1; i < stmt.displayColumns.size(); i++) {
ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i);
Column destColumn = destColumnArray.get(i);
AbstractExpression colExpr = col.expression.getLeft();
assert(colExpr.getExpressionType() == ExpressionType.VALUE_TUPLE);
processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn,
col.expression.getExpressionType(), (TupleValueExpression)colExpr);
// Correctly set the type of the column so that it's consistent.
// Otherwise HSQLDB might promote types differently than Volt.
destColumn.setType(col.expression.getValueType().getValue());
}
}
}
/**
* Verify the materialized view meets our arcane rules about what can and can't
* go in a materialized view. Throw hopefully helpful error messages when these
* rules are inevitably borked.
*
* @param viewName The name of the view being checked.
* @param stmt The output from the parser describing the select statement that creates the view.
* @throws VoltCompilerException
*/
private void checkViewMeetsSpec(String viewName, ParsedSelectStmt stmt) throws VoltCompilerException {
int groupColCount = stmt.groupByColumns.size();
int displayColCount = stmt.displayColumns.size();
String msg = "Materialized view \"" + viewName + "\" ";
if (stmt.tableList.size() != 1) {
msg += "has " + String.valueOf(stmt.tableList.size()) + " sources. " +
"Only one source view or source table is allowed.";
throw m_compiler.new VoltCompilerException(msg);
}
if (displayColCount <= groupColCount) {
msg += "has too few columns.";
throw m_compiler.new VoltCompilerException(msg);
}
if (stmt.hasComplexGroupby()) {
msg += "contains an expression involving a group by. " +
"Expressions with group by are not currently supported in views.";
throw m_compiler.new VoltCompilerException(msg);
}
if (stmt.hasComplexAgg()) {
msg += "contains an expression involving an aggregate function. " +
"Expressions with aggregate functions are not currently supported in views.";
throw m_compiler.new VoltCompilerException(msg);
}
int i;
for (i = 0; i < groupColCount; i++) {
ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i);
ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i);
if (outcol.expression.getExpressionType() != ExpressionType.VALUE_TUPLE) {
msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias;
throw m_compiler.new VoltCompilerException(msg);
}
TupleValueExpression expr = (TupleValueExpression) outcol.expression;
if (expr.getColumnIndex() != gbcol.index) {
msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias;
throw m_compiler.new VoltCompilerException(msg);
}
}
AbstractExpression coli = stmt.displayColumns.get(i).expression;
if (coli.getExpressionType() != ExpressionType.AGGREGATE_COUNT_STAR) {
msg += "is missing count(*) as the column after the group by columns, a materialized view requirement.";
throw m_compiler.new VoltCompilerException(msg);
}
for (i++; i < displayColCount; i++) {
ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i);
if ((outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_COUNT) &&
(outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_SUM)) {
msg += "must have non-group by columns aggregated by sum or count.";
throw m_compiler.new VoltCompilerException(msg);
}
if (outcol.expression.getLeft().getExpressionType() != ExpressionType.VALUE_TUPLE) {
msg += "must have non-group by columns use only one level of aggregation.";
throw m_compiler.new VoltCompilerException(msg);
}
}
}
void processMaterializedViewColumn(MaterializedViewInfo info, Table srcTable, Table destTable,
Column destColumn, ExpressionType type, TupleValueExpression colExpr)
throws VoltCompiler.VoltCompilerException {
if (colExpr != null) {
assert(colExpr.getTableName().equalsIgnoreCase(srcTable.getTypeName()));
String srcColName = colExpr.getColumnName();
Column srcColumn = srcTable.getColumns().getIgnoreCase(srcColName);
destColumn.setMatviewsource(srcColumn);
}
destColumn.setMatview(info);
destColumn.setAggregatetype(type.getValue());
}
}
|
ENG-4997: Revert thing I forgot to revert to fix bug.
|
src/frontend/org/voltdb/compiler/DDLCompiler.java
|
ENG-4997: Revert thing I forgot to revert to fix bug.
|
|
Java
|
agpl-3.0
|
54865901edc4ad6dbd2498ab64cd06e370aefc7a
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
6f5fbb26-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
6f5a5e60-2e62-11e5-9284-b827eb9e62be
|
6f5fbb26-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
6f5fbb26-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
f114a0a7e2dc1be5804e2f82bebcc38d5954475f
| 0
|
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
|
43146ba2-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
430f0126-2e62-11e5-9284-b827eb9e62be
|
43146ba2-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
43146ba2-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
d9e0db65d42da14dd801763195060ad8a7f0263d
| 0
|
FableBlaze/RuM,FableBlaze/RuM
|
package ee.ut.cs.rum.plugins.internal.ui.details;
import java.text.SimpleDateFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import ee.ut.cs.rum.database.domain.Plugin;
import ee.ut.cs.rum.database.util.PluginAccess;
import ee.ut.cs.rum.plugins.development.description.PluginInfo;
import ee.ut.cs.rum.plugins.development.description.deserializer.PluginInfoDeserializer;
import ee.ut.cs.rum.plugins.development.ui.PluginConfigurationUi;
import ee.ut.cs.rum.plugins.ui.PluginsManagementUI;
public class PluginDetails extends ScrolledComposite {
private static final long serialVersionUID = 458942786595146853L;
private Long pluginId;
private Composite content;
public PluginDetails(PluginsManagementUI pluginsManagementUI, Long pluginId) {
super(pluginsManagementUI, SWT.CLOSE | SWT.H_SCROLL | SWT.V_SCROLL);
this.pluginId = pluginId;
this.content = new Composite(this, SWT.NONE);
content.setLayout(new GridLayout(2, false));
this.setContent(content);
Plugin plugin = PluginAccess.getPluginDataFromDb(pluginId);
createContents(plugin);
content.setSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
private void createContents(Plugin plugin) {
Label label = new Label (content, SWT.NONE);
label.setText("Plugin details");
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
((GridData) label.getLayoutData()).horizontalSpan = ((GridLayout) content.getLayout()).numColumns;
label = new Label (content, SWT.NONE);
label.setText("Id:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getId().toString());
label = new Label (content, SWT.NONE);
label.setText("Symbolic name:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleSymbolicName());
label = new Label (content, SWT.NONE);
label.setText("Version:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleVersion());
label = new Label (content, SWT.NONE);
label.setText("Name:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleName());
label = new Label (content, SWT.NONE);
label.setText("Vendor:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleVendor());
label = new Label (content, SWT.NONE);
label.setText("Description:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleDescription());
label = new Label (content, SWT.NONE);
label.setText("Activator:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleActivator());
label = new Label (content, SWT.NONE);
label.setText("Original filename:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getOriginalFilename());
label = new Label (content, SWT.NONE);
label.setText("Uploaded at:");
label = new Label (content, SWT.NONE);
label.setText(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(plugin.getUploadedAt()));
label = new Label (content, SWT.NONE);
label.setText("Uploaded by:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getUploadedBy());
label = new Label (content, SWT.NONE);
label.setText("File path:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getFileLocation());
label = new Label (content, SWT.NONE);
label.setText("Configuration UI:");
label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PluginInfo.class, new PluginInfoDeserializer());
Gson gson = gsonBuilder.create();
PluginInfo pluginInfo = gson.fromJson(plugin.getPluginInfo(), PluginInfo.class);
PluginConfigurationUi pluginConfigurationUi = new PluginConfigurationUi(content, pluginInfo);
pluginConfigurationUi.setEnabled(false);
label = new Label (content, SWT.NONE);
label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
label.setText("Imported packages:");
//TODO: Should parse import packages list better
Composite importedPackagesContainer = new Composite(content, SWT.NONE);
importedPackagesContainer.setLayout(new FillLayout(SWT.VERTICAL));
for (String importedPackage : plugin.getBundleImportPackage().split("\",")) {
label = new Label (importedPackagesContainer, SWT.NONE);
label.setText(importedPackage);
}
}
public Long getPluginId() {
return pluginId;
}
}
|
RuM_Plugins/src/ee/ut/cs/rum/plugins/internal/ui/details/PluginDetails.java
|
package ee.ut.cs.rum.plugins.internal.ui.details;
import java.text.SimpleDateFormat;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import ee.ut.cs.rum.database.domain.Plugin;
import ee.ut.cs.rum.database.util.PluginAccess;
import ee.ut.cs.rum.plugins.development.description.PluginInfo;
import ee.ut.cs.rum.plugins.development.description.deserializer.PluginInfoDeserializer;
import ee.ut.cs.rum.plugins.development.ui.PluginConfigurationUi;
import ee.ut.cs.rum.plugins.ui.PluginsManagementUI;
public class PluginDetails extends ScrolledComposite {
private static final long serialVersionUID = 458942786595146853L;
private Long pluginId;
private Composite content;
public PluginDetails(PluginsManagementUI pluginsManagementUI, Long pluginId) {
super(pluginsManagementUI, SWT.CLOSE | SWT.H_SCROLL | SWT.V_SCROLL);
this.pluginId = pluginId;
this.content = new Composite(this, SWT.NONE);
content.setLayout(new GridLayout(2, false));
this.setContent(content);
Plugin plugin = PluginAccess.getPluginDataFromDb(pluginId);
createContents(plugin);
content.setSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
private void createContents(Plugin plugin) {
Label label = new Label (content, SWT.NONE);
label.setText("Plugin details");
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
((GridData) label.getLayoutData()).horizontalSpan = ((GridLayout) content.getLayout()).numColumns;
label = new Label (content, SWT.NONE);
label.setText("Id:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getId().toString());
label = new Label (content, SWT.NONE);
label.setText("Symbolic name:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleSymbolicName());
label = new Label (content, SWT.NONE);
label.setText("Version:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleVersion());
label = new Label (content, SWT.NONE);
label.setText("Name:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleName());
label = new Label (content, SWT.NONE);
label.setText("Vendor:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleVendor());
label = new Label (content, SWT.NONE);
label.setText("Description:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleDescription());
label = new Label (content, SWT.NONE);
label.setText("Activator:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getBundleActivator());
label = new Label (content, SWT.NONE);
label.setText("Configuration UI:");
label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PluginInfo.class, new PluginInfoDeserializer());
Gson gson = gsonBuilder.create();
PluginInfo pluginInfo = gson.fromJson(plugin.getPluginInfo(), PluginInfo.class);
PluginConfigurationUi pluginConfigurationUi = new PluginConfigurationUi(content, pluginInfo);
pluginConfigurationUi.setEnabled(false);
label = new Label (content, SWT.NONE);
label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
label.setText("Imported packages:");
//TODO: Should parse import packages list better
Composite importedPackagesContainer = new Composite(content, SWT.NONE);
importedPackagesContainer.setLayout(new FillLayout(SWT.VERTICAL));
for (String importedPackage : plugin.getBundleImportPackage().split("\",")) {
label = new Label (importedPackagesContainer, SWT.NONE);
label.setText(importedPackage);
}
label = new Label (content, SWT.NONE);
label.setText("Original filename:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getOriginalFilename());
label = new Label (content, SWT.NONE);
label.setText("Uploaded at:");
label = new Label (content, SWT.NONE);
label.setText(new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(plugin.getUploadedAt()));
label = new Label (content, SWT.NONE);
label.setText("Uploaded by:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getUploadedBy());
label = new Label (content, SWT.NONE);
label.setText("File path:");
label = new Label (content, SWT.NONE);
label.setText(plugin.getFileLocation());
}
public Long getPluginId() {
return pluginId;
}
}
|
Moved configurationUi and importedPackages to the end of plugin details
|
RuM_Plugins/src/ee/ut/cs/rum/plugins/internal/ui/details/PluginDetails.java
|
Moved configurationUi and importedPackages to the end of plugin details
|
|
Java
|
lgpl-2.1
|
1b3c469468f1b5bc45ff9fde1608440a6c194ddd
| 0
|
plast-lab/soot,cfallin/soot,anddann/soot,xph906/SootNew,plast-lab/soot,mbenz89/soot,xph906/SootNew,cfallin/soot,plast-lab/soot,cfallin/soot,mbenz89/soot,xph906/SootNew,anddann/soot,anddann/soot,mbenz89/soot,anddann/soot,cfallin/soot,xph906/SootNew,mbenz89/soot
|
package soot.jimple.toolkits.thread.transaction;
import java.util.*;
import soot.*;
import soot.util.Chain;
import soot.jimple.*;
import soot.toolkits.scalar.*;
public class TransactionBodyTransformer extends BodyTransformer
{
private static final TransactionBodyTransformer instance = new TransactionBodyTransformer();
private TransactionBodyTransformer() {}
public static TransactionBodyTransformer v() { return instance; }
public static boolean[] addedGlobalLockObj = null;
private static boolean addedGlobalLockDefs = false;
private static int throwableNum = 0; // doesn't matter if not reinitialized to 0
protected void internalTransform(Body b, String phase, Map opts)
{
throw new RuntimeException("Not Supported");
}
protected void internalTransform(Body b, FlowSet fs, List<TransactionGroup> groups)
{
//
JimpleBody j = (JimpleBody) b;
SootMethod thisMethod = b.getMethod();
PatchingChain units = b.getUnits();
Iterator unitIt = units.iterator();
Unit firstUnit = j.getFirstNonIdentityStmt();
Unit lastUnit = (Unit) units.getLast();
// Objects of synchronization, plus book keeping
Local[] lockObj = new Local[groups.size()];
boolean[] addedLocalLockObj = new boolean[groups.size()];
SootField[] globalLockObj = new SootField[groups.size()];
for(int i = 1; i < groups.size(); i++)
{
lockObj[i] = Jimple.v().newLocal("lockObj" + i, RefType.v("java.lang.Object"));
addedLocalLockObj[i] = false;
globalLockObj[i] = null;
}
// Make sure a main routine exists. We will insert some code into it.
// if (!Scene.v().getMainClass().declaresMethod("void main(java.lang.String[])"))
// throw new RuntimeException("couldn't find main() in mainClass");
// Add all global lock objects to the main class if not yet added.
// Get references to them if they do already exist.
for(int i = 1; i < groups.size(); i++)
{
TransactionGroup tnGroup = groups.get(i);
// if( useGlobalLock[i - 1] )
if( !tnGroup.useDynamicLock && !tnGroup.useLocksets )
{
if( !addedGlobalLockObj[i] )
{
// Add globalLockObj field if possible...
// Avoid name collision... if it's already there, then just use it!
try
{
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
// field already exists
}
catch(RuntimeException re)
{
// field does not yet exist (or, as a pre-existing error, there is more than one field by this name)
globalLockObj[i] = new SootField("globalLockObj" + i, RefType.v("java.lang.Object"),
Modifier.STATIC | Modifier.PUBLIC);
Scene.v().getMainClass().addField(globalLockObj[i]);
}
addedGlobalLockObj[i] = true;
}
else
{
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
}
}
}
// If the current method is the clinit method of the main class, for each global lock object,
// add a local lock object and assign it a new object. Copy the new
// local lock object into the global lock object for use by other fns.
if(!addedGlobalLockDefs)// thisMethod.getSubSignature().equals("void <clinit>()") && thisMethod.getDeclaringClass() == Scene.v().getMainClass())
{
// Either get or add the <clinit> method to the main class
SootClass mainClass = Scene.v().getMainClass();
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !mainClass.declaresMethod("void <clinit>()");
if(addingNewClinit)
{
clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
mainClass.addMethod(clinitMethod);
}
else
{
clinitMethod = mainClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain clinitUnits = clinitBody.getUnits();
for(int i = 1; i < groups.size(); i++)
{
TransactionGroup tnGroup = groups.get(i);
// if( useGlobalLock[i - 1] )
if( !tnGroup.useDynamicLock && !tnGroup.useLocksets )
{
// add local lock obj
// addedLocalLockObj[i] = true;
clinitBody.getLocals().add(lockObj[i]); // TODO: add name conflict avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockObj[i],
Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if(addingNewClinit)
clinitUnits.add(newStmt);
else
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(lockObj[i],
initMethod.makeRef(), Collections.EMPTY_LIST));
if(addingNewClinit)
clinitUnits.add(initStmt);
else
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
// copy new object to global static lock object (for use by other fns)
Stmt assignStmt = Jimple.v().newAssignStmt(
Jimple.v().newStaticFieldRef(globalLockObj[i].makeRef()), lockObj[i]);
if(addingNewClinit)
clinitUnits.add(assignStmt);
else
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
}
}
if(addingNewClinit)
clinitUnits.add(Jimple.v().newReturnVoidStmt());
addedGlobalLockDefs = true;
}
int tempNum = 1;
// Iterate through all of the transactions in the current method
Iterator fsIt = fs.iterator();
Stmt newPrep = null;
while(fsIt.hasNext())
{
Transaction tn = ((TransactionFlowPair) fsIt.next()).tn;
if(tn.setNumber == -1)
continue; // this tn should be deleted... for now just skip it!
if(tn.wholeMethod)
{
thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method
}
Local clo = null; // depends on type of locking
LockRegion clr = null; // current lock region
int lockNum = 0;
boolean moreLocks = true;
while(moreLocks)
{
// If this method does not yet have a reference to the lock object
// needed for this transaction, then create one.
if( tn.group.useDynamicLock )
{
Value lock = getLockFor((EquivalentValue) tn.lockObject); // adds local vars and global objects if needed
if(lock instanceof Ref)
{
if(!b.getLocals().contains(lockObj[tn.setNumber]))
b.getLocals().add(lockObj[tn.setNumber]);
newPrep = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock);
if(tn.wholeMethod)
units.insertBeforeNoRedirect(newPrep, firstUnit);
else
units.insertBefore(newPrep, tn.entermonitor);
clo = lockObj[tn.setNumber];
}
else if(lock instanceof Local)
clo = (Local) lock;
else
throw new RuntimeException("Unknown type of lock (" + lock + "): expected Ref or Local");
clr = tn;
moreLocks = false;
}
else if( tn.group.useLocksets )
{
Value lock = getLockFor((EquivalentValue) tn.lockset.get(lockNum)); // adds local vars and global objects if needed
if( lock instanceof FieldRef )
{
// add a local variable for this lock
Local lockLocal = Jimple.v().newLocal("locksetObj" + tempNum, RefType.v("java.lang.Object"));
tempNum++;
b.getLocals().add(lockLocal);
// make it refer to the right lock object
newPrep = Jimple.v().newAssignStmt(lockLocal, lock);
if(tn.entermonitor != null)
units.insertBefore(newPrep, tn.entermonitor);
else
units.insertBeforeNoRedirect(newPrep, tn.beginning);
// use it as the lock
clo = lockLocal;
}
else if( lock instanceof Local )
clo = (Local) lock;
else
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local");
if(lockNum + 1 >= tn.lockset.size())
moreLocks = false;
else
moreLocks = true;
if( lockNum > 0 )
{
LockRegion nlr = new LockRegion();
nlr.beginning = clr.beginning;
for (Pair earlyEnd : clr.earlyEnds) {
Stmt earlyExitmonitor = (Stmt) earlyEnd.getO2();
nlr.earlyEnds.add(new Pair(earlyExitmonitor, null)); // <early exitmonitor, null>
}
nlr.last = clr.last; // last stmt before exception handling
if(clr.end != null)
{
Stmt endExitmonitor = (Stmt) clr.end.getO2();
nlr.after = endExitmonitor;
}
clr = nlr;
}
else
clr = tn;
}
else // global lock
{
if(!addedLocalLockObj[tn.setNumber])
b.getLocals().add(lockObj[tn.setNumber]);
addedLocalLockObj[tn.setNumber] = true;
newPrep = Jimple.v().newAssignStmt(lockObj[tn.setNumber],
Jimple.v().newStaticFieldRef(globalLockObj[tn.setNumber].makeRef()));
if(tn.wholeMethod)
units.insertBeforeNoRedirect(newPrep, firstUnit);
else
units.insertBefore(newPrep, tn.entermonitor);
clo = lockObj[tn.setNumber];
clr = tn;
moreLocks = false;
}
// Add synchronization code
// For transactions from synchronized methods, use synchronizeSingleEntrySingleExitBlock()
// to add all necessary code (including ugly exception handling)
// For transactions from synchronized blocks, simply replace the
// monitorenter/monitorexit statements with new ones
if(true)
{
// Remove old prep stmt
if( clr.prepStmt != null )
{
// units.remove(clr.prepStmt);
}
// Reuse old entermonitor or insert new one, and insert prep
Stmt newEntermonitor = Jimple.v().newEnterMonitorStmt(clo);
if( clr.entermonitor != null )
{
units.insertBefore(newEntermonitor, clr.entermonitor);
// redirectTraps(b, clr.entermonitor, newEntermonitor); // EXPERIMENTAL
units.remove(clr.entermonitor);
clr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep);
// clr.prepStmt = newPrep;
}
else
{
units.insertBeforeNoRedirect(newEntermonitor, clr.beginning);
clr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep);
// clr.prepStmt = newPrep;
}
// For each early end, reuse or insert exitmonitor stmt
List<Pair> newEarlyEnds = new ArrayList<Pair>();
for (Pair end : clr.earlyEnds) {
Stmt earlyEnd = (Stmt) end.getO1();
Stmt exitmonitor = (Stmt) end.getO2();
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( exitmonitor != null )
{
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor);
}
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL
units.remove(exitmonitor);
newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor));
}
else
{
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, earlyEnd);
}
units.insertBefore(newExitmonitor, earlyEnd);
newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor));
}
}
clr.earlyEnds = newEarlyEnds;
// If fallthrough end, reuse or insert goto and exit
if( clr.after != null )
{
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( clr.end != null )
{
Stmt exitmonitor = (Stmt) clr.end.getO2();
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor);
}
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL
units.remove(exitmonitor);
clr.end = new Pair(clr.end.getO1(), newExitmonitor);
}
else
{
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, clr.after);
}
units.insertBefore(newExitmonitor, clr.after); // steal jumps to end, send them to monitorexit
Stmt newGotoStmt = Jimple.v().newGotoStmt(clr.after);
units.insertBeforeNoRedirect(newGotoStmt, clr.after);
clr.end = new Pair(newGotoStmt, newExitmonitor);
}
}
// If exceptional end, reuse it, else insert it and traps
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( clr.exceptionalEnd != null )
{
Stmt exitmonitor = (Stmt) clr.exceptionalEnd.getO2();
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, exitmonitor);
}
units.insertBefore(newExitmonitor, exitmonitor);
units.remove(exitmonitor);
clr.exceptionalEnd = new Pair(clr.exceptionalEnd.getO1(), newExitmonitor);
}
else
{
// insert after the last end
Stmt lastEnd = null; // last end stmt (not same as last stmt)
if( clr.end != null )
{
lastEnd = (Stmt) clr.end.getO1();
}
else
{
for (Pair earlyEnd : clr.earlyEnds) {
Stmt end = (Stmt) earlyEnd.getO1();
if( lastEnd == null || (units.contains(lastEnd) && units.contains(end) && units.follows(end, lastEnd)) )
lastEnd = end;
}
}
if(clr.last == null)
clr.last = lastEnd; // last stmt and last end are the same
if( lastEnd == null )
throw new RuntimeException("Lock Region has no ends! Where should we put the exception handling???");
// Add throwable
Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable"));
b.getLocals().add(throwableLocal);
// Add stmts
Stmt newCatch = Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef());
units.insertAfter(newCatch, clr.last);
units.insertAfter(newExitmonitor, newCatch);
Stmt newThrow = Jimple.v().newThrowStmt(throwableLocal);
units.insertAfter(newThrow, newExitmonitor);
// Add traps
SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable");
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, clr.beginning, lastEnd, newCatch));
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, newExitmonitor, newThrow, newCatch));
clr.exceptionalEnd = new Pair(newThrow, newExitmonitor);
}
}
/*
else if(tn.wholeMethod)
{
thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method
synchronizeSingleEntrySingleExitBlock(b, (Stmt) firstUnit, (Stmt) lastUnit, (Local) clo);
}
else if(lockNum > 0)
{
// don't have all the info to do this right yet
// synchronizeSingleEntrySingleExitBlock(b, (Stmt) tnbodystart, (Stmt) tnbodyend, (Local) clo);
}
else
{
if(tn.entermonitor == null)
G.v().out.println("ERROR: Transaction has no beginning statement: " + tn.method.toString());
// Deal with entermonitor
Stmt newBegin = Jimple.v().newEnterMonitorStmt(clo);
units.insertBefore(newBegin, tn.entermonitor);
redirectTraps(b, tn.entermonitor, newBegin);
units.remove(tn.entermonitor);
// Deal with exitmonitors
// early
Iterator endsIt = tn.earlyEnds.iterator();
while(endsIt.hasNext())
{
Pair end = (Pair) endsIt.next();
Stmt sEnd = (Stmt) end.getO2();
Stmt newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
}
// exceptional
Stmt sEnd = (Stmt) tn.exceptionalEnd.getO2();
Stmt newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
// fallthrough
sEnd = (Stmt) tn.end.getO2();
newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
}
*/
// Replace calls to notify() with calls to notifyAll()
// Replace base object with appropriate lockobj
lockNum++;
}
// deal with waits and notifys
{
Iterator<Object> notifysIt = tn.notifys.iterator();
while(notifysIt.hasNext())
{
Stmt sNotify = (Stmt) notifysIt.next();
Stmt newNotify =
Jimple.v().newInvokeStmt(
Jimple.v().newVirtualInvokeExpr(
clo,
sNotify.getInvokeExpr().getMethodRef().declaringClass().getMethod("void notifyAll()").makeRef(),
Collections.EMPTY_LIST));
if(newPrep != null)
{
Stmt tmp = (Stmt) newPrep.clone();
units.insertBefore(tmp, sNotify);
units.insertBefore(newNotify, tmp);
}
else
units.insertBefore(newNotify, sNotify);
redirectTraps(b, sNotify, newNotify);
units.remove(sNotify);
}
// Replace base object of calls to wait with appropriate lockobj
Iterator<Object> waitsIt = tn.waits.iterator();
while(waitsIt.hasNext())
{
Stmt sWait = (Stmt) waitsIt.next();
((InstanceInvokeExpr) sWait.getInvokeExpr()).setBase(clo); // WHAT IF THIS IS THE WRONG LOCK IN A PAIR OF NESTED LOCKS???
if(newPrep != null)
units.insertBefore((Stmt) newPrep.clone(), sWait);
// Stmt newWait =
// Jimple.v().newInvokeStmt(
// Jimple.v().newVirtualInvokeExpr(
// (Local) clo,
// sWait.getInvokeExpr().getMethodRef().declaringClass().getMethod("void wait()").makeRef(),
// Collections.EMPTY_LIST));
// units.insertBefore(newWait, sWait);
// redirectTraps(b, sWait, newWait);
// units.remove(sWait);
}
}
}
}
static int lockNumber = 0;
static Map<EquivalentValue, StaticFieldRef> lockEqValToLock = new HashMap<EquivalentValue, StaticFieldRef>();
static public Value getLockFor(EquivalentValue lockEqVal)
{
Value lock = lockEqVal.getValue();
if( lock instanceof InstanceFieldRef )
return lock;
if( lock instanceof Local )
return lock;
if( lock instanceof StaticFieldRef )
{
if( lockEqValToLock.containsKey(lockEqVal) )
return lockEqValToLock.get(lockEqVal);
StaticFieldRef sfrLock = (StaticFieldRef) lock;
SootClass lockClass = sfrLock.getField().getDeclaringClass();
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !lockClass.declaresMethod("void <clinit>()");
if(addingNewClinit)
{
clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
lockClass.addMethod(clinitMethod);
}
else
{
clinitMethod = lockClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain clinitUnits = clinitBody.getUnits();
Local lockLocal = Jimple.v().newLocal("objectLockLocal" + lockNumber, RefType.v("java.lang.Object"));
// lockNumber is increased below
clinitBody.getLocals().add(lockLocal); // TODO: add name conflict avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockLocal, Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if(addingNewClinit)
clinitUnits.add(newStmt);
else
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(lockLocal,
initMethod.makeRef(), Collections.EMPTY_LIST));
if(addingNewClinit)
clinitUnits.add(initStmt);
else
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
// copy new object to global static lock object (for use by other fns)
SootField actualLockObject = new SootField("objectLockGlobal" + lockNumber, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC);
lockNumber++;
lockClass.addField(actualLockObject);
StaticFieldRef actualLockSfr = Jimple.v().newStaticFieldRef(actualLockObject.makeRef());
Stmt assignStmt = Jimple.v().newAssignStmt(actualLockSfr, lockLocal);
if(addingNewClinit)
clinitUnits.add(assignStmt);
else
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
if(addingNewClinit)
clinitUnits.add(Jimple.v().newReturnVoidStmt());
lockEqValToLock.put(lockEqVal, actualLockSfr);
return actualLockSfr;
}
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local");
}
/*
public void synchronizeSingleEntrySingleExitBlock(Body b, Stmt start, Stmt end, Local lockObj)
{
PatchingChain units = b.getUnits();
// <existing local defs>
// add a throwable to local vars
Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable"));
b.getLocals().add(throwableLocal);
// <existing identity refs>
// add entermonitor statement and label0
// Unit label0Unit = start;
Unit labelEnterMonitorStmt = Jimple.v().newEnterMonitorStmt(lockObj);
units.insertBeforeNoRedirect(labelEnterMonitorStmt, start); // steal jumps to start, send them to monitorenter
// <existing code body> check for return statements
List returnUnits = new ArrayList();
if(start != end)
{
Iterator bodyIt = units.iterator(start, end);
while(bodyIt.hasNext())
{
Stmt bodyStmt = (Stmt) bodyIt.next();
if(bodyIt.hasNext()) // ignore the end unit
{
if( bodyStmt instanceof ReturnStmt ||
bodyStmt instanceof ReturnVoidStmt)
{
returnUnits.add(bodyStmt);
}
}
}
}
// add normal flow and labels
Unit labelExitMonitorStmt = (Unit) Jimple.v().newExitMonitorStmt(lockObj);
units.insertBefore(labelExitMonitorStmt, end); // steal jumps to end, send them to monitorexit
// end = (Stmt) units.getSuccOf(end);
Unit label1Unit = (Unit) Jimple.v().newGotoStmt(end);
units.insertBeforeNoRedirect(label1Unit, end);
// end = (Stmt) units.getSuccOf(end);
// add exceptional flow and labels
Unit label2Unit = (Unit) Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef());
units.insertBeforeNoRedirect(label2Unit, end);
// end = (Stmt) units.getSuccOf(end);
Unit label3Unit = (Unit) Jimple.v().newExitMonitorStmt(lockObj);
units.insertBeforeNoRedirect(label3Unit, end);
// end = (Stmt) units.getSuccOf(end);
Unit label4Unit = (Unit) Jimple.v().newThrowStmt(throwableLocal);
units.insertBeforeNoRedirect(label4Unit, end);
// end = (Stmt) units.getSuccOf(end);
// <existing end statement>
Iterator returnIt = returnUnits.iterator();
while(returnIt.hasNext())
{
Stmt bodyStmt = (Stmt) returnIt.next();
units.insertBefore(Jimple.v().newExitMonitorStmt(lockObj), bodyStmt); // TODO: WHAT IF IT'S IN A NESTED TRANSACTION???
// Stmt placeholder = Jimple.v().newNopStmt();
// units.insertAfter(Jimple.v().newNopStmt(), label4Unit);
// bodyStmt.redirectJumpsToThisTo(placeholder);
// units.insertBefore(Jimple.v().newGotoStmt(placeholder), bodyStmt);
// units.remove(bodyStmt);
// units.swapWith(placeholder, bodyStmt);
// units.swapWith
}
// add exception routing table
Unit label0Unit = (Unit) units.getSuccOf(labelEnterMonitorStmt);
SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable");
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label0Unit, label1Unit, label2Unit));
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label3Unit, label4Unit, label2Unit));
}
*/
public void redirectTraps(Body b, Unit oldUnit, Unit newUnit)
{
Chain traps = b.getTraps();
Iterator trapsIt = traps.iterator();
while(trapsIt.hasNext())
{
AbstractTrap trap = (AbstractTrap) trapsIt.next();
if(trap.getHandlerUnit() == oldUnit)
trap.setHandlerUnit(newUnit);
if(trap.getBeginUnit() == oldUnit)
trap.setBeginUnit(newUnit);
if(trap.getEndUnit() == oldUnit)
trap.setEndUnit(newUnit);
}
}
}
|
src/soot/jimple/toolkits/thread/transaction/TransactionBodyTransformer.java
|
package soot.jimple.toolkits.thread.transaction;
import java.util.*;
import soot.*;
import soot.util.Chain;
import soot.jimple.*;
import soot.toolkits.scalar.*;
public class TransactionBodyTransformer extends BodyTransformer
{
private static final TransactionBodyTransformer instance = new TransactionBodyTransformer();
private TransactionBodyTransformer() {}
public static TransactionBodyTransformer v() { return instance; }
public static boolean[] addedGlobalLockObj = null;
private static boolean addedGlobalLockDefs = false;
private static int throwableNum = 0; // doesn't matter if not reinitialized to 0
protected void internalTransform(Body b, String phase, Map opts)
{
throw new RuntimeException("Not Supported");
}
protected void internalTransform(Body b, FlowSet fs, List<TransactionGroup> groups)
{
//
JimpleBody j = (JimpleBody) b;
SootMethod thisMethod = b.getMethod();
PatchingChain units = b.getUnits();
Iterator unitIt = units.iterator();
Unit firstUnit = j.getFirstNonIdentityStmt();
Unit lastUnit = (Unit) units.getLast();
// Objects of synchronization, plus book keeping
Local[] lockObj = new Local[groups.size()];
boolean[] addedLocalLockObj = new boolean[groups.size()];
SootField[] globalLockObj = new SootField[groups.size()];
for(int i = 1; i < groups.size(); i++)
{
lockObj[i] = Jimple.v().newLocal("lockObj" + i, RefType.v("java.lang.Object"));
addedLocalLockObj[i] = false;
globalLockObj[i] = null;
}
// Make sure a main routine exists. We will insert some code into it.
// if (!Scene.v().getMainClass().declaresMethod("void main(java.lang.String[])"))
// throw new RuntimeException("couldn't find main() in mainClass");
// Add all global lock objects to the main class if not yet added.
// Get references to them if they do already exist.
for(int i = 1; i < groups.size(); i++)
{
TransactionGroup tnGroup = groups.get(i);
// if( useGlobalLock[i - 1] )
if( !tnGroup.useDynamicLock && !tnGroup.useLocksets )
{
if( !addedGlobalLockObj[i] )
{
// Add globalLockObj field if possible...
// Avoid name collision... if it's already there, then just use it!
try
{
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
// field already exists
}
catch(RuntimeException re)
{
// field does not yet exist (or, as a pre-existing error, there is more than one field by this name)
globalLockObj[i] = new SootField("globalLockObj" + i, RefType.v("java.lang.Object"),
Modifier.STATIC | Modifier.PUBLIC);
Scene.v().getMainClass().addField(globalLockObj[i]);
}
addedGlobalLockObj[i] = true;
}
else
{
globalLockObj[i] = Scene.v().getMainClass().getFieldByName("globalLockObj" + i);
}
}
}
// If the current method is the clinit method of the main class, for each global lock object,
// add a local lock object and assign it a new object. Copy the new
// local lock object into the global lock object for use by other fns.
if(!addedGlobalLockDefs)// thisMethod.getSubSignature().equals("void <clinit>()") && thisMethod.getDeclaringClass() == Scene.v().getMainClass())
{
// Either get or add the <clinit> method to the main class
SootClass mainClass = Scene.v().getMainClass();
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !mainClass.declaresMethod("void <clinit>()");
if(addingNewClinit)
{
clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
mainClass.addMethod(clinitMethod);
}
else
{
clinitMethod = mainClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain clinitUnits = clinitBody.getUnits();
for(int i = 1; i < groups.size(); i++)
{
TransactionGroup tnGroup = groups.get(i);
// if( useGlobalLock[i - 1] )
if( !tnGroup.useDynamicLock && !tnGroup.useLocksets )
{
// add local lock obj
// addedLocalLockObj[i] = true;
clinitBody.getLocals().add(lockObj[i]); // TODO: add name conflict avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockObj[i],
Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if(addingNewClinit)
clinitUnits.add(newStmt);
else
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(lockObj[i],
initMethod.makeRef(), Collections.EMPTY_LIST));
if(addingNewClinit)
clinitUnits.add(initStmt);
else
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
// copy new object to global static lock object (for use by other fns)
Stmt assignStmt = Jimple.v().newAssignStmt(
Jimple.v().newStaticFieldRef(globalLockObj[i].makeRef()), lockObj[i]);
if(addingNewClinit)
clinitUnits.add(assignStmt);
else
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
}
}
if(addingNewClinit)
clinitUnits.add(Jimple.v().newReturnVoidStmt());
addedGlobalLockDefs = true;
}
int tempNum = 1;
// Iterate through all of the transactions in the current method
Iterator fsIt = fs.iterator();
Stmt assignLocalLockStmt = null;
while(fsIt.hasNext())
{
Transaction tn = ((TransactionFlowPair) fsIt.next()).tn;
if(tn.setNumber == -1)
continue; // this tn should be deleted... for now just skip it!
if(tn.wholeMethod)
{
thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method
}
Local clo = null; // depends on type of locking
LockRegion clr = null; // current lock region
int lockNum = 0;
boolean moreLocks = true;
while(moreLocks)
{
// If this method does not yet have a reference to the lock object
// needed for this transaction, then create one.
if( tn.group.useDynamicLock )
{
Value lock = getLockFor((EquivalentValue) tn.lockObject); // adds local vars and global objects if needed
if(lock instanceof Ref)
{
if(!b.getLocals().contains(lockObj[tn.setNumber]))
b.getLocals().add(lockObj[tn.setNumber]);
assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber], lock);
if(tn.wholeMethod)
units.insertBeforeNoRedirect(assignLocalLockStmt, firstUnit);
else
units.insertBefore(assignLocalLockStmt, tn.entermonitor);
clo = lockObj[tn.setNumber];
}
else if(lock instanceof Local)
clo = (Local) lock;
else
throw new RuntimeException("Unknown type of lock (" + lock + "): expected Ref or Local");
clr = tn;
moreLocks = false;
}
else if( tn.group.useLocksets )
{
Value lock = getLockFor((EquivalentValue) tn.lockset.get(lockNum)); // adds local vars and global objects if needed
if( lock instanceof FieldRef )
{
// add a local variable for this lock
Local lockLocal = Jimple.v().newLocal("locksetObj" + tempNum, RefType.v("java.lang.Object"));
tempNum++;
b.getLocals().add(lockLocal);
// make it refer to the right lock object
assignLocalLockStmt = Jimple.v().newAssignStmt(lockLocal, lock);
if(tn.entermonitor != null)
units.insertBefore(assignLocalLockStmt, tn.entermonitor);
else
units.insertBeforeNoRedirect(assignLocalLockStmt, tn.beginning);
// use it as the lock
clo = lockLocal;
}
else if( lock instanceof Local )
clo = (Local) lock;
else
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local");
if(lockNum + 1 >= tn.lockset.size())
moreLocks = false;
else
moreLocks = true;
if( lockNum > 0 )
{
LockRegion nlr = new LockRegion();
nlr.beginning = clr.beginning;
for (Pair earlyEnd : clr.earlyEnds) {
Stmt earlyExitmonitor = (Stmt) earlyEnd.getO2();
nlr.earlyEnds.add(new Pair(earlyExitmonitor, null)); // <early exitmonitor, null>
}
nlr.last = clr.last; // last stmt before exception handling
if(clr.end != null)
{
Stmt endExitmonitor = (Stmt) clr.end.getO2();
nlr.after = endExitmonitor;
}
clr = nlr;
}
else
clr = tn;
}
else // global lock
{
if(!addedLocalLockObj[tn.setNumber])
b.getLocals().add(lockObj[tn.setNumber]);
addedLocalLockObj[tn.setNumber] = true;
assignLocalLockStmt = Jimple.v().newAssignStmt(lockObj[tn.setNumber],
Jimple.v().newStaticFieldRef(globalLockObj[tn.setNumber].makeRef()));
if(tn.wholeMethod)
units.insertBeforeNoRedirect(assignLocalLockStmt, firstUnit);
else
units.insertBefore(assignLocalLockStmt, tn.entermonitor);
clo = lockObj[tn.setNumber];
clr = tn;
moreLocks = false;
}
// Add synchronization code
// For transactions from synchronized methods, use synchronizeSingleEntrySingleExitBlock()
// to add all necessary code (including ugly exception handling)
// For transactions from synchronized blocks, simply replace the
// monitorenter/monitorexit statements with new ones
if(true)
{
// Remove old prep stmt
if( clr.prepStmt != null )
{
// units.remove(clr.prepStmt);
}
// Reuse old entermonitor or insert new one, and insert prep
Stmt newEntermonitor = Jimple.v().newEnterMonitorStmt(clo);
if( clr.entermonitor != null )
{
units.insertBefore(newEntermonitor, clr.entermonitor);
// redirectTraps(b, clr.entermonitor, newEntermonitor); // EXPERIMENTAL
units.remove(clr.entermonitor);
clr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep);
// clr.prepStmt = newPrep;
}
else
{
units.insertBeforeNoRedirect(newEntermonitor, clr.beginning);
clr.entermonitor = newEntermonitor;
// units.insertBefore(newEntermonitor, newPrep);
// clr.prepStmt = newPrep;
}
// For each early end, reuse or insert exitmonitor stmt
List<Pair> newEarlyEnds = new ArrayList<Pair>();
for (Pair end : clr.earlyEnds) {
Stmt earlyEnd = (Stmt) end.getO1();
Stmt exitmonitor = (Stmt) end.getO2();
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( exitmonitor != null )
{
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL
units.remove(exitmonitor);
newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor));
}
else
{
units.insertBefore(newExitmonitor, earlyEnd);
newEarlyEnds.add(new Pair(earlyEnd, newExitmonitor));
}
}
clr.earlyEnds = newEarlyEnds;
// If fallthrough end, reuse or insert goto and exit
if( clr.after != null )
{
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( clr.end != null )
{
Stmt exitmonitor = (Stmt) clr.end.getO2();
units.insertBefore(newExitmonitor, exitmonitor);
// redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL
units.remove(exitmonitor);
clr.end = new Pair(clr.end.getO1(), newExitmonitor);
}
else
{
units.insertBefore(newExitmonitor, clr.after); // steal jumps to end, send them to monitorexit
Stmt newGotoStmt = Jimple.v().newGotoStmt(clr.after);
units.insertBeforeNoRedirect(newGotoStmt, clr.after);
clr.end = new Pair(newGotoStmt, newExitmonitor);
}
}
// If exceptional end, reuse it, else insert it and traps
Stmt newExitmonitor = Jimple.v().newExitMonitorStmt(clo);
if( clr.exceptionalEnd != null )
{
Stmt exitmonitor = (Stmt) clr.exceptionalEnd.getO2();
if(assignLocalLockStmt != null)
{
Stmt tmp = (Stmt) assignLocalLockStmt.clone();
units.insertBefore(tmp, exitmonitor);
units.insertBefore(newExitmonitor, tmp);
}
else
{
units.insertBefore(newExitmonitor, exitmonitor);
}
// redirectTraps(b, exitmonitor, newExitmonitor); // EXPERIMENTAL
units.remove(exitmonitor);
clr.exceptionalEnd = new Pair(clr.exceptionalEnd.getO1(), newExitmonitor);
}
else
{
// insert after the last end
Stmt lastEnd = null; // last end stmt (not same as last stmt)
if( clr.end != null )
{
lastEnd = (Stmt) clr.end.getO1();
}
else
{
for (Pair earlyEnd : clr.earlyEnds) {
Stmt end = (Stmt) earlyEnd.getO1();
if( lastEnd == null || (units.contains(lastEnd) && units.contains(end) && units.follows(end, lastEnd)) )
lastEnd = end;
}
}
if(clr.last == null)
clr.last = lastEnd; // last stmt and last end are the same
if( lastEnd == null )
throw new RuntimeException("Lock Region has no ends! Where should we put the exception handling???");
// Add throwable
Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable"));
b.getLocals().add(throwableLocal);
// Add stmts
Stmt newCatch = Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef());
units.insertAfter(newCatch, clr.last);
units.insertAfter(newExitmonitor, newCatch);
Stmt newThrow = Jimple.v().newThrowStmt(throwableLocal);
units.insertAfter(newThrow, newExitmonitor);
// Add traps
SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable");
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, clr.beginning, lastEnd, newCatch));
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, newExitmonitor, newThrow, newCatch));
clr.exceptionalEnd = new Pair(newThrow, newExitmonitor);
}
}
/*
else if(tn.wholeMethod)
{
thisMethod.setModifiers( thisMethod.getModifiers() & ~ (Modifier.SYNCHRONIZED) ); // remove synchronized modifier for this method
synchronizeSingleEntrySingleExitBlock(b, (Stmt) firstUnit, (Stmt) lastUnit, (Local) clo);
}
else if(lockNum > 0)
{
// don't have all the info to do this right yet
// synchronizeSingleEntrySingleExitBlock(b, (Stmt) tnbodystart, (Stmt) tnbodyend, (Local) clo);
}
else
{
if(tn.entermonitor == null)
G.v().out.println("ERROR: Transaction has no beginning statement: " + tn.method.toString());
// Deal with entermonitor
Stmt newBegin = Jimple.v().newEnterMonitorStmt(clo);
units.insertBefore(newBegin, tn.entermonitor);
redirectTraps(b, tn.entermonitor, newBegin);
units.remove(tn.entermonitor);
// Deal with exitmonitors
// early
Iterator endsIt = tn.earlyEnds.iterator();
while(endsIt.hasNext())
{
Pair end = (Pair) endsIt.next();
Stmt sEnd = (Stmt) end.getO2();
Stmt newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
}
// exceptional
Stmt sEnd = (Stmt) tn.exceptionalEnd.getO2();
Stmt newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
// fallthrough
sEnd = (Stmt) tn.end.getO2();
newEnd = Jimple.v().newExitMonitorStmt(clo);
units.insertBefore(newEnd, sEnd);
redirectTraps(b, sEnd, newEnd);
units.remove(sEnd);
}
*/
// Replace calls to notify() with calls to notifyAll()
// Replace base object with appropriate lockobj
lockNum++;
}
// deal with waits and notifys
{
Iterator<Object> notifysIt = tn.notifys.iterator();
while(notifysIt.hasNext())
{
Stmt sNotify = (Stmt) notifysIt.next();
Stmt newNotify =
Jimple.v().newInvokeStmt(
Jimple.v().newVirtualInvokeExpr(
clo,
sNotify.getInvokeExpr().getMethodRef().declaringClass().getMethod("void notifyAll()").makeRef(),
Collections.EMPTY_LIST));
if(assignLocalLockStmt != null)
{
Stmt tmp = (Stmt) assignLocalLockStmt.clone();
units.insertBefore(tmp, sNotify);
units.insertBefore(newNotify, tmp);
}
else
units.insertBefore(newNotify, sNotify);
redirectTraps(b, sNotify, newNotify);
units.remove(sNotify);
}
// Replace base object of calls to wait with appropriate lockobj
Iterator<Object> waitsIt = tn.waits.iterator();
while(waitsIt.hasNext())
{
Stmt sWait = (Stmt) waitsIt.next();
((InstanceInvokeExpr) sWait.getInvokeExpr()).setBase(clo); // WHAT IF THIS IS THE WRONG LOCK IN A PAIR OF NESTED LOCKS???
if(assignLocalLockStmt != null)
units.insertBefore((Stmt) assignLocalLockStmt.clone(), sWait);
// Stmt newWait =
// Jimple.v().newInvokeStmt(
// Jimple.v().newVirtualInvokeExpr(
// (Local) clo,
// sWait.getInvokeExpr().getMethodRef().declaringClass().getMethod("void wait()").makeRef(),
// Collections.EMPTY_LIST));
// units.insertBefore(newWait, sWait);
// redirectTraps(b, sWait, newWait);
// units.remove(sWait);
}
}
}
}
static int lockNumber = 0;
static Map<EquivalentValue, StaticFieldRef> lockEqValToLock = new HashMap<EquivalentValue, StaticFieldRef>();
static public Value getLockFor(EquivalentValue lockEqVal)
{
Value lock = lockEqVal.getValue();
if( lock instanceof InstanceFieldRef )
return lock;
if( lock instanceof Local )
return lock;
if( lock instanceof StaticFieldRef )
{
if( lockEqValToLock.containsKey(lockEqVal) )
return lockEqValToLock.get(lockEqVal);
StaticFieldRef sfrLock = (StaticFieldRef) lock;
SootClass lockClass = sfrLock.getField().getDeclaringClass();
SootMethod clinitMethod = null;
JimpleBody clinitBody = null;
Stmt firstStmt = null;
boolean addingNewClinit = !lockClass.declaresMethod("void <clinit>()");
if(addingNewClinit)
{
clinitMethod = new SootMethod("<clinit>", new ArrayList(), VoidType.v(), Modifier.PUBLIC | Modifier.STATIC);
clinitBody = Jimple.v().newBody(clinitMethod);
clinitMethod.setActiveBody(clinitBody);
lockClass.addMethod(clinitMethod);
}
else
{
clinitMethod = lockClass.getMethod("void <clinit>()");
clinitBody = (JimpleBody) clinitMethod.getActiveBody();
firstStmt = clinitBody.getFirstNonIdentityStmt();
}
PatchingChain clinitUnits = clinitBody.getUnits();
Local lockLocal = Jimple.v().newLocal("objectLockLocal" + lockNumber, RefType.v("java.lang.Object"));
// lockNumber is increased below
clinitBody.getLocals().add(lockLocal); // TODO: add name conflict avoidance code
// assign new object to lock obj
Stmt newStmt = Jimple.v().newAssignStmt(lockLocal, Jimple.v().newNewExpr(RefType.v("java.lang.Object")));
if(addingNewClinit)
clinitUnits.add(newStmt);
else
clinitUnits.insertBeforeNoRedirect(newStmt, firstStmt);
// initialize new object
SootClass objectClass = Scene.v().loadClassAndSupport("java.lang.Object");
RefType type = RefType.v(objectClass);
SootMethod initMethod = objectClass.getMethod("void <init>()");
Stmt initStmt = Jimple.v().newInvokeStmt(
Jimple.v().newSpecialInvokeExpr(lockLocal,
initMethod.makeRef(), Collections.EMPTY_LIST));
if(addingNewClinit)
clinitUnits.add(initStmt);
else
clinitUnits.insertBeforeNoRedirect(initStmt, firstStmt);
// copy new object to global static lock object (for use by other fns)
SootField actualLockObject = new SootField("objectLockGlobal" + lockNumber, RefType.v("java.lang.Object"), Modifier.STATIC | Modifier.PUBLIC);
lockNumber++;
lockClass.addField(actualLockObject);
StaticFieldRef actualLockSfr = Jimple.v().newStaticFieldRef(actualLockObject.makeRef());
Stmt assignStmt = Jimple.v().newAssignStmt(actualLockSfr, lockLocal);
if(addingNewClinit)
clinitUnits.add(assignStmt);
else
clinitUnits.insertBeforeNoRedirect(assignStmt, firstStmt);
if(addingNewClinit)
clinitUnits.add(Jimple.v().newReturnVoidStmt());
lockEqValToLock.put(lockEqVal, actualLockSfr);
return actualLockSfr;
}
throw new RuntimeException("Unknown type of lock (" + lock + "): expected FieldRef or Local");
}
/*
public void synchronizeSingleEntrySingleExitBlock(Body b, Stmt start, Stmt end, Local lockObj)
{
PatchingChain units = b.getUnits();
// <existing local defs>
// add a throwable to local vars
Local throwableLocal = Jimple.v().newLocal("throwableLocal" + (throwableNum++), RefType.v("java.lang.Throwable"));
b.getLocals().add(throwableLocal);
// <existing identity refs>
// add entermonitor statement and label0
// Unit label0Unit = start;
Unit labelEnterMonitorStmt = Jimple.v().newEnterMonitorStmt(lockObj);
units.insertBeforeNoRedirect(labelEnterMonitorStmt, start); // steal jumps to start, send them to monitorenter
// <existing code body> check for return statements
List returnUnits = new ArrayList();
if(start != end)
{
Iterator bodyIt = units.iterator(start, end);
while(bodyIt.hasNext())
{
Stmt bodyStmt = (Stmt) bodyIt.next();
if(bodyIt.hasNext()) // ignore the end unit
{
if( bodyStmt instanceof ReturnStmt ||
bodyStmt instanceof ReturnVoidStmt)
{
returnUnits.add(bodyStmt);
}
}
}
}
// add normal flow and labels
Unit labelExitMonitorStmt = (Unit) Jimple.v().newExitMonitorStmt(lockObj);
units.insertBefore(labelExitMonitorStmt, end); // steal jumps to end, send them to monitorexit
// end = (Stmt) units.getSuccOf(end);
Unit label1Unit = (Unit) Jimple.v().newGotoStmt(end);
units.insertBeforeNoRedirect(label1Unit, end);
// end = (Stmt) units.getSuccOf(end);
// add exceptional flow and labels
Unit label2Unit = (Unit) Jimple.v().newIdentityStmt(throwableLocal, Jimple.v().newCaughtExceptionRef());
units.insertBeforeNoRedirect(label2Unit, end);
// end = (Stmt) units.getSuccOf(end);
Unit label3Unit = (Unit) Jimple.v().newExitMonitorStmt(lockObj);
units.insertBeforeNoRedirect(label3Unit, end);
// end = (Stmt) units.getSuccOf(end);
Unit label4Unit = (Unit) Jimple.v().newThrowStmt(throwableLocal);
units.insertBeforeNoRedirect(label4Unit, end);
// end = (Stmt) units.getSuccOf(end);
// <existing end statement>
Iterator returnIt = returnUnits.iterator();
while(returnIt.hasNext())
{
Stmt bodyStmt = (Stmt) returnIt.next();
units.insertBefore(Jimple.v().newExitMonitorStmt(lockObj), bodyStmt); // TODO: WHAT IF IT'S IN A NESTED TRANSACTION???
// Stmt placeholder = Jimple.v().newNopStmt();
// units.insertAfter(Jimple.v().newNopStmt(), label4Unit);
// bodyStmt.redirectJumpsToThisTo(placeholder);
// units.insertBefore(Jimple.v().newGotoStmt(placeholder), bodyStmt);
// units.remove(bodyStmt);
// units.swapWith(placeholder, bodyStmt);
// units.swapWith
}
// add exception routing table
Unit label0Unit = (Unit) units.getSuccOf(labelEnterMonitorStmt);
SootClass throwableClass = Scene.v().loadClassAndSupport("java.lang.Throwable");
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label0Unit, label1Unit, label2Unit));
b.getTraps().addLast(Jimple.v().newTrap(throwableClass, label3Unit, label4Unit, label2Unit));
}
*/
public void redirectTraps(Body b, Unit oldUnit, Unit newUnit)
{
Chain traps = b.getTraps();
Iterator trapsIt = traps.iterator();
while(trapsIt.hasNext())
{
AbstractTrap trap = (AbstractTrap) trapsIt.next();
if(trap.getHandlerUnit() == oldUnit)
trap.setHandlerUnit(newUnit);
if(trap.getBeginUnit() == oldUnit)
trap.setBeginUnit(newUnit);
if(trap.getEndUnit() == oldUnit)
trap.setEndUnit(newUnit);
}
}
}
|
Transactions: bug fixes.
|
src/soot/jimple/toolkits/thread/transaction/TransactionBodyTransformer.java
|
Transactions: bug fixes.
|
|
Java
|
lgpl-2.1
|
8ea575b055e083ec8d1a6b93cb0cf7ce297ef3a2
| 0
|
zhaofengli/QuasselDroid,justjanne/QuasselDroid,schaal/QuasselDroid
|
/**
QuasselDroid - Quassel client for Android
Copyright (C) 2011 Ken Børge Viktil
Copyright (C) 2011 Magnus Fjell
Copyright (C) 2011 Martin Sandsmark <martin.sandsmark@kde.org>
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, or under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License and the
GNU Lesser General Public License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
package com.iskrembilen.quasseldroid.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Observer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import com.iskrembilen.quasseldroid.Buffer;
import com.iskrembilen.quasseldroid.BufferCollection;
import com.iskrembilen.quasseldroid.IrcMessage;
import com.iskrembilen.quasseldroid.IrcUser;
import com.iskrembilen.quasseldroid.R;
import com.iskrembilen.quasseldroid.gui.BufferActivity;
import com.iskrembilen.quasseldroid.gui.LoginActivity;
import com.iskrembilen.quasseldroid.io.CoreConnection;
/**
* This Service holds the connection to the core from the phone, it handles all
* the communication with the core. It talks to CoreConnection
*/
public class CoreConnService extends Service {
private static final String TAG = CoreConnService.class.getSimpleName();
/**
* Id for result code in the resultReciver that is going to notify the
* activity currently on screen about the change
*/
public static final int CONNECTION_DISCONNECTED = 0;
public static final int CONNECTION_CONNECTED = 1;
public static final int NEW_CERTIFICATE = 2;
public static final int UNSUPPORTED_PROTOCOL = 3;
public static final String STATUS_KEY = "status";
public static final String CERT_KEY = "certificate";
private Pattern URLPattern = Pattern.compile("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)", Pattern.CASE_INSENSITIVE);
private CoreConnection coreConn;
private final IBinder binder = new LocalBinder();
Handler incomingHandler;
NotificationManager notifyManager;
ArrayList<ResultReceiver> statusReceivers;
SharedPreferences preferences;
BufferCollection bufferCollection;
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public CoreConnService getService() {
return CoreConnService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void cancelHighlight() {
notifyManager.cancel(R.id.NOTIFICATION_HIGHLIGHT);
}
@Override
public void onCreate() {
super.onCreate();
incomingHandler = new IncomingHandler();
notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
statusReceivers = new ArrayList<ResultReceiver>();
}
@Override
public void onDestroy() {
this.disconnectFromCore();
}
public Handler getHandler() {
return incomingHandler;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
handleIntent(intent);
}
return START_STICKY;
}
/**
* Show a notification while this service is running.
*
* @param connected
* are we connected to a core or not
*/
private void showNotification(boolean connected) {
//TODO: Remove when "leaving" the application
CharSequence text = "";
int temp_flags = 0;
int icon;
if (connected) {
text = getText(R.string.notification_connected);
icon = R.drawable.icon;
temp_flags = Notification.FLAG_ONGOING_EVENT;
} else {
text = getText(R.string.notification_disconnected);
icon = R.drawable.inactive;
temp_flags = Notification.FLAG_ONLY_ALERT_ONCE;
}
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(icon, text, System.currentTimeMillis());
notification.flags |= temp_flags;
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent;
// TODO: Fix so that if a chat is currently on top, launch that one,
// instead of the BufferActivity
if (connected) { // Launch the Buffer Activity.
Intent launch = new Intent(this, BufferActivity.class);
launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
contentIntent = PendingIntent.getActivity(this, 0, launch, 0);
} else {
Intent launch = new Intent(this, LoginActivity.class);
contentIntent = PendingIntent.getActivity(this, 0, launch, 0);
}
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.app_name), text,
contentIntent);
// Send the notification.
notifyManager.notify(R.id.NOTIFICATION, notification);
}
/**
* Handle the data in the intent, and use it to connect with CoreConnect
*
* @param intent
*/
private void handleIntent(Intent intent) {
if (coreConn != null) {
this.disconnectFromCore();
}
Bundle connectData = intent.getExtras();
String address = connectData.getString("address");
int port = connectData.getInt("port");
String username = connectData.getString("username");
String password = connectData.getString("password");
Boolean ssl = connectData.getBoolean("ssl");
Log.i(TAG, "Connecting to core: " + address + ":" + port
+ " with username " + username);
bufferCollection = new BufferCollection();
coreConn = new CoreConnection(address, port, username, password, ssl,
this);
}
// public void newUser(IrcUser user) {
// ircUsers.put(user.nick, user);
// }
//
// public IrcUser getUser(String nick) {
// return ircUsers.get(nick);
// }
//
// public boolean hasUser(String nick) {
// return ircUsers.containsKey(nick);
// }
public void sendMessage(int bufferId, String message) {
coreConn.sendMessage(bufferId, message);
}
public void markBufferAsRead(int bufferId) {
coreConn.requestMarkBufferAsRead(bufferId);
}
public void setLastSeen(int bufferId, int msgId) {
coreConn.requestSetLastMsgRead(bufferId, msgId);
bufferCollection.getBuffer(bufferId).setLastSeenMessage(msgId);
}
public void setMarkerLine(int bufferId, int msgId) {
coreConn.requestSetMarkerLine(bufferId, msgId);
bufferCollection.getBuffer(bufferId).setMarkerLineMessage(msgId);
}
public Buffer getBuffer(int bufferId, Observer obs) {
bufferCollection.getBuffer(bufferId).addObserver(obs);
// coreConn.requestBacklog(bufferId);
return bufferCollection.getBuffer(bufferId);
}
public void getMoreBacklog(int bufferId, int amount){
Log.d(TAG, "Fetching more backlog");
coreConn.requestMoreBacklog(bufferId, amount);
}
public BufferCollection getBufferList(Observer obs) {
if (bufferCollection == null)
return null;
bufferCollection.addObserver(obs);
return bufferCollection;
}
/**
* Checks if there is a highlight in the message and then sets the flag of
* that message to highlight
*
* @param buffer
* the buffer the message belongs to
* @param message
* the message to check
*/
public void checkMessageForHighlight(Buffer buffer, IrcMessage message) {
if (message.type == IrcMessage.Type.Plain) {
String nick = coreConn.getNick(buffer.getInfo().networkId);
if(nick == null) {
Log.e(TAG, "Nick is null in check message for highlight");
return;
} else if(nick.equals("")) return;
Pattern regexHighlight = Pattern.compile(".*(?<!(\\w|\\d))" + coreConn.getNick(buffer.getInfo().networkId) + "(?!(\\w|\\d)).*", Pattern.CASE_INSENSITIVE);
Matcher matcher = regexHighlight.matcher(message.content);
if (matcher.find()) {
message.setFlag(IrcMessage.Flag.Highlight);
// FIXME: move to somewhere proper
}
}
}
/**
* Check if a message contains a URL that we need to support to open in a
* browser Set the url fields in the message so we can get it later
*
* @param message
* ircmessage to check
*/
public void checkForURL(IrcMessage message) {
Matcher matcher = URLPattern.matcher(message.content);
if (matcher.find()) {
message.addURL(this, matcher.group(0));
}
}
/**
* Parse mIRC style codes in IrcMessage
*/
public void parseStyleCodes(IrcMessage message) {
final char boldIndicator = 2;
final char normalIndicator = 15;
final char italicIndicator = 29;
final char underlineIndicator = 31;
String content = message.content.toString();
if (content.indexOf(boldIndicator) == -1
&& content.indexOf(italicIndicator) == -1
&& content.indexOf(underlineIndicator) == -1)
return;
SpannableStringBuilder newString = new SpannableStringBuilder(message.content);
while (true) {
content = newString.toString();
int start = content.indexOf(boldIndicator);
int end = content.indexOf(boldIndicator, start+1);
int style = Typeface.BOLD;
if (start == -1) {
start = content.indexOf(italicIndicator);
end = content.indexOf(italicIndicator, start+1);
style = Typeface.ITALIC;
}
if (start == -1) {
start = content.indexOf(underlineIndicator);
end = content.indexOf(underlineIndicator, start+1);
style = -1;
}
if (start == -1)
break;
if (end == -1)
end = content.indexOf(normalIndicator, start);
if (end == -1)
end = content.length()-1;
if(start==end) {
newString.delete(start, start+1);
break;
}
if (style == -1) {
newString.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} else {
newString.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (content.charAt(end) == boldIndicator
|| content.charAt(end) == italicIndicator
|| content.charAt(end) == normalIndicator
|| content.charAt(end) == underlineIndicator)
newString.delete(end, end+1);
newString.delete(start, start+1);
}
message.content = newString;
}
/**
* Parse mIRC color codes in IrcMessage
*/
public void parseColorCodes(IrcMessage message) {
final char formattingIndicator = 3;
/*
* if (message.content.toString().indexOf(formattingIndicator) == -1)
* return;
*/
String content = message.content.toString();
if (content.indexOf(formattingIndicator) == -1)
return;
SpannableStringBuilder newString = new SpannableStringBuilder(message.content);
while (true) {
content = newString.toString();
// ^C5,12colored text and background^C
int start = content.indexOf(formattingIndicator);
if (start == -1) {
break;
}
int end = start + 1;
int fg = -1;
int bg = -1;
if (end < content.length()) {
if (Character.isDigit(content.charAt(end))) {
if (Character.isDigit(content.charAt(end + 1))) {
fg = Integer.parseInt(content.substring(end, end + 2));
end += 2;
} else {
fg = Integer.parseInt(content.substring(end, end+1));
end += 1;
}
}
if (content.charAt(end) == ',') {
end++;
if (Character.isDigit(content.charAt(end))) {
if (Character.isDigit(content.charAt(end + 1))) {
bg = Integer.parseInt(content.substring(end, end + 2));
end += 2;
} else {
bg = Integer.parseInt(content.substring(end, end + 1));
end += 1;
}
}
}
}
int length = end - start;
int endOfSpan = content.indexOf(formattingIndicator, end) - length;
if (endOfSpan <= 0) // check for malformed messages
endOfSpan = content.length() - length;
newString.delete(start, end);
if (fg != -1) {
newString.setSpan(new ForegroundColorSpan(getResources()
.getColor(mircCodeToColor(fg))), start, endOfSpan,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (bg != -1) {
newString.setSpan(new BackgroundColorSpan(getResources()
.getColor(mircCodeToColor(bg))), start, endOfSpan,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
message.content = newString; // BURN IN HELL JAVA
}
private int mircCodeToColor(int code) {
int color;
switch (code) {
case 0: // white
color = R.color.ircmessage_white;
break;
case 1: // black
color = R.color.ircmessage_black;
break;
case 2: // blue (navy)
color = R.color.ircmessage_blue;
break;
case 3: // green
color = R.color.ircmessage_green;
break;
case 4: // red
color = R.color.ircmessage_red;
break;
case 5: // brown (maroon)
color = R.color.ircmessage_brown;
break;
case 6: // purple
color = R.color.ircmessage_purple;
break;
case 7: // orange (olive)
color = R.color.ircmessage_orange;
break;
case 8: // yellow
color = R.color.ircmessage_yellow;
break;
case 9: // light green (lime)
color = R.color.ircmessage_light_green;
break;
case 10: // teal (a green/blue cyan)
color = R.color.ircmessage_teal;
break;
case 11: // light cyan (cyan) (aqua)
color = R.color.ircmessage_light_cyan;
break;
case 12: // light blue (royal)
color = R.color.ircmessage_light_blue;
break;
case 13: // pink (light purple) (fuchsia)
color = R.color.ircmessage_pink;
break;
case 14: // grey
color = R.color.ircmessage_gray;
break;
default:
color = R.color.ircmessage_normal_color;
}
return color;
}
public void disconnectFromCore() {
notifyManager.cancel(R.id.NOTIFICATION);
if (coreConn != null)
coreConn.disconnect();
}
public boolean isConnected() {
return coreConn.isConnected();
}
/**
* Register a resultReceiver with this server, that will get notification
* when a change happens with the connection to the core Like when the
* connection is lost.
*
* @param resultReceiver
* - Receiver that will get the status updates
*/
public void registerStatusReceiver(ResultReceiver resultReceiver) {
statusReceivers.add(resultReceiver);
if (coreConn != null && coreConn.isConnected()) {
resultReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
} else {
resultReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
}
}
/**
* Unregister a receiver when you don't want any more updates.
*
* @param resultReceiver
*/
public void unregisterStatusReceiver(ResultReceiver resultReceiver) {
statusReceivers.remove(resultReceiver);
}
/**
* Handler of incoming messages from CoreConnection, since it's in another
* read thread.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg == null) {
Log.e(TAG, "Msg was null?");
return;
}
Buffer buffer;
IrcMessage message;
switch (msg.what) {
case R.id.CORECONNECTION_NEW_BACKLOGITEM_TO_SERVICE:
/**
* New message on one buffer so update that buffer with the new
* message
*/
message = (IrcMessage) msg.obj;
buffer = bufferCollection.getBuffer(message.bufferInfo.id);
if (buffer == null) {
Log.e(TAG, "A messages buffer is null:" + message);
return;
}
if (!buffer.hasMessage(message)) {
/**
* Check if we are highlighted in the message, TODO: Add
* support for custom highlight masks
*/
checkMessageForHighlight(buffer, message);
checkForURL(message);
parseColorCodes(message);
parseStyleCodes(message);
buffer.addBacklogMessage(message);
} else {
Log.e(TAG, "Getting message buffer already have " + buffer.getInfo().name);
}
break;
case R.id.CORECONNECTION_NEW_MESSAGE_TO_SERVICE:
/**
* New message on one buffer so update that buffer with the new
* message
*/
message = (IrcMessage) msg.obj;
buffer = bufferCollection.getBuffer(message.bufferInfo.id);
if (buffer == null) {
Log.e(TAG, "A messages buffer is null: " + message);
return;
}
if (!buffer.hasMessage(message)) {
/**
* Check if we are highlighted in the message, TODO: Add
* support for custom highlight masks
*/
checkMessageForHighlight(buffer, message);
parseColorCodes(message);
parseStyleCodes(message);
if (message.isHighlighted()) {
// Create a notification about the highlight
String text = buffer.getInfo().name + ": <" + message.getNick() + "> " + message.content;
Notification notification = new Notification(R.drawable.highlight, text, System.currentTimeMillis());
Intent launch = new Intent(CoreConnService.this, BufferActivity.class);
launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(CoreConnService.this, 0, launch, 0);
// Set the info for the views that show in the
// notification panel.
notification.setLatestEventInfo(CoreConnService.this, getText(R.string.app_name), text, contentIntent);
// Send the notification.
notifyManager.notify(R.id.NOTIFICATION_HIGHLIGHT, notification);
}
checkForURL(message);
buffer.addMessage(message);
} else {
Log.e(TAG, "Getting message buffer already have " + buffer.toString());
}
break;
case R.id.CORECONNECTION_NEW_BUFFER_TO_SERVICE:
/**
* New buffer received, so update out channel holder with the
* new buffer
*/
buffer = (Buffer) msg.obj;
bufferCollection.addBuffer(buffer);
break;
case R.id.CORECONNECTION_ADD_MULTIPLE_BUFFERS:
/**
* Complete list of buffers received
*/
bufferCollection.addBuffers((Collection<Buffer>) msg.obj);
break;
case R.id.CORECONNECTION_SET_LAST_SEEN_TO_SERVICE:
/**
* Setting last seen message id in a buffer
*/
if (bufferCollection.hasBuffer(msg.arg1)) {
bufferCollection.getBuffer(msg.arg1).setLastSeenMessage(msg.arg2);
} else {
Log.e(TAG, "Getting set last seen message on unknown buffer: " + msg.arg1);
}
break;
case R.id.CORECONNECTION_SET_MARKERLINE_TO_SERVICE:
/**
* Setting marker line message id in a buffer
*/
if (bufferCollection.hasBuffer(msg.arg1)) {
bufferCollection.getBuffer(msg.arg1).setMarkerLineMessage(msg.arg2);
} else {
Log.e(TAG, "Getting set marker line message on unknown buffer: " + msg.arg1);
}
break;
case R.id.CORECONNECTION_CONNECTED:
/**
* CoreConn has connected to a core
*/
showNotification(true);
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
}
break;
case R.id.CORECONNECTION_LOST_CONNECTION:
/**
* Lost connection with core, update notification
*/
for (ResultReceiver statusReceiver : statusReceivers) {
if (msg.obj != null) { // Have description of what is wrong,
// used only for login atm
Bundle bundle = new Bundle();
bundle.putString(CoreConnService.STATUS_KEY, (String) msg.obj);
statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, bundle);
} else {
statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
}
}
showNotification(false);
break;
// case R.id.CORECONNECTION_NEW_USERLIST_ADDED:
// /**
// * Initial list of users
// */
// ArrayList<IrcUser> users = (ArrayList<IrcUser>) msg.obj;
// for (IrcUser user : users) {
// newUser(user);
// }
// break;
case R.id.CORECONNECTION_NEW_USER_ADDED:
/**
* New IrcUser added
*/
// IrcUser user = (IrcUser) msg.obj;
// newUser(user);
break;
case R.id.CORECONNECTION_SET_BUFFER_ORDER:
/**
* Buffer order changed so set the new one
*/
bufferCollection.getBuffer(msg.arg1).setOrder(msg.arg2);
break;
case R.id.CORECONNECTION_SET_BUFFER_TEMP_HIDDEN:
/**
* Buffer has been marked as temporary hidden, update buffer
*/
bufferCollection.getBuffer(msg.arg1).setTemporarilyHidden((Boolean) msg.obj);
break;
case R.id.CORECONNECTION_SET_BUFFER_PERM_HIDDEN:
/**
* Buffer has been marked as permanently hidden, update buffer
*/
bufferCollection.getBuffer(msg.arg1).setPermanentlyHidden((Boolean) msg.obj);
break;
case R.id.CORECONNECTION_INVALID_CERTIFICATE:
/**
* Received a mismatching certificate
*/
case R.id.CORECONNECTION_NEW_CERTIFICATE:
/**
* Received a new, unseen certificate
*/
Bundle bundle = new Bundle();
bundle.putString(CERT_KEY, (String) msg.obj);
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.NEW_CERTIFICATE, bundle);
}
break;
case R.id.CORECONNECTION_SET_BUFFER_ACTIVE:
/**
* Set buffer as active or parted
*/
bufferCollection.getBuffer(msg.arg1).setActive((Boolean)msg.obj);
break;
case R.id.CORECONNECTION_UNSUPPORTED_PROTOCOL:
/**
* The protocol version of the core is not supported so tell user it is to old
*/
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.UNSUPPORTED_PROTOCOL, null);
}
}
}
}
}
|
src/com/iskrembilen/quasseldroid/service/CoreConnService.java
|
/**
QuasselDroid - Quassel client for Android
Copyright (C) 2011 Ken Børge Viktil
Copyright (C) 2011 Magnus Fjell
Copyright (C) 2011 Martin Sandsmark <martin.sandsmark@kde.org>
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, or under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License and the
GNU Lesser General Public License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
package com.iskrembilen.quasseldroid.service;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Observer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import com.iskrembilen.quasseldroid.Buffer;
import com.iskrembilen.quasseldroid.BufferCollection;
import com.iskrembilen.quasseldroid.IrcMessage;
import com.iskrembilen.quasseldroid.IrcUser;
import com.iskrembilen.quasseldroid.R;
import com.iskrembilen.quasseldroid.gui.BufferActivity;
import com.iskrembilen.quasseldroid.gui.LoginActivity;
import com.iskrembilen.quasseldroid.io.CoreConnection;
/**
* This Service holds the connection to the core from the phone, it handles all
* the communication with the core. It talks to CoreConnection
*/
public class CoreConnService extends Service {
private static final String TAG = CoreConnService.class.getSimpleName();
/**
* Id for result code in the resultReciver that is going to notify the
* activity currently on screen about the change
*/
public static final int CONNECTION_DISCONNECTED = 0;
public static final int CONNECTION_CONNECTED = 1;
public static final int NEW_CERTIFICATE = 2;
public static final int UNSUPPORTED_PROTOCOL = 3;
public static final String STATUS_KEY = "status";
public static final String CERT_KEY = "certificate";
private Pattern URLPattern = Pattern.compile("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)", Pattern.CASE_INSENSITIVE);
private CoreConnection coreConn;
private final IBinder binder = new LocalBinder();
Handler incomingHandler;
NotificationManager notifyManager;
ArrayList<ResultReceiver> statusReceivers;
SharedPreferences preferences;
BufferCollection bufferCollection;
/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public CoreConnService getService() {
return CoreConnService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public void cancelHighlight() {
notifyManager.cancel(R.id.NOTIFICATION_HIGHLIGHT);
}
@Override
public void onCreate() {
super.onCreate();
incomingHandler = new IncomingHandler();
notifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
statusReceivers = new ArrayList<ResultReceiver>();
}
@Override
public void onDestroy() {
this.disconnectFromCore();
}
public Handler getHandler() {
return incomingHandler;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
handleIntent(intent);
}
return START_STICKY;
}
/**
* Show a notification while this service is running.
*
* @param connected
* are we connected to a core or not
*/
private void showNotification(boolean connected) {
//TODO: Remove when "leaving" the application
CharSequence text = "";
int temp_flags = 0;
int icon;
if (connected) {
text = getText(R.string.notification_connected);
icon = R.drawable.icon;
temp_flags = Notification.FLAG_ONGOING_EVENT;
} else {
text = getText(R.string.notification_disconnected);
icon = R.drawable.inactive;
temp_flags = Notification.FLAG_ONLY_ALERT_ONCE;
}
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(icon, text, System.currentTimeMillis());
notification.flags |= temp_flags;
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent;
// TODO: Fix so that if a chat is currently on top, launch that one,
// instead of the BufferActivity
if (connected) { // Launch the Buffer Activity.
Intent launch = new Intent(this, BufferActivity.class);
launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
contentIntent = PendingIntent.getActivity(this, 0, launch, 0);
} else {
Intent launch = new Intent(this, LoginActivity.class);
contentIntent = PendingIntent.getActivity(this, 0, launch, 0);
}
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.app_name), text,
contentIntent);
// Send the notification.
notifyManager.notify(R.id.NOTIFICATION, notification);
}
/**
* Handle the data in the intent, and use it to connect with CoreConnect
*
* @param intent
*/
private void handleIntent(Intent intent) {
if (coreConn != null) {
this.disconnectFromCore();
}
Bundle connectData = intent.getExtras();
String address = connectData.getString("address");
int port = connectData.getInt("port");
String username = connectData.getString("username");
String password = connectData.getString("password");
Boolean ssl = connectData.getBoolean("ssl");
Log.i(TAG, "Connecting to core: " + address + ":" + port
+ " with username " + username);
bufferCollection = new BufferCollection();
coreConn = new CoreConnection(address, port, username, password, ssl,
this);
}
// public void newUser(IrcUser user) {
// ircUsers.put(user.nick, user);
// }
//
// public IrcUser getUser(String nick) {
// return ircUsers.get(nick);
// }
//
// public boolean hasUser(String nick) {
// return ircUsers.containsKey(nick);
// }
public void sendMessage(int bufferId, String message) {
coreConn.sendMessage(bufferId, message);
}
public void markBufferAsRead(int bufferId) {
coreConn.requestMarkBufferAsRead(bufferId);
}
public void setLastSeen(int bufferId, int msgId) {
coreConn.requestSetLastMsgRead(bufferId, msgId);
bufferCollection.getBuffer(bufferId).setLastSeenMessage(msgId);
}
public void setMarkerLine(int bufferId, int msgId) {
coreConn.requestSetMarkerLine(bufferId, msgId);
bufferCollection.getBuffer(bufferId).setMarkerLineMessage(msgId);
}
public Buffer getBuffer(int bufferId, Observer obs) {
bufferCollection.getBuffer(bufferId).addObserver(obs);
// coreConn.requestBacklog(bufferId);
return bufferCollection.getBuffer(bufferId);
}
public void getMoreBacklog(int bufferId, int amount){
Log.d(TAG, "Fetching more backlog");
coreConn.requestMoreBacklog(bufferId, amount);
}
public BufferCollection getBufferList(Observer obs) {
if (bufferCollection == null)
return null;
bufferCollection.addObserver(obs);
return bufferCollection;
}
/**
* Handler of incoming messages from CoreConnection, since it's in another
* read thread.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg == null) {
Log.e(TAG, "Msg was null?");
return;
}
Buffer buffer;
IrcMessage message;
switch (msg.what) {
case R.id.CORECONNECTION_NEW_BACKLOGITEM_TO_SERVICE:
/**
* New message on one buffer so update that buffer with the new
* message
*/
message = (IrcMessage) msg.obj;
buffer = bufferCollection.getBuffer(message.bufferInfo.id);
if (buffer == null) {
Log.e(TAG, "A messages buffer is null:" + message);
return;
}
if (!buffer.hasMessage(message)) {
/**
* Check if we are highlighted in the message, TODO: Add
* support for custom highlight masks
*/
checkMessageForHighlight(buffer, message);
checkForURL(message);
parseColorCodes(message);
parseStyleCodes(message);
buffer.addBacklogMessage(message);
} else {
Log.e(TAG, "Getting message buffer already have " + buffer.getInfo().name);
}
break;
case R.id.CORECONNECTION_NEW_MESSAGE_TO_SERVICE:
/**
* New message on one buffer so update that buffer with the new
* message
*/
message = (IrcMessage) msg.obj;
buffer = bufferCollection.getBuffer(message.bufferInfo.id);
if (buffer == null) {
Log.e(TAG, "A messages buffer is null: " + message);
return;
}
if (!buffer.hasMessage(message)) {
/**
* Check if we are highlighted in the message, TODO: Add
* support for custom highlight masks
*/
checkMessageForHighlight(buffer, message);
parseColorCodes(message);
parseStyleCodes(message);
if (message.isHighlighted()) {
// Create a notification about the highlight
String text = buffer.getInfo().name + ": <" + message.getNick() + "> " + message.content;
Notification notification = new Notification(R.drawable.highlight, text, System.currentTimeMillis());
Intent launch = new Intent(CoreConnService.this, BufferActivity.class);
launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(CoreConnService.this, 0, launch, 0);
// Set the info for the views that show in the
// notification panel.
notification.setLatestEventInfo(CoreConnService.this, getText(R.string.app_name), text, contentIntent);
// Send the notification.
notifyManager.notify(R.id.NOTIFICATION_HIGHLIGHT, notification);
}
checkForURL(message);
buffer.addMessage(message);
} else {
Log.e(TAG, "Getting message buffer already have " + buffer.toString());
}
break;
case R.id.CORECONNECTION_NEW_BUFFER_TO_SERVICE:
/**
* New buffer received, so update out channel holder with the
* new buffer
*/
buffer = (Buffer) msg.obj;
bufferCollection.addBuffer(buffer);
break;
case R.id.CORECONNECTION_ADD_MULTIPLE_BUFFERS:
/**
* Complete list of buffers received
*/
bufferCollection.addBuffers((Collection<Buffer>) msg.obj);
break;
case R.id.CORECONNECTION_SET_LAST_SEEN_TO_SERVICE:
/**
* Setting last seen message id in a buffer
*/
if (bufferCollection.hasBuffer(msg.arg1)) {
bufferCollection.getBuffer(msg.arg1).setLastSeenMessage(msg.arg2);
} else {
Log.e(TAG, "Getting set last seen message on unknown buffer: " + msg.arg1);
}
break;
case R.id.CORECONNECTION_SET_MARKERLINE_TO_SERVICE:
/**
* Setting marker line message id in a buffer
*/
if (bufferCollection.hasBuffer(msg.arg1)) {
bufferCollection.getBuffer(msg.arg1).setMarkerLineMessage(msg.arg2);
} else {
Log.e(TAG, "Getting set marker line message on unknown buffer: " + msg.arg1);
}
break;
case R.id.CORECONNECTION_CONNECTED:
/**
* CoreConn has connected to a core
*/
showNotification(true);
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
}
break;
case R.id.CORECONNECTION_LOST_CONNECTION:
/**
* Lost connection with core, update notification
*/
for (ResultReceiver statusReceiver : statusReceivers) {
if (msg.obj != null) { // Have description of what is wrong,
// used only for login atm
Bundle bundle = new Bundle();
bundle.putString(CoreConnService.STATUS_KEY, (String) msg.obj);
statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, bundle);
} else {
statusReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
}
}
showNotification(false);
break;
// case R.id.CORECONNECTION_NEW_USERLIST_ADDED:
// /**
// * Initial list of users
// */
// ArrayList<IrcUser> users = (ArrayList<IrcUser>) msg.obj;
// for (IrcUser user : users) {
// newUser(user);
// }
// break;
case R.id.CORECONNECTION_NEW_USER_ADDED:
/**
* New IrcUser added
*/
// IrcUser user = (IrcUser) msg.obj;
// newUser(user);
break;
case R.id.CORECONNECTION_SET_BUFFER_ORDER:
/**
* Buffer order changed so set the new one
*/
bufferCollection.getBuffer(msg.arg1).setOrder(msg.arg2);
break;
case R.id.CORECONNECTION_SET_BUFFER_TEMP_HIDDEN:
/**
* Buffer has been marked as temporary hidden, update buffer
*/
bufferCollection.getBuffer(msg.arg1).setTemporarilyHidden((Boolean) msg.obj);
break;
case R.id.CORECONNECTION_SET_BUFFER_PERM_HIDDEN:
/**
* Buffer has been marked as permanently hidden, update buffer
*/
bufferCollection.getBuffer(msg.arg1).setPermanentlyHidden((Boolean) msg.obj);
break;
case R.id.CORECONNECTION_INVALID_CERTIFICATE:
/**
* Received a mismatching certificate
*/
case R.id.CORECONNECTION_NEW_CERTIFICATE:
/**
* Received a new, unseen certificate
*/
Bundle bundle = new Bundle();
bundle.putString(CERT_KEY, (String) msg.obj);
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.NEW_CERTIFICATE, bundle);
}
break;
case R.id.CORECONNECTION_SET_BUFFER_ACTIVE:
/**
* Set buffer as active or parted
*/
bufferCollection.getBuffer(msg.arg1).setActive((Boolean)msg.obj);
break;
case R.id.CORECONNECTION_UNSUPPORTED_PROTOCOL:
/**
* The protocol version of the core is not supported so tell user it is to old
*/
for (ResultReceiver statusReceiver : statusReceivers) {
statusReceiver.send(CoreConnService.UNSUPPORTED_PROTOCOL, null);
}
}
}
}
/**
* Checks if there is a highlight in the message and then sets the flag of
* that message to highlight
*
* @param buffer
* the buffer the message belongs to
* @param message
* the message to check
*/
public void checkMessageForHighlight(Buffer buffer, IrcMessage message) {
if (message.type == IrcMessage.Type.Plain) {
String nick = coreConn.getNick(buffer.getInfo().networkId);
if(nick == null) {
Log.e(TAG, "Nick is null in check message for highlight");
return;
} else if(nick.equals("")) return;
Pattern regexHighlight = Pattern.compile(".*(?<!(\\w|\\d))" + coreConn.getNick(buffer.getInfo().networkId) + "(?!(\\w|\\d)).*", Pattern.CASE_INSENSITIVE);
Matcher matcher = regexHighlight.matcher(message.content);
if (matcher.find()) {
message.setFlag(IrcMessage.Flag.Highlight);
// FIXME: move to somewhere proper
}
}
}
/**
* Check if a message contains a URL that we need to support to open in a
* browser Set the url fields in the message so we can get it later
*
* @param message
* ircmessage to check
*/
public void checkForURL(IrcMessage message) {
Matcher matcher = URLPattern.matcher(message.content);
if (matcher.find()) {
message.addURL(this, matcher.group(0));
}
}
/**
* Parse mIRC style codes in IrcMessage
*/
public void parseStyleCodes(IrcMessage message) {
final char boldIndicator = 2;
final char normalIndicator = 15;
final char italicIndicator = 29;
final char underlineIndicator = 31;
String content = message.content.toString();
if (content.indexOf(boldIndicator) == -1
&& content.indexOf(italicIndicator) == -1
&& content.indexOf(underlineIndicator) == -1)
return;
SpannableStringBuilder newString = new SpannableStringBuilder(message.content);
while (true) {
content = newString.toString();
int start = content.indexOf(boldIndicator);
int end = content.indexOf(boldIndicator, start+1);
int style = Typeface.BOLD;
if (start == -1) {
start = content.indexOf(italicIndicator);
end = content.indexOf(italicIndicator, start+1);
style = Typeface.ITALIC;
}
if (start == -1) {
start = content.indexOf(underlineIndicator);
end = content.indexOf(underlineIndicator, start+1);
style = -1;
}
if (start == -1)
break;
if (end == -1)
end = content.indexOf(normalIndicator, start);
if (end == -1)
end = content.length()-1;
if(start==end) {
newString.delete(start, start+1);
break;
}
if (style == -1) {
newString.setSpan(new UnderlineSpan(), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
} else {
newString.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (content.charAt(end) == boldIndicator
|| content.charAt(end) == italicIndicator
|| content.charAt(end) == normalIndicator
|| content.charAt(end) == underlineIndicator)
newString.delete(end, end+1);
newString.delete(start, start+1);
}
message.content = newString;
}
/**
* Parse mIRC color codes in IrcMessage
*/
public void parseColorCodes(IrcMessage message) {
final char formattingIndicator = 3;
/*
* if (message.content.toString().indexOf(formattingIndicator) == -1)
* return;
*/
String content = message.content.toString();
if (content.indexOf(formattingIndicator) == -1)
return;
SpannableStringBuilder newString = new SpannableStringBuilder(message.content);
while (true) {
content = newString.toString();
// ^C5,12colored text and background^C
int start = content.indexOf(formattingIndicator);
if (start == -1) {
break;
}
int end = start + 1;
int fg = -1;
int bg = -1;
if (end < content.length()) {
if (Character.isDigit(content.charAt(end))) {
if (Character.isDigit(content.charAt(end + 1))) {
fg = Integer.parseInt(content.substring(end, end + 2));
end += 2;
} else {
fg = Integer.parseInt(content.substring(end, end+1));
end += 1;
}
}
if (content.charAt(end) == ',') {
end++;
if (Character.isDigit(content.charAt(end))) {
if (Character.isDigit(content.charAt(end + 1))) {
bg = Integer.parseInt(content.substring(end, end + 2));
end += 2;
} else {
bg = Integer.parseInt(content.substring(end, end + 1));
end += 1;
}
}
}
}
int length = end - start;
int endOfSpan = content.indexOf(formattingIndicator, end) - length;
if (endOfSpan <= 0) // check for malformed messages
endOfSpan = content.length() - length;
newString.delete(start, end);
if (fg != -1) {
newString.setSpan(new ForegroundColorSpan(getResources()
.getColor(mircCodeToColor(fg))), start, endOfSpan,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (bg != -1) {
newString.setSpan(new BackgroundColorSpan(getResources()
.getColor(mircCodeToColor(bg))), start, endOfSpan,
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
message.content = newString; // BURN IN HELL JAVA
}
private int mircCodeToColor(int code) {
int color;
switch (code) {
case 0: // white
color = R.color.ircmessage_white;
break;
case 1: // black
color = R.color.ircmessage_black;
break;
case 2: // blue (navy)
color = R.color.ircmessage_blue;
break;
case 3: // green
color = R.color.ircmessage_green;
break;
case 4: // red
color = R.color.ircmessage_red;
break;
case 5: // brown (maroon)
color = R.color.ircmessage_brown;
break;
case 6: // purple
color = R.color.ircmessage_purple;
break;
case 7: // orange (olive)
color = R.color.ircmessage_orange;
break;
case 8: // yellow
color = R.color.ircmessage_yellow;
break;
case 9: // light green (lime)
color = R.color.ircmessage_light_green;
break;
case 10: // teal (a green/blue cyan)
color = R.color.ircmessage_teal;
break;
case 11: // light cyan (cyan) (aqua)
color = R.color.ircmessage_light_cyan;
break;
case 12: // light blue (royal)
color = R.color.ircmessage_light_blue;
break;
case 13: // pink (light purple) (fuchsia)
color = R.color.ircmessage_pink;
break;
case 14: // grey
color = R.color.ircmessage_gray;
break;
default:
color = R.color.ircmessage_normal_color;
}
return color;
}
public void disconnectFromCore() {
notifyManager.cancel(R.id.NOTIFICATION);
if (coreConn != null)
coreConn.disconnect();
}
public boolean isConnected() {
return coreConn.isConnected();
}
/**
* Register a resultReceiver with this server, that will get notification
* when a change happens with the connection to the core Like when the
* connection is lost.
*
* @param resultReceiver
* - Receiver that will get the status updates
*/
public void registerStatusReceiver(ResultReceiver resultReceiver) {
statusReceivers.add(resultReceiver);
if (coreConn != null && coreConn.isConnected()) {
resultReceiver.send(CoreConnService.CONNECTION_CONNECTED, null);
} else {
resultReceiver.send(CoreConnService.CONNECTION_DISCONNECTED, null);
}
}
/**
* Unregister a receiver when you don't want any more updates.
*
* @param resultReceiver
*/
public void unregisterStatusReceiver(ResultReceiver resultReceiver) {
statusReceivers.remove(resultReceiver);
}
}
|
moved service handler to bottom of class for readability
|
src/com/iskrembilen/quasseldroid/service/CoreConnService.java
|
moved service handler to bottom of class for readability
|
|
Java
|
unlicense
|
ad547e56c3e6bfe36eebfdb7d6561b0b3fd9fe47
| 0
|
Kramermp/FoodMood
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package foodprofile.view;
import foodmood.controller.NavigationCntl;
import foodprofile.controller.FoodCntl;
import foodprofile.model.Food;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.*;
/**
*
* @author mpk5206
*/
public class FoodUI extends JFrame{
private Food theFoodModel;
private JFrame frame = new JFrame("Food");
private FoodCntl parentCntl;
private JLabel foodName;
private JTextField foodInput;
private JLabel foodGroup;
private JComboBox foodGroupInput;
private JLabel date;
private JTextField dateInput;
private JLabel time;
private JTextField timeInput;
private JButton submit;
private JComboBox monthsBox;
private JComboBox daysBox;
private JButton listButton;
private JButton homeButton;
private JButton deleteButton;
/**
* Default Constructor for empty FoodView
* @param parentController the parentController
*/
public FoodUI(FoodCntl foodController) {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.parentCntl = foodController;
initializeComponents();
}
private void initializeComponents() {
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(null);
homeButton = new JButton("Home");
homeButton.setBounds(50, 50, 80, 25);
frame.add(homeButton);
date = new JLabel("Date:");
date.setBounds(100, 75, 80, 25);
frame.add(date);
//The text field option for date
// dateInput = new JTextField(50);
// dateInput.setBounds(200, 75, 80, 25);
// frame.add(dateInput);
//Makes the date drop downs to elliminate user entering error
String[] months = new String[12];
for (int i = 0; i < 12; i++) {
months[i] = (i+1)+"";
}
String[] days = new String[31];
for (int i = 0; i < 31; i++) {
days[i] = (i+1)+"";
}
JPanel dateInputPanel = new JPanel();
dateInputPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
monthsBox = new JComboBox(months);
dateInputPanel.add(monthsBox);
JLabel slash = new JLabel("/");
dateInputPanel.add(slash);
daysBox = new JComboBox(days);
dateInputPanel.add(daysBox);
dateInputPanel.setBounds(200, 75, 180, 25);
frame.add(dateInputPanel);
time = new JLabel("Time:");
time.setBounds(100, 100, 80, 25);
frame.add(time);
timeInput = new JTextField(50);
timeInput.setBounds(200, 100, 80, 25);
frame.add(timeInput);
foodGroup = new JLabel("Food Group:");
foodGroup.setBounds(100, 125, 80, 25);
frame.add(foodGroup);
String[] foodGroupOptions = {"Dairy", "Fruits", "Grains", "Protein", "Vegetables"};
foodGroupInput = new JComboBox(foodGroupOptions);
foodGroupInput.setBounds(200, 125, 100, 25);
frame.add(foodGroupInput);
foodName = new JLabel("Food:");
foodName.setBounds(100, 150, 80, 25);
frame.add(foodName);
foodInput = new JTextField(50);
foodInput.setBounds(200, 150, 100, 50);
frame.add(foodInput);
submit = new JButton("Submit");
submit.setBounds(150, 250, 80, 25);
frame.add(submit);
listButton = new JButton("Food List");
listButton.setBounds(300, 250, 180, 25);
frame.add(listButton);
frame.setVisible(true);
// dateInput.addActionListener((ActionEvent ae) -> {
// System.out.println("DateInput event triggered.");
// });
timeInput.addActionListener((ActionEvent ae) -> {
System.out.println("TimeInput event triggered.");
});
foodGroupInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodGroupInput event triggered.");
});
foodInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodInput event triggered.");
});
submit.addActionListener((ActionEvent ae) -> {
String name = foodInput.getText();
String category = foodGroupInput.getSelectedItem().toString();
int month = Integer.parseInt(monthsBox.getSelectedItem().toString());
int day = Integer.parseInt(daysBox.getSelectedItem().toString());
GregorianCalendar time = new GregorianCalendar(2017, month, day);
parentCntl.addFood(name, category, time);
});
listButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goListView();
});
homeButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goHome();
});
}
private void exit() {
}
/**
* Creates a FoodView of the provided FoodProfile
* @param foodProfile the source foodprofile
* @param parentController the parent controller
*/
public FoodUI(FoodCntl parentController, Food food) {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.parentCntl = parentController;
this.theFoodModel = food;
initView();
}
public void initView(){
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(null);
date = new JLabel("Date:");
date.setBounds(100, 75, 80, 25);
frame.add(date);
//The text field option for date
// dateInput = new JTextField(50);
// dateInput.setBounds(200, 75, 80, 25);
// frame.add(dateInput);
//Makes the date drop downs to elliminate user entering error
String[] months = new String[13];
for (int i = 1; i < 12; i++) {
months[i] = (i)+"";
}
months[0] = theFoodModel.getTime().getTime().getMonth()+"";
String[] days = new String[32];
for (int i = 1; i < 31; i++) {
days[i] = (i)+"";
}
days[0] = theFoodModel.getTime().getTime().getDate()+"";
JPanel dateInputPanel = new JPanel();
dateInputPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
monthsBox = new JComboBox(months);
dateInputPanel.add(monthsBox);
JLabel slash = new JLabel("/");
dateInputPanel.add(slash);
daysBox = new JComboBox(days);
dateInputPanel.add(daysBox);
dateInputPanel.setBounds(200, 75, 180, 25);
frame.add(dateInputPanel);
time = new JLabel("Time:");
time.setBounds(100, 100, 80, 25);
frame.add(time);
timeInput = new JTextField(50);
timeInput.setBounds(200, 100, 80, 25);
frame.add(timeInput);
foodGroup = new JLabel("Food Group:");
foodGroup.setBounds(100, 125, 80, 25);
frame.add(foodGroup);
String[] foodGroupOptions = {theFoodModel.getFoodCategories().get(0), "Dairy", "Fruits", "Grains", "Protein", "Vegetables"};
foodGroupInput = new JComboBox(foodGroupOptions);
foodGroupInput.setBounds(200, 125, 100, 25);
frame.add(foodGroupInput);
foodName = new JLabel("Food:");
foodName.setBounds(100, 150, 80, 25);
frame.add(foodName);
foodInput = new JTextField(50);
foodInput.setText(theFoodModel.getName());
foodInput.setBounds(200, 150, 100, 50);
frame.add(foodInput);
submit = new JButton("Update");
submit.setBounds(150, 250, 80, 25);
frame.add(submit);
listButton = new JButton("Food List");
listButton.setBounds(300, 250, 180, 25);
frame.add(listButton);
deleteButton = new JButton("Delete");
deleteButton.setBounds(50, 250, 80, 25);
frame.add(deleteButton);
frame.setVisible(true);
// dateInput.addActionListener((ActionEvent ae) -> {
// System.out.println("DateInput event triggered.");
// });
timeInput.addActionListener((ActionEvent ae) -> {
System.out.println("TimeInput event triggered.");
});
foodGroupInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodGroupInput event triggered.");
});
foodInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodInput event triggered.");
});
submit.addActionListener((ActionEvent ae) -> {
String name = foodInput.getText();
String category = foodGroupInput.getSelectedItem().toString();
int month = Integer.parseInt(monthsBox.getSelectedItem().toString());
int day = Integer.parseInt(daysBox.getSelectedItem().toString());
GregorianCalendar time = new GregorianCalendar(2017, month, day);
theFoodModel.setFoodCategory(category);
theFoodModel.setName(name);
theFoodModel.setTime(time);
parentCntl.updateFood(theFoodModel);
});
listButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goListView();
});
deleteButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.deleteFood(theFoodModel);
parentCntl.goListView();
});
}
}
|
src/foodprofile/view/FoodUI.java
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package foodprofile.view;
import foodmood.controller.NavigationCntl;
import foodprofile.controller.FoodCntl;
import foodprofile.model.Food;
import foodprofile.model.FoodProfileModel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.*;
/**
*
* @author mpk5206
*/
public class FoodUI extends JFrame{
private Food theFoodModel;
private JFrame frame = new JFrame("Food");
private FoodCntl parentCntl;
private JLabel foodName;
private JTextField foodInput;
private JLabel foodGroup;
private JComboBox foodGroupInput;
private JLabel date;
private JTextField dateInput;
private JLabel time;
private JTextField timeInput;
private JButton submit;
private JComboBox monthsBox;
private JComboBox daysBox;
private JButton listButton;
private JButton homeButton;
private JButton deleteButton;
/**
* Default Constructor for empty FoodView
* @param parentController the parentController
*/
public FoodUI(FoodCntl foodController) {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.parentCntl = foodController;
initializeComponents();
}
private void initializeComponents() {
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(null);
homeButton = new JButton("Home");
homeButton.setBounds(50, 50, 80, 25);
frame.add(homeButton);
date = new JLabel("Date:");
date.setBounds(100, 75, 80, 25);
frame.add(date);
//The text field option for date
// dateInput = new JTextField(50);
// dateInput.setBounds(200, 75, 80, 25);
// frame.add(dateInput);
//Makes the date drop downs to elliminate user entering error
String[] months = new String[12];
for (int i = 0; i < 12; i++) {
months[i] = (i+1)+"";
}
String[] days = new String[31];
for (int i = 0; i < 31; i++) {
days[i] = (i+1)+"";
}
JPanel dateInputPanel = new JPanel();
dateInputPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
monthsBox = new JComboBox(months);
dateInputPanel.add(monthsBox);
JLabel slash = new JLabel("/");
dateInputPanel.add(slash);
daysBox = new JComboBox(days);
dateInputPanel.add(daysBox);
dateInputPanel.setBounds(200, 75, 180, 25);
frame.add(dateInputPanel);
time = new JLabel("Time:");
time.setBounds(100, 100, 80, 25);
frame.add(time);
timeInput = new JTextField(50);
timeInput.setBounds(200, 100, 80, 25);
frame.add(timeInput);
foodGroup = new JLabel("Food Group:");
foodGroup.setBounds(100, 125, 80, 25);
frame.add(foodGroup);
String[] foodGroupOptions = {"Dairy", "Fruits", "Grains", "Protein", "Vegetables"};
foodGroupInput = new JComboBox(foodGroupOptions);
foodGroupInput.setBounds(200, 125, 100, 25);
frame.add(foodGroupInput);
foodName = new JLabel("Food:");
foodName.setBounds(100, 150, 80, 25);
frame.add(foodName);
foodInput = new JTextField(50);
foodInput.setBounds(200, 150, 100, 50);
frame.add(foodInput);
submit = new JButton("Submit");
submit.setBounds(150, 250, 80, 25);
frame.add(submit);
listButton = new JButton("Food List");
listButton.setBounds(300, 250, 180, 25);
frame.add(listButton);
frame.setVisible(true);
// dateInput.addActionListener((ActionEvent ae) -> {
// System.out.println("DateInput event triggered.");
// });
timeInput.addActionListener((ActionEvent ae) -> {
System.out.println("TimeInput event triggered.");
});
foodGroupInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodGroupInput event triggered.");
});
foodInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodInput event triggered.");
});
submit.addActionListener((ActionEvent ae) -> {
String name = foodInput.getText();
String category = foodGroupInput.getSelectedItem().toString();
int month = Integer.parseInt(monthsBox.getSelectedItem().toString());
int day = Integer.parseInt(daysBox.getSelectedItem().toString());
GregorianCalendar time = new GregorianCalendar(2017, month, day);
parentCntl.addFood(name, category, time);
});
listButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goListView();
});
homeButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goHome();
});
}
private void exit() {
}
/**
* Creates a FoodView of the provided FoodProfile
* @param foodProfile the source foodprofile
* @param parentController the parent controller
*/
public FoodUI(FoodCntl parentController, Food food) {
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.parentCntl = parentController;
this.theFoodModel = food;
initView();
}
public void initView(){
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLayout(null);
date = new JLabel("Date:");
date.setBounds(100, 75, 80, 25);
frame.add(date);
//The text field option for date
// dateInput = new JTextField(50);
// dateInput.setBounds(200, 75, 80, 25);
// frame.add(dateInput);
//Makes the date drop downs to elliminate user entering error
String[] months = new String[13];
for (int i = 1; i < 12; i++) {
months[i] = (i)+"";
}
months[0] = theFoodModel.getTime().getTime().getMonth()+"";
String[] days = new String[32];
for (int i = 1; i < 31; i++) {
days[i] = (i)+"";
}
days[0] = theFoodModel.getTime().getTime().getDate()+"";
JPanel dateInputPanel = new JPanel();
dateInputPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
monthsBox = new JComboBox(months);
dateInputPanel.add(monthsBox);
JLabel slash = new JLabel("/");
dateInputPanel.add(slash);
daysBox = new JComboBox(days);
dateInputPanel.add(daysBox);
dateInputPanel.setBounds(200, 75, 180, 25);
frame.add(dateInputPanel);
time = new JLabel("Time:");
time.setBounds(100, 100, 80, 25);
frame.add(time);
timeInput = new JTextField(50);
timeInput.setBounds(200, 100, 80, 25);
frame.add(timeInput);
foodGroup = new JLabel("Food Group:");
foodGroup.setBounds(100, 125, 80, 25);
frame.add(foodGroup);
String[] foodGroupOptions = {theFoodModel.getFoodCategories().get(0), "Dairy", "Fruits", "Grains", "Protein", "Vegetables"};
foodGroupInput = new JComboBox(foodGroupOptions);
foodGroupInput.setBounds(200, 125, 100, 25);
frame.add(foodGroupInput);
foodName = new JLabel("Food:");
foodName.setBounds(100, 150, 80, 25);
frame.add(foodName);
foodInput = new JTextField(50);
foodInput.setText(theFoodModel.getName());
foodInput.setBounds(200, 150, 100, 50);
frame.add(foodInput);
submit = new JButton("Update");
submit.setBounds(150, 250, 80, 25);
frame.add(submit);
listButton = new JButton("Food List");
listButton.setBounds(300, 250, 180, 25);
frame.add(listButton);
deleteButton = new JButton("Delete");
deleteButton.setBounds(50, 250, 80, 25);
frame.add(deleteButton);
frame.setVisible(true);
// dateInput.addActionListener((ActionEvent ae) -> {
// System.out.println("DateInput event triggered.");
// });
timeInput.addActionListener((ActionEvent ae) -> {
System.out.println("TimeInput event triggered.");
});
foodGroupInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodGroupInput event triggered.");
});
foodInput.addActionListener((ActionEvent ae) -> {
System.out.println("foodInput event triggered.");
});
submit.addActionListener((ActionEvent ae) -> {
String name = foodInput.getText();
String category = foodGroupInput.getSelectedItem().toString();
int month = Integer.parseInt(monthsBox.getSelectedItem().toString());
int day = Integer.parseInt(daysBox.getSelectedItem().toString());
GregorianCalendar time = new GregorianCalendar(2017, month, day);
theFoodModel.setFoodCategory(category);
theFoodModel.setName(name);
theFoodModel.setTime(time);
parentCntl.updateFood(theFoodModel);
});
listButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.goListView();
});
deleteButton.addActionListener((ActionEvent ae) -> {
this.setVisible(false);
parentCntl.deleteFood(theFoodModel);
parentCntl.goListView();
});
}
}
|
Removed reference to FoodProfile
|
src/foodprofile/view/FoodUI.java
|
Removed reference to FoodProfile
|
|
Java
|
apache-2.0
|
a453eecaa8eb7567c961c566d5581742b7609133
| 0
|
code4craft/ibatis-plugin
|
package org.intellij.ibatis.provider;
import com.intellij.codeInsight.lookup.LookupValueFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import org.intellij.ibatis.IbatisManager;
import org.intellij.ibatis.util.IbatisConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* filed access method reference provider
*/
public class FieldAccessMethodReferenceProvider extends BaseReferenceProvider {
@NotNull public PsiReference[] getReferencesByElement(PsiElement psiElement) {
final XmlAttributeValue xmlAttributeValue = (XmlAttributeValue) psiElement;
final XmlTag xmlTag = (XmlTag) xmlAttributeValue.getParent().getParent(); //result or parameter tag
final PsiClass psiClass;
XmlAttributeValuePsiReference psiReference = null;
if (xmlTag.getName().equals("result") || xmlTag.getName().equals("parameter") || xmlTag.getName().equals("resultMap")) {
psiClass = getPsiClassForMap(xmlTag, xmlAttributeValue);
if (psiClass != null)
psiReference = new XmlAttributeValuePsiReference(xmlAttributeValue) {
@Nullable public PsiElement resolve() {
if("Map".equals(psiClass.getName())) {
return null;
}
PsiClass referencedClass = psiClass;
String referencePath = getCanonicalText();
String methodName = "set" + StringUtil.capitalize(referencePath);
if (referencePath.contains(".")) {
String fieldName = referencePath.substring(0, referencePath.lastIndexOf('.'));
methodName = "set" + StringUtil.capitalize(referencePath.substring(referencePath.lastIndexOf('.') + 1));
referencedClass = findGetterMethodReturnType(psiClass, "get" + StringUtil.capitalize(fieldName));
}
if (referencedClass != null) {
PsiMethod[] methods = referencedClass.findMethodsByName(methodName, true);
if (methods.length > 0) return methods[0];
}
return null;
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
String referencePath = getCanonicalText();
String newFieldName = StringUtil.decapitalize(newElementName.replace("set", ""));
if (!referencePath.contains(".")) { //flat field
((XmlAttribute) xmlAttributeValue.getParent()).setValue(StringUtil.decapitalize(newElementName.replace("set", "")));
} else //deep field
{
String field1 = referencePath.substring(0, referencePath.indexOf("."));
String newReferencePath;
if (psiClass.findMethodsByName("set" + StringUtil.capitalize(field1), true).length > 0) { //field2 changed
newReferencePath = field1 + "." + newFieldName;
} else //field1 changed
{
newReferencePath = referencePath.replace(field1, newFieldName);
}
((XmlAttribute) xmlAttributeValue.getParent()).setValue(newReferencePath);
}
return resolve();
}
public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException {
return super.bindToElement(element);
}
public boolean isReferenceTo(PsiElement element) {
return super.isReferenceTo(element);
}
public Object[] getVariants() {
if("Map".equals(psiClass.getName())) {
return null;
}
List<String> setterMethods = getAllSetterMethods(psiClass, getCanonicalText());
List<Object> variants = new ArrayList<Object>();
for (String setterMethod : setterMethods) {
variants.add(LookupValueFactory.createLookupValue(setterMethod, IbatisConstants.CLASS_FIELD));
}
return variants.toArray();
}
public boolean isSoft() {
return "Map".equals(psiClass.getName());
}
};
} else {
psiClass = getPsiClassForDynamicProperty(xmlTag, xmlAttributeValue);
if (psiClass != null)
psiReference = new XmlAttributeValuePsiReference(xmlAttributeValue) {
@Nullable public PsiElement resolve() {
if("Map".equals(psiClass.getName())) {
return null;
}
PsiClass referencedClass = psiClass;
String referencePath = getCanonicalText().replace("IntellijIdeaRulezzz ", "");
String methodName = "get" + StringUtil.capitalize(referencePath);
if (referencePath.contains(".")) {
String fieldName = referencePath.substring(0, referencePath.lastIndexOf('.'));
methodName = "get" + StringUtil.capitalize(referencePath.substring(referencePath.lastIndexOf('.') + 1));
referencedClass = findGetterMethodReturnType(psiClass, "get" + StringUtil.capitalize(fieldName));
}
if (referencedClass != null) {
PsiMethod[] methods = referencedClass.findMethodsByName(methodName, true);
if (methods.length > 0) return methods[0];
}
return null;
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
String referencePath = getCanonicalText();
String newFieldName = StringUtil.decapitalize(newElementName.replace("get", ""));
if (!referencePath.contains(".")) { //flat field
((XmlAttribute) xmlAttributeValue.getParent()).setValue(StringUtil.decapitalize(newElementName.replace("get", "")));
} else //deep field
{
String field1 = referencePath.substring(0, referencePath.indexOf("."));
String newReferencePath;
if (psiClass.findMethodsByName("get" + StringUtil.capitalize(field1), true).length > 0) { //field2 changed
newReferencePath = field1 + "." + newFieldName;
} else //field1 changed
{
newReferencePath = referencePath.replace(field1, newFieldName);
}
((XmlAttribute) xmlAttributeValue.getParent()).setValue(newReferencePath);
}
return resolve();
}
public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException {
return super.bindToElement(element);
}
public boolean isReferenceTo(PsiElement element) {
return super.isReferenceTo(element);
}
public Object[] getVariants() {
if("Map".equals(psiClass.getName())) {
return null;
}
List<String> setterMethods = getAllGetterMethods(psiClass, getCanonicalText().replace("IntellijIdeaRulezzz ", ""));
List<Object> variants = new ArrayList<Object>();
for (String setterMethod : setterMethods) {
variants.add(LookupValueFactory.createLookupValue(setterMethod, IbatisConstants.CLASS_FIELD));
}
return variants.toArray();
}
public boolean isSoft() {
return "Map".equals(psiClass.getName());
}
};
}
if (psiReference == null) return PsiReference.EMPTY_ARRAY;
return new PsiReference[]{psiReference};
}
/**
* find getter method return type
*
* @param psiClass PsiClass
* @param methodName getter method name
* @return PsiClass
*/
private PsiClass findGetterMethodReturnType(PsiClass psiClass, String methodName) {
PsiMethod[] methods = psiClass.findMethodsByName(methodName, true);
//getter method find for current
if (methods.length > 0) {
PsiMethod psiGetterMethod = methods[0];
PsiType returnType = psiGetterMethod.getReturnType();
if (returnType instanceof PsiClassType) {
PsiClass psiFieldClass = ((PsiClassType) returnType).resolve();
if (psiFieldClass != null)
return psiFieldClass;
}
}
return null;
}
public List<String> getAllSetterMethods(PsiClass psiClass, String currentMethodName) {
List<String> methodNames = new ArrayList<String>();
PsiMethod[] psiMethods = null;
String prefix = "";
//flat field
if (!currentMethodName.contains(".")) {
psiMethods = psiClass.getAllMethods();
} else {
prefix = currentMethodName.substring(0, currentMethodName.lastIndexOf('.'));
String getterMethod = "get" + StringUtil.capitalize(prefix);
PsiClass psiFieldClass = findGetterMethodReturnType(psiClass, getterMethod);
if (psiFieldClass != null) {
psiMethods = psiFieldClass.getAllMethods();
prefix = prefix + ".";
}
}
if (psiMethods != null && psiMethods.length > 0) {
for (PsiMethod psiMethod : psiMethods) {
String methodName = psiMethod.getName();
if (methodName.startsWith("set") && psiMethod.getParameterList().getParametersCount() == 1) {
methodNames.add(prefix + StringUtil.decapitalize(methodName.replaceFirst("set", "")));
}
}
}
return methodNames;
}
public List<String> getAllGetterMethods(PsiClass psiClass, String currentMethodName) {
List<String> methodNames = new ArrayList<String>();
PsiMethod[] psiMethods = null;
String prefix = "";
//flat field
if (!currentMethodName.contains(".")) {
psiMethods = psiClass.getAllMethods();
} else {
prefix = currentMethodName.substring(0, currentMethodName.lastIndexOf('.'));
String getterMethod = "get" + StringUtil.capitalize(prefix);
PsiClass psiFieldClass = findGetterMethodReturnType(psiClass, getterMethod);
if (psiFieldClass != null) {
psiMethods = psiFieldClass.getAllMethods();
prefix = prefix + ".";
}
}
if (psiMethods != null && psiMethods.length > 0) {
for (PsiMethod psiMethod : psiMethods) {
String methodName = psiMethod.getName();
if (methodName.startsWith("get") && psiMethod.getParameterList().getParametersCount() == 0) {
methodNames.add(prefix + StringUtil.decapitalize(methodName.replaceFirst("get", "")));
}
}
}
return methodNames;
}
public PsiClass getPsiClassForDynamicProperty(XmlTag xmlTag, XmlAttributeValue xmlAttributeValue) {
XmlTag parentTag = xmlTag.getParentTag();
if (parentTag != null) {
if (parentTag.getAttribute("parameterClass") != null) {
String className = parentTag.getAttributeValue("parameterClass");
return IbatisClassShortcutsReferenceProvider.getPsiClass(xmlAttributeValue, className);
} else if (parentTag.getAttribute("parameterMap") != null) {
String parameterMapId = parentTag.getAttributeValue("parameterMap");
return IbatisManager.getInstance().getAllParameterMap(xmlAttributeValue).get(parameterMapId);
} else {
return getPsiClassForDynamicProperty(parentTag, xmlAttributeValue);
}
}
return null;
}
/**
* get Psi Class for resultMap for parameterMap
*
* @param xmlTag tag for xml attribute
* @param xmlAttributeValue xml attribute value
* @return
*/
public PsiClass getPsiClassForMap(XmlTag xmlTag, XmlAttributeValue xmlAttributeValue) {
XmlTag parentTag = xmlTag.getParentTag(); //resultMap or parameterMap element
if (xmlTag.getName().equals("resultMap")) parentTag = xmlTag; //resultMap's groupBy
if (parentTag != null && parentTag.getAttribute("class") != null) {
String className = parentTag.getAttributeValue("class");
return IbatisClassShortcutsReferenceProvider.getPsiClass(xmlAttributeValue, className);
}
return null;
}
}
|
src/org/intellij/ibatis/provider/FieldAccessMethodReferenceProvider.java
|
package org.intellij.ibatis.provider;
import com.intellij.codeInsight.lookup.LookupValueFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import org.intellij.ibatis.IbatisManager;
import org.intellij.ibatis.util.IbatisConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* filed access method reference provider
*/
public class FieldAccessMethodReferenceProvider extends BaseReferenceProvider {
@NotNull public PsiReference[] getReferencesByElement(PsiElement psiElement) {
final XmlAttributeValue xmlAttributeValue = (XmlAttributeValue) psiElement;
final XmlTag xmlTag = (XmlTag) xmlAttributeValue.getParent().getParent(); //result or parameter tag
final PsiClass psiClass;
XmlAttributeValuePsiReference psiReference = null;
if (xmlTag.getName().equals("result") || xmlTag.getName().equals("parameter") || xmlTag.getName().equals("resultMap")) {
psiClass = getPsiClassForMap(xmlTag, xmlAttributeValue);
if (psiClass != null)
psiReference = new XmlAttributeValuePsiReference(xmlAttributeValue) {
@Nullable public PsiElement resolve() {
if("Map".equals(psiClass.getName())) {
return null;
}
PsiClass referencedClass = psiClass;
String referencePath = getCanonicalText();
String methodName = "set" + StringUtil.capitalize(referencePath);
if (referencePath.contains(".")) {
String fieldName = referencePath.substring(0, referencePath.lastIndexOf('.'));
methodName = "set" + StringUtil.capitalize(referencePath.substring(referencePath.lastIndexOf('.') + 1));
referencedClass = findGetterMethodReturnType(psiClass, "get" + StringUtil.capitalize(fieldName));
}
if (referencedClass != null) {
PsiMethod[] methods = referencedClass.findMethodsByName(methodName, true);
if (methods.length > 0) return methods[0];
}
return null;
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
String referencePath = getCanonicalText();
String newFieldName = StringUtil.decapitalize(newElementName.replace("set", ""));
if (!referencePath.contains(".")) { //flat field
((XmlAttribute) xmlAttributeValue.getParent()).setValue(StringUtil.decapitalize(newElementName.replace("set", "")));
} else //deep field
{
String field1 = referencePath.substring(0, referencePath.indexOf("."));
String newReferencePath;
if (psiClass.findMethodsByName("set" + StringUtil.capitalize(field1), true).length > 0) { //field2 changed
newReferencePath = field1 + "." + newFieldName;
} else //field1 changed
{
newReferencePath = referencePath.replace(field1, newFieldName);
}
((XmlAttribute) xmlAttributeValue.getParent()).setValue(newReferencePath);
}
return resolve();
}
public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException {
return super.bindToElement(element);
}
public boolean isReferenceTo(PsiElement element) {
return super.isReferenceTo(element);
}
public Object[] getVariants() {
if("Map".equals(psiClass.getName())) {
return null;
}
List<String> setterMethods = getAllSetterMethods(psiClass, getCanonicalText());
List<Object> variants = new ArrayList<Object>();
for (String setterMethod : setterMethods) {
variants.add(LookupValueFactory.createLookupValue(setterMethod, IbatisConstants.CLASS_FIELD));
}
return variants.toArray();
}
public boolean isSoft() {
if("Map".equals(psiClass.getName())) {
return true;
}
return false;
}
};
} else {
psiClass = getPsiClassForDynamicProperty(xmlTag, xmlAttributeValue);
if (psiClass != null)
psiReference = new XmlAttributeValuePsiReference(xmlAttributeValue) {
@Nullable public PsiElement resolve() {
if("Map".equals(psiClass.getName())) {
return null;
}
PsiClass referencedClass = psiClass;
String referencePath = getCanonicalText().replace("IntellijIdeaRulezzz ", "");
String methodName = "get" + StringUtil.capitalize(referencePath);
if (referencePath.contains(".")) {
String fieldName = referencePath.substring(0, referencePath.lastIndexOf('.'));
methodName = "get" + StringUtil.capitalize(referencePath.substring(referencePath.lastIndexOf('.') + 1));
referencedClass = findGetterMethodReturnType(psiClass, "get" + StringUtil.capitalize(fieldName));
}
if (referencedClass != null) {
PsiMethod[] methods = referencedClass.findMethodsByName(methodName, true);
if (methods.length > 0) return methods[0];
}
return null;
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
String referencePath = getCanonicalText();
String newFieldName = StringUtil.decapitalize(newElementName.replace("get", ""));
if (!referencePath.contains(".")) { //flat field
((XmlAttribute) xmlAttributeValue.getParent()).setValue(StringUtil.decapitalize(newElementName.replace("get", "")));
} else //deep field
{
String field1 = referencePath.substring(0, referencePath.indexOf("."));
String newReferencePath;
if (psiClass.findMethodsByName("get" + StringUtil.capitalize(field1), true).length > 0) { //field2 changed
newReferencePath = field1 + "." + newFieldName;
} else //field1 changed
{
newReferencePath = referencePath.replace(field1, newFieldName);
}
((XmlAttribute) xmlAttributeValue.getParent()).setValue(newReferencePath);
}
return resolve();
}
public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException {
return super.bindToElement(element);
}
public boolean isReferenceTo(PsiElement element) {
return super.isReferenceTo(element);
}
public Object[] getVariants() {
if("Map".equals(psiClass.getName())) {
return null;
}
List<String> setterMethods = getAllGetterMethods(psiClass, getCanonicalText().replace("IntellijIdeaRulezzz ", ""));
List<Object> variants = new ArrayList<Object>();
for (String setterMethod : setterMethods) {
variants.add(LookupValueFactory.createLookupValue(setterMethod, IbatisConstants.CLASS_FIELD));
}
return variants.toArray();
}
public boolean isSoft() {
if("Map".equals(psiClass.getName())) {
return true;
}
return false;
}
};
}
if (psiReference == null) return PsiReference.EMPTY_ARRAY;
return new PsiReference[]{psiReference};
}
/**
* find getter method return type
*
* @param psiClass PsiClass
* @param methodName getter method name
* @return PsiClass
*/
private PsiClass findGetterMethodReturnType(PsiClass psiClass, String methodName) {
PsiMethod[] methods = psiClass.findMethodsByName(methodName, true);
//getter method find for current
if (methods.length > 0) {
PsiMethod psiGetterMethod = methods[0];
PsiType returnType = psiGetterMethod.getReturnType();
if (returnType instanceof PsiClassType) {
PsiClass psiFieldClass = ((PsiClassType) returnType).resolve();
if (psiFieldClass != null)
return psiFieldClass;
}
}
return null;
}
public List<String> getAllSetterMethods(PsiClass psiClass, String currentMethodName) {
List<String> methodNames = new ArrayList<String>();
PsiMethod[] psiMethods = null;
String prefix = "";
//flat field
if (!currentMethodName.contains(".")) {
psiMethods = psiClass.getAllMethods();
} else {
prefix = currentMethodName.substring(0, currentMethodName.lastIndexOf('.'));
String getterMethod = "get" + StringUtil.capitalize(prefix);
PsiClass psiFieldClass = findGetterMethodReturnType(psiClass, getterMethod);
if (psiFieldClass != null) {
psiMethods = psiFieldClass.getAllMethods();
prefix = prefix + ".";
}
}
if (psiMethods != null && psiMethods.length > 0) {
for (PsiMethod psiMethod : psiMethods) {
String methodName = psiMethod.getName();
if (methodName.startsWith("set") && psiMethod.getParameterList().getParametersCount() == 1) {
methodNames.add(prefix + StringUtil.decapitalize(methodName.replaceFirst("set", "")));
}
}
}
return methodNames;
}
public List<String> getAllGetterMethods(PsiClass psiClass, String currentMethodName) {
List<String> methodNames = new ArrayList<String>();
PsiMethod[] psiMethods = null;
String prefix = "";
//flat field
if (!currentMethodName.contains(".")) {
psiMethods = psiClass.getAllMethods();
} else {
prefix = currentMethodName.substring(0, currentMethodName.lastIndexOf('.'));
String getterMethod = "get" + StringUtil.capitalize(prefix);
PsiClass psiFieldClass = findGetterMethodReturnType(psiClass, getterMethod);
if (psiFieldClass != null) {
psiMethods = psiFieldClass.getAllMethods();
prefix = prefix + ".";
}
}
if (psiMethods != null && psiMethods.length > 0) {
for (PsiMethod psiMethod : psiMethods) {
String methodName = psiMethod.getName();
if (methodName.startsWith("get") && psiMethod.getParameterList().getParametersCount() == 0) {
methodNames.add(prefix + StringUtil.decapitalize(methodName.replaceFirst("get", "")));
}
}
}
return methodNames;
}
public PsiClass getPsiClassForDynamicProperty(XmlTag xmlTag, XmlAttributeValue xmlAttributeValue) {
XmlTag parentTag = xmlTag.getParentTag();
if (parentTag != null) {
if (parentTag.getAttribute("parameterClass") != null) {
String className = parentTag.getAttributeValue("parameterClass");
return IbatisClassShortcutsReferenceProvider.getPsiClass(xmlAttributeValue, className);
} else if (parentTag.getAttribute("parameterMap") != null) {
String parameterMapId = parentTag.getAttributeValue("parameterMap");
return IbatisManager.getInstance().getAllParameterMap(xmlAttributeValue).get(parameterMapId);
} else {
return getPsiClassForDynamicProperty(parentTag, xmlAttributeValue);
}
}
return null;
}
/**
* get Psi Class for resultMap for parameterMap
*
* @param xmlTag tag for xml attribute
* @param xmlAttributeValue xml attribute value
* @return
*/
public PsiClass getPsiClassForMap(XmlTag xmlTag, XmlAttributeValue xmlAttributeValue) {
XmlTag parentTag = xmlTag.getParentTag(); //resultMap or parameterMap element
if (xmlTag.getName().equals("resultMap")) parentTag = xmlTag; //resultMap's groupBy
if (parentTag != null && parentTag.getAttribute("class") != null) {
String className = parentTag.getAttributeValue("class");
return IbatisClassShortcutsReferenceProvider.getPsiClass(xmlAttributeValue, className);
}
return null;
}
}
|
code format
git-svn-id: a3757b7b28cb5f166982e3e590f726e1a71ef014@57 a27988d2-9830-0410-8773-31d6671a21de
|
src/org/intellij/ibatis/provider/FieldAccessMethodReferenceProvider.java
|
code format
|
|
Java
|
apache-2.0
|
8482dc120d92929c8b2ccde2bf197328fb0e556e
| 0
|
trombka/blc-tmp,liqianggao/BroadleafCommerce,gengzhengtao/BroadleafCommerce,bijukunjummen/BroadleafCommerce,macielbombonato/BroadleafCommerce,rawbenny/BroadleafCommerce,trombka/blc-tmp,TouK/BroadleafCommerce,rawbenny/BroadleafCommerce,lgscofield/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,daniellavoie/BroadleafCommerce,macielbombonato/BroadleafCommerce,sanlingdd/broadleaf,SerPenTeHoK/BroadleafCommerce,passion1014/metaworks_framework,ljshj/BroadleafCommerce,rawbenny/BroadleafCommerce,sitexa/BroadleafCommerce,passion1014/metaworks_framework,cloudbearings/BroadleafCommerce,alextiannus/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,zhaorui1/BroadleafCommerce,TouK/BroadleafCommerce,zhaorui1/BroadleafCommerce,udayinfy/BroadleafCommerce,wenmangbo/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,liqianggao/BroadleafCommerce,liqianggao/BroadleafCommerce,cloudbearings/BroadleafCommerce,gengzhengtao/BroadleafCommerce,alextiannus/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,macielbombonato/BroadleafCommerce,cogitoboy/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,cogitoboy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,lgscofield/BroadleafCommerce,sitexa/BroadleafCommerce,udayinfy/BroadleafCommerce,passion1014/metaworks_framework,sitexa/BroadleafCommerce,gengzhengtao/BroadleafCommerce,cogitoboy/BroadleafCommerce,udayinfy/BroadleafCommerce,caosg/BroadleafCommerce,shopizer/BroadleafCommerce,caosg/BroadleafCommerce,sanlingdd/broadleaf,cengizhanozcan/BroadleafCommerce,cloudbearings/BroadleafCommerce,wenmangbo/BroadleafCommerce,shopizer/BroadleafCommerce,caosg/BroadleafCommerce,daniellavoie/BroadleafCommerce,TouK/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,ljshj/BroadleafCommerce,lgscofield/BroadleafCommerce,trombka/blc-tmp,ljshj/BroadleafCommerce,wenmangbo/BroadleafCommerce,shopizer/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,bijukunjummen/BroadleafCommerce,bijukunjummen/BroadleafCommerce,daniellavoie/BroadleafCommerce,alextiannus/BroadleafCommerce,zhaorui1/BroadleafCommerce
|
/*
* Copyright 2008-2009 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.broadleafcommerce.order.service.call;
import org.broadleafcommerce.catalog.domain.Category;
import org.broadleafcommerce.catalog.domain.Product;
import org.broadleafcommerce.catalog.domain.Sku;
import org.broadleafcommerce.order.domain.PersonalMessage;
public class DiscreteOrderItemRequest {
private Sku sku;
private Category category;
private Product product;
private int quantity;
private PersonalMessage personalMessage;
public Sku getSku() {
return sku;
}
public void setSku(Sku sku) {
this.sku = sku;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DiscreteOrderItemRequest)) return false;
DiscreteOrderItemRequest that = (DiscreteOrderItemRequest) o;
if (!category.equals(that.category)) return false;
if (!product.equals(that.product)) return false;
if (quantity != that.quantity) return false;
if (!sku.equals(that.sku)) return false;
return true;
}
@Override
public int hashCode() {
int result = product != null ? product.hashCode() : 0;
result = 31 * result + (category != null ? category.hashCode() : 0);
result = 31 * result + (sku != null ? sku.hashCode() : 0);
result = 31 * result + quantity;
return result;
}
public PersonalMessage getPersonalMessage() {
return personalMessage;
}
public void setPersonalMessage(PersonalMessage personalMessage) {
this.personalMessage = personalMessage;
}
}
|
BroadleafCommerce/src-framework/org/broadleafcommerce/order/service/call/DiscreteOrderItemRequest.java
|
/*
* Copyright 2008-2009 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.broadleafcommerce.order.service.call;
import org.broadleafcommerce.catalog.domain.Category;
import org.broadleafcommerce.catalog.domain.Product;
import org.broadleafcommerce.catalog.domain.Sku;
public class DiscreteOrderItemRequest {
private Sku sku;
private Category category;
private Product product;
private int quantity;
public Sku getSku() {
return sku;
}
public void setSku(Sku sku) {
this.sku = sku;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DiscreteOrderItemRequest)) return false;
DiscreteOrderItemRequest that = (DiscreteOrderItemRequest) o;
if (!category.equals(that.category)) return false;
if (!product.equals(that.product)) return false;
if (quantity != that.quantity) return false;
if (!sku.equals(that.sku)) return false;
return true;
}
@Override
public int hashCode() {
int result = product != null ? product.hashCode() : 0;
result = 31 * result + (category != null ? category.hashCode() : 0);
result = 31 * result + (sku != null ? sku.hashCode() : 0);
result = 31 * result + quantity;
return result;
}
}
|
add ability to add a personal message to DiscreteOrderItemRequest (useful for gift cards)
|
BroadleafCommerce/src-framework/org/broadleafcommerce/order/service/call/DiscreteOrderItemRequest.java
|
add ability to add a personal message to DiscreteOrderItemRequest (useful for gift cards)
|
|
Java
|
apache-2.0
|
a6d30c1849eeb0432e15f99d878037098968f0cf
| 0
|
google/closure-compiler,monetate/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,nawawi/closure-compiler,nawawi/closure-compiler,google/closure-compiler,Yannic/closure-compiler,monetate/closure-compiler,vobruba-martin/closure-compiler,Yannic/closure-compiler,vobruba-martin/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,Yannic/closure-compiler,ChadKillingsworth/closure-compiler,vobruba-martin/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,Yannic/closure-compiler
|
/*
* Copyright 2011 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* An extension of {@code WarningsGuard} that provides functionality to maintain
* a list of warnings (white-list). It is subclasses' responsibility to decide
* what to do with the white-list by implementing the {@code level} function.
* Warnings are defined by the name of the JS file and the first line of
* warnings description.
*/
@GwtIncompatible("java.io, java.util.regex")
public class WhitelistWarningsGuard extends WarningsGuard {
private static final Splitter LINE_SPLITTER = Splitter.on('\n');
/** The set of white-listed warnings, same format as {@code formatWarning}. */
private final Set<String> whitelist;
/** Pattern to match line number in error descriptions. */
private static final Pattern LINE_NUMBER = Pattern.compile(":-?\\d+");
public WhitelistWarningsGuard() {
this(ImmutableSet.of());
}
/**
* This class depends on an input set that contains the white-list. The format
* of each white-list string is:
* {@code <file-name>:<line-number>? <warning-description>}
* {@code # <optional-comment>}
*
* @param whitelist The set of JS-warnings that are white-listed. This is
* expected to have similar format as {@code formatWarning(JSError)}.
*/
public WhitelistWarningsGuard(Set<String> whitelist) {
checkNotNull(whitelist);
this.whitelist = normalizeWhitelist(whitelist);
}
/**
* Loads legacy warnings list from the set of strings. During development line
* numbers are changed very often - we just cut them and compare without ones.
*
* @return known legacy warnings without line numbers.
*/
protected Set<String> normalizeWhitelist(Set<String> whitelist) {
Set<String> result = new HashSet<>();
for (String line : whitelist) {
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.charAt(0) == '#') {
// strip out empty lines and comments.
continue;
}
// Strip line number for matching.
result.add(LINE_NUMBER.matcher(trimmed).replaceFirst(":"));
}
return ImmutableSet.copyOf(result);
}
@Override
public CheckLevel level(JSError error) {
if (error.getDefaultLevel().equals(CheckLevel.ERROR)
&& !DOWNGRADEABLE_ERRORS_LIST.contains(error.getType().key)) {
return null;
}
if (containWarning(formatWarning(error))) {
// If the message matches the guard we use WARNING, so that it
// - Shows up on stderr, and
// - Gets caught by the WhitelistBuilder downstream in the pipeline
return CheckLevel.WARNING;
}
return null;
}
private static final ImmutableSet<String> DOWNGRADEABLE_ERRORS_LIST =
ImmutableSet.of(
);
/**
* Determines whether a given warning is included in the white-list.
*
* @param formattedWarning the warning formatted by {@code formatWarning}
* @return whether the given warning is white-listed or not.
*/
protected boolean containWarning(String formattedWarning) {
return whitelist.contains(formattedWarning);
}
@Override
public int getPriority() {
return WarningsGuard.Priority.SUPPRESS_BY_WHITELIST.getValue();
}
/** Creates a warnings guard from a file. */
public static WhitelistWarningsGuard fromFile(File file) {
return new WhitelistWarningsGuard(loadWhitelistedJsWarnings(file));
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
public static Set<String> loadWhitelistedJsWarnings(File file) {
return loadWhitelistedJsWarnings(
Files.asCharSource(file, UTF_8));
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
protected static Set<String> loadWhitelistedJsWarnings(CharSource supplier) {
try {
return loadWhitelistedJsWarnings(supplier.openStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
// TODO(nicksantos): This is a weird API.
static Set<String> loadWhitelistedJsWarnings(Reader reader)
throws IOException {
checkNotNull(reader);
Set<String> result = new HashSet<>();
result.addAll(CharStreams.readLines(reader));
return result;
}
/**
* If subclasses want to modify the formatting, they should override
* #formatWarning(JSError, boolean), not this method.
*/
protected String formatWarning(JSError error) {
return formatWarning(error, false);
}
/**
* @param withMetaData If true, include metadata that's useful to humans
* This metadata won't be used for matching the warning.
*/
protected String formatWarning(JSError error, boolean withMetaData) {
StringBuilder sb = new StringBuilder();
sb.append(error.getSourceName()).append(":");
if (withMetaData) {
sb.append(error.getLineNumber());
}
List<String> lines = LINE_SPLITTER.splitToList(error.getDescription());
sb.append(" ").append(lines.get(0));
// Add the rest of the message as a comment.
if (withMetaData) {
for (int i = 1; i < lines.size(); i++) {
sb.append("\n# ").append(lines.get(i));
}
sb.append("\n");
}
return sb.toString();
}
public static String getFirstLine(String warning) {
int lineLength = warning.indexOf('\n');
if (lineLength > 0) {
warning = warning.substring(0, lineLength);
}
return warning;
}
/** Whitelist builder */
public class WhitelistBuilder implements ErrorHandler {
private final Set<JSError> warnings = new LinkedHashSet<>();
private String productName = null;
private String generatorTarget = null;
private String headerNote = null;
/** Fill in your product name to get a fun message! */
public WhitelistBuilder setProductName(String name) {
this.productName = name;
return this;
}
/** Fill in instructions on how to generate this whitelist. */
public WhitelistBuilder setGeneratorTarget(String name) {
this.generatorTarget = name;
return this;
}
/** A note to include at the top of the whitelist file. */
public WhitelistBuilder setNote(String note) {
this.headerNote = note;
return this;
}
@Override
public void report(CheckLevel level, JSError error) {
warnings.add(error);
}
/**
* Writes the warnings collected in a format that the WhitelistWarningsGuard
* can read back later.
*/
public void writeWhitelist(File out) throws IOException {
try (PrintStream stream = new PrintStream(out)) {
appendWhitelist(stream);
}
}
/**
* Writes the warnings collected in a format that the WhitelistWarningsGuard
* can read back later.
*/
public void appendWhitelist(PrintStream out) {
out.append(
"# This is a list of legacy warnings that have yet to be fixed.\n");
if (productName != null && !productName.isEmpty() && !warnings.isEmpty()) {
out.append("# Please find some time and fix at least one of them "
+ "and it will be the happiest day for " + productName + ".\n");
}
if (generatorTarget != null && !generatorTarget.isEmpty()) {
out.append("# When you fix any of these warnings, run "
+ generatorTarget + " task.\n");
}
if (headerNote != null) {
out.append("#" + Joiner.on("\n# ").join(Splitter.on('\n').split(headerNote)) + "\n");
}
Multimap<DiagnosticType, String> warningsByType = TreeMultimap.create();
for (JSError warning : warnings) {
warningsByType.put(
warning.getType(),
formatWarning(warning, true /* withLineNumber */));
}
for (DiagnosticType type : warningsByType.keySet()) {
if (DiagnosticGroups.DEPRECATED.matches(type)) {
// Deprecation warnings are not raisable to error, so we don't need them in whitelists.
continue;
}
out.append("\n# Warning ")
.append(type.key)
.append(": ")
.println(Iterables.get(
LINE_SPLITTER.split(type.format.toPattern()), 0));
for (String warning : warningsByType.get(type)) {
out.println(warning);
}
}
out.flush();
}
}
}
|
src/com/google/javascript/jscomp/WhitelistWarningsGuard.java
|
/*
* Copyright 2011 The Closure Compiler 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 com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import com.google.common.io.CharSource;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Reader;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
/**
* An extension of {@code WarningsGuard} that provides functionality to maintain
* a list of warnings (white-list). It is subclasses' responsibility to decide
* what to do with the white-list by implementing the {@code level} function.
* Warnings are defined by the name of the JS file and the first line of
* warnings description.
*/
@GwtIncompatible("java.io, java.util.regex")
public class WhitelistWarningsGuard extends WarningsGuard {
private static final Splitter LINE_SPLITTER = Splitter.on('\n');
/** The set of white-listed warnings, same format as {@code formatWarning}. */
private final Set<String> whitelist;
/** Pattern to match line number in error descriptions. */
private static final Pattern LINE_NUMBER = Pattern.compile(":-?\\d+");
public WhitelistWarningsGuard() {
this(ImmutableSet.of());
}
/**
* This class depends on an input set that contains the white-list. The format
* of each white-list string is:
* {@code <file-name>:<line-number>? <warning-description>}
* {@code # <optional-comment>}
*
* @param whitelist The set of JS-warnings that are white-listed. This is
* expected to have similar format as {@code formatWarning(JSError)}.
*/
public WhitelistWarningsGuard(Set<String> whitelist) {
checkNotNull(whitelist);
this.whitelist = normalizeWhitelist(whitelist);
}
/**
* Loads legacy warnings list from the set of strings. During development line
* numbers are changed very often - we just cut them and compare without ones.
*
* @return known legacy warnings without line numbers.
*/
protected Set<String> normalizeWhitelist(Set<String> whitelist) {
Set<String> result = new HashSet<>();
for (String line : whitelist) {
String trimmed = line.trim();
if (trimmed.isEmpty() || trimmed.charAt(0) == '#') {
// strip out empty lines and comments.
continue;
}
// Strip line number for matching.
result.add(LINE_NUMBER.matcher(trimmed).replaceFirst(":"));
}
return ImmutableSet.copyOf(result);
}
@Override
public CheckLevel level(JSError error) {
if (containWarning(formatWarning(error))) {
// If the message matches the guard we use WARNING, so that it
// - Shows up on stderr, and
// - Gets caught by the WhitelistBuilder downstream in the pipeline
return CheckLevel.WARNING;
}
return null;
}
/**
* Determines whether a given warning is included in the white-list.
*
* @param formattedWarning the warning formatted by {@code formatWarning}
* @return whether the given warning is white-listed or not.
*/
protected boolean containWarning(String formattedWarning) {
return whitelist.contains(formattedWarning);
}
@Override
public int getPriority() {
return WarningsGuard.Priority.SUPPRESS_BY_WHITELIST.getValue();
}
/** Creates a warnings guard from a file. */
public static WhitelistWarningsGuard fromFile(File file) {
return new WhitelistWarningsGuard(loadWhitelistedJsWarnings(file));
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
public static Set<String> loadWhitelistedJsWarnings(File file) {
return loadWhitelistedJsWarnings(
Files.asCharSource(file, UTF_8));
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
protected static Set<String> loadWhitelistedJsWarnings(CharSource supplier) {
try {
return loadWhitelistedJsWarnings(supplier.openStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Loads legacy warnings list from the file.
* @return The lines of the file.
*/
// TODO(nicksantos): This is a weird API.
static Set<String> loadWhitelistedJsWarnings(Reader reader)
throws IOException {
checkNotNull(reader);
Set<String> result = new HashSet<>();
result.addAll(CharStreams.readLines(reader));
return result;
}
/**
* If subclasses want to modify the formatting, they should override
* #formatWarning(JSError, boolean), not this method.
*/
protected String formatWarning(JSError error) {
return formatWarning(error, false);
}
/**
* @param withMetaData If true, include metadata that's useful to humans
* This metadata won't be used for matching the warning.
*/
protected String formatWarning(JSError error, boolean withMetaData) {
StringBuilder sb = new StringBuilder();
sb.append(error.getSourceName()).append(":");
if (withMetaData) {
sb.append(error.getLineNumber());
}
List<String> lines = LINE_SPLITTER.splitToList(error.getDescription());
sb.append(" ").append(lines.get(0));
// Add the rest of the message as a comment.
if (withMetaData) {
for (int i = 1; i < lines.size(); i++) {
sb.append("\n# ").append(lines.get(i));
}
sb.append("\n");
}
return sb.toString();
}
public static String getFirstLine(String warning) {
int lineLength = warning.indexOf('\n');
if (lineLength > 0) {
warning = warning.substring(0, lineLength);
}
return warning;
}
/** Whitelist builder */
public class WhitelistBuilder implements ErrorHandler {
private final Set<JSError> warnings = new LinkedHashSet<>();
private String productName = null;
private String generatorTarget = null;
private String headerNote = null;
/** Fill in your product name to get a fun message! */
public WhitelistBuilder setProductName(String name) {
this.productName = name;
return this;
}
/** Fill in instructions on how to generate this whitelist. */
public WhitelistBuilder setGeneratorTarget(String name) {
this.generatorTarget = name;
return this;
}
/** A note to include at the top of the whitelist file. */
public WhitelistBuilder setNote(String note) {
this.headerNote = note;
return this;
}
@Override
public void report(CheckLevel level, JSError error) {
warnings.add(error);
}
/**
* Writes the warnings collected in a format that the WhitelistWarningsGuard
* can read back later.
*/
public void writeWhitelist(File out) throws IOException {
try (PrintStream stream = new PrintStream(out)) {
appendWhitelist(stream);
}
}
/**
* Writes the warnings collected in a format that the WhitelistWarningsGuard
* can read back later.
*/
public void appendWhitelist(PrintStream out) {
out.append(
"# This is a list of legacy warnings that have yet to be fixed.\n");
if (productName != null && !productName.isEmpty() && !warnings.isEmpty()) {
out.append("# Please find some time and fix at least one of them "
+ "and it will be the happiest day for " + productName + ".\n");
}
if (generatorTarget != null && !generatorTarget.isEmpty()) {
out.append("# When you fix any of these warnings, run "
+ generatorTarget + " task.\n");
}
if (headerNote != null) {
out.append("#" + Joiner.on("\n# ").join(Splitter.on('\n').split(headerNote)) + "\n");
}
Multimap<DiagnosticType, String> warningsByType = TreeMultimap.create();
for (JSError warning : warnings) {
warningsByType.put(
warning.getType(),
formatWarning(warning, true /* withLineNumber */));
}
for (DiagnosticType type : warningsByType.keySet()) {
if (DiagnosticGroups.DEPRECATED.matches(type)) {
// Deprecation warnings are not raisable to error, so we don't need them in whitelists.
continue;
}
out.append("\n# Warning ")
.append(type.key)
.append(": ")
.println(Iterables.get(
LINE_SPLITTER.split(type.format.toPattern()), 0));
for (String warning : warningsByType.get(type)) {
out.println(warning);
}
}
out.flush();
}
}
}
|
Errors can no longer be downgraded to Warnings by WhitelistWarningGuard.
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=298681187
|
src/com/google/javascript/jscomp/WhitelistWarningsGuard.java
|
Errors can no longer be downgraded to Warnings by WhitelistWarningGuard.
|
|
Java
|
apache-2.0
|
796f1e1c77afe7508b4b753c63e1798b3cbd80bb
| 0
|
seronal/Raccoon,olipfei/Raccoon,pie-ai/Raccoon,olipfei/Raccoon,seronal/Raccoon,pie-ai/Raccoon,onyxbits/Raccoon,onyxbits/Raccoon
|
package de.onyxbits.raccoon;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsEntry;
import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsResponse;
import com.akdeniz.googleplaycrawler.GooglePlay.DocV2;
import com.akdeniz.googleplaycrawler.GooglePlayAPI;
import de.onyxbits.raccoon.io.Archive;
import de.onyxbits.raccoon.io.DownloadLogger;
import de.onyxbits.raccoon.io.FetchListener;
import de.onyxbits.raccoon.io.FetchService;
/**
* Runs the app in command line interface mode.
*
* @author patrick
*
*/
public class CliService implements FetchListener, Runnable {
private String[] cmdLine;
private DownloadLogger logger;
private Archive destination;
public CliService(String[] cmdLine) {
this.cmdLine = cmdLine;
}
public boolean onChunk(FetchService src, long numBytes) {
System.out.print('.');
return false;
}
public void onFailure(FetchService src, Exception e) {
System.err.println("Failure: " + e.getMessage());
// e.printStackTrace();
}
public void onAborted(FetchService src) {
}
public void run() {
Option help = new Option("h", false, "Show commandline usage");
Option version = new Option("v", false, "Show version and exit");
Option update = new Option("u", false, "Update archive (requires -a).");
Option archive = new Option("a", true, "Archive to work on");
Option importer = new Option(
"i",
true,
"Import apps. A text file, containing one market url per line must be given (requires -a and -u to actually download).");
Option paid = new Option("p", false,
"Use with -f to download paid apps (the app must already have been bought).");
archive.setArgName("directory");
Option fetch = new Option("f", true, "Fetch an app (requires -a).");
fetch.setArgName("packId,versionCode,offerType");
importer.setArgName("file");
Options opts = new Options();
opts.addOption(version);
opts.addOption(archive);
opts.addOption(help);
opts.addOption(update);
opts.addOption(importer);
opts.addOption(fetch);
opts.addOption(paid);
CommandLine cmd = null;
try {
cmd = new BasicParser().parse(opts, cmdLine);
}
catch (ParseException e1) {
System.err.println(e1.getMessage());
System.exit(1);
}
if (cmd.hasOption('h')) {
new HelpFormatter().printHelp("Raccoon", opts);
System.exit(0);
}
if (cmd.hasOption('v')) {
System.out.println(App.VERSIONSTRING);
System.exit(0);
}
if (cmd.hasOption('a')) {
destination = new Archive(new File(cmd.getOptionValue('a')));
logger = new DownloadLogger(destination);
logger.clear();
}
if (cmd.hasOption("i")) {
requireArchive();
try {
doImport(new File(cmd.getOptionValue('i')));
}
catch (IOException e) {
System.err.println(e.getMessage());
}
}
if (cmd.hasOption("u")) {
requireArchive();
doUpdate();
}
if (cmd.hasOption("f")) {
requireArchive();
String[] tmp = cmd.getOptionValues('f')[0].split(",");
try {
String appId = tmp[0];
int vc = Integer.parseInt(tmp[1]);
int ot = Integer.parseInt(tmp[2]);
new FetchService(destination, appId, vc, ot, cmd.hasOption('p'), this).run();
}
catch (Exception e) {
System.err.println("Format: packagename,versioncode,offertype");
System.exit(1);
}
}
}
private void doUpdate() {
BulkDetailsResponse response = null;
GooglePlayAPI service = null;
try {
service = App.createConnection(destination);
response = service.bulkDetails(destination.list());
}
catch (Exception e) {
e.printStackTrace();
return;
}
for (BulkDetailsEntry bulkDetailsEntry : response.getEntryList()) {
DocV2 doc = bulkDetailsEntry.getDoc();
String pn = doc.getBackendDocid();
int vc = -1;
int ot = -1;
boolean paid = false;
try {
vc = doc.getDetails().getAppDetails().getVersionCode();
ot = doc.getOffer(0).getOfferType();
paid = doc.getOffer(0).getCheckoutFlowRequired();
}
catch (Exception e) {
// Something in the apk storage did not resolve. This could be an app
// that was pulled from Google Play or a directory s/he created. Design
// decision: ignore silently. In the first case the user doesn't want
// to bother in the second, s/he does not need to.
continue;
}
File target = destination.fileUnder(pn, vc);
if (!target.exists()) {
FetchService fs = new FetchService(destination, pn, vc, ot, paid, this);
fs.run();
}
}
}
private void doImport(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String prefix = "market://details?id=";
while ((line = br.readLine()) != null) {
if (line.startsWith(prefix) && line.length() > prefix.length()) {
// Let's keep it simple.
String id = line.substring(prefix.length(), line.length());
destination.fileUnder(id, 0).getParentFile().mkdirs();
System.out.println("Adding: " + id);
}
}
br.close();
}
/**
* Check if an archive is specified, bail out if not.
*/
private void requireArchive() {
if (destination == null) {
System.err.println("No archive specified!");
System.exit(1);
}
}
@Override
public void onBeginFile(FetchService src, File file) {
System.err.println("Starting: " + file.getName());
}
@Override
public void onFinishFile(FetchService src, File file) {
try {
// NOTE: Not correct to do that here, but since the user can't cancel,
// we can get away with it.
logger.addEntry(file);
System.out.println("\nSuccess");
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onComplete(FetchService src) {
}
}
|
src/main/java/de/onyxbits/raccoon/CliService.java
|
package de.onyxbits.raccoon;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsEntry;
import com.akdeniz.googleplaycrawler.GooglePlay.BulkDetailsResponse;
import com.akdeniz.googleplaycrawler.GooglePlay.DocV2;
import com.akdeniz.googleplaycrawler.GooglePlayAPI;
import de.onyxbits.raccoon.io.Archive;
import de.onyxbits.raccoon.io.DownloadLogger;
import de.onyxbits.raccoon.io.FetchListener;
import de.onyxbits.raccoon.io.FetchService;
/**
* Runs the app in command line interface mode.
*
* @author patrick
*
*/
public class CliService implements FetchListener, Runnable {
private String[] cmdLine;
private DownloadLogger logger;
private Archive destination;
public CliService(String[] cmdLine) {
this.cmdLine = cmdLine;
}
public boolean onChunk(FetchService src, long numBytes) {
System.out.print('.');
return false;
}
public void onFailure(FetchService src, Exception e) {
System.err.println("Failure: " + e.getMessage());
// e.printStackTrace();
}
public void onAborted(FetchService src) {
}
public void run() {
Option help = new Option("h", false, "Show commandline usage");
Option version = new Option("v", false, "Show version and exit");
Option update = new Option("u", false, "Update archive (requires -a).");
Option archive = new Option("a", true, "Archive to work on");
Option importer = new Option(
"i",
true,
"Import apps. A text file, containing one market url per line must be given (requires -a and -u to actually download).");
Option paid = new Option("p", false,
"Use with -f to download paid apps (the app must already have been bought).");
archive.setArgName("directory");
Option fetch = new Option("f", true, "Fetch an app (requires -a).");
fetch.setArgName("packId,versionCode,offerType");
Options opts = new Options();
opts.addOption(version);
opts.addOption(archive);
opts.addOption(help);
opts.addOption(update);
opts.addOption(importer);
opts.addOption(fetch);
opts.addOption(paid);
CommandLine cmd = null;
try {
cmd = new BasicParser().parse(opts, cmdLine);
}
catch (ParseException e1) {
System.err.println(e1.getMessage());
System.exit(1);
}
if (cmd.hasOption('h')) {
new HelpFormatter().printHelp("Raccoon", opts);
System.exit(0);
}
if (cmd.hasOption('v')) {
System.out.println(App.VERSIONSTRING);
System.exit(0);
}
if (cmd.hasOption('a')) {
destination = new Archive(new File(cmd.getOptionValue('a')));
logger = new DownloadLogger(destination);
logger.clear();
}
if (cmd.hasOption("i")) {
requireArchive();
try {
doImport(new File(cmd.getOptionValue('i')));
}
catch (IOException e) {
System.err.println(e.getMessage());
}
}
if (cmd.hasOption("u")) {
requireArchive();
doUpdate();
}
if (cmd.hasOption("f")) {
requireArchive();
String[] tmp = cmd.getOptionValues('f')[0].split(",");
try {
String appId = tmp[0];
int vc = Integer.parseInt(tmp[1]);
int ot = Integer.parseInt(tmp[2]);
new FetchService(destination, appId, vc, ot, cmd.hasOption('p'), this).run();
}
catch (Exception e) {
System.err.println("Format: packagename,versioncode,offertype");
System.exit(1);
}
}
}
private void doUpdate() {
BulkDetailsResponse response = null;
GooglePlayAPI service = null;
try {
service = App.createConnection(destination);
response = service.bulkDetails(destination.list());
}
catch (Exception e) {
e.printStackTrace();
return;
}
for (BulkDetailsEntry bulkDetailsEntry : response.getEntryList()) {
DocV2 doc = bulkDetailsEntry.getDoc();
String pn = doc.getBackendDocid();
int vc = -1;
int ot = -1;
boolean paid = false;
try {
vc = doc.getDetails().getAppDetails().getVersionCode();
ot = doc.getOffer(0).getOfferType();
paid = doc.getOffer(0).getCheckoutFlowRequired();
}
catch (Exception e) {
// Something in the apk storage did not resolve. This could be an app
// that was pulled from Google Play or a directory s/he created. Design
// decision: ignore silently. In the first case the user doesn't want
// to bother in the second, s/he does not need to.
continue;
}
File target = destination.fileUnder(pn, vc);
if (!target.exists()) {
FetchService fs = new FetchService(destination, pn, vc, ot, paid, this);
fs.run();
}
}
}
private void doImport(File file) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
String prefix = "market://details?id=";
while ((line = br.readLine()) != null) {
if (line.startsWith(prefix) && line.length() > prefix.length()) {
// Let's keep it simple.
String id = line.substring(prefix.length(), line.length());
destination.fileUnder(id, 0).getParentFile().mkdirs();
System.out.println("Adding: " + id);
}
}
br.close();
}
/**
* Check if an archive is specified, bail out if not.
*/
private void requireArchive() {
if (destination == null) {
System.err.println("No archive specified!");
System.exit(1);
}
}
@Override
public void onBeginFile(FetchService src, File file) {
System.err.println("Starting: " + file.getName());
}
@Override
public void onFinishFile(FetchService src, File file) {
try {
// NOTE: Not correct to do that here, but since the user can't cancel,
// we can get away with it.
logger.addEntry(file);
System.out.println("\nSuccess");
}
catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onComplete(FetchService src) {
}
}
|
BUGFIX: give a name to the argument for the -i command line option.
|
src/main/java/de/onyxbits/raccoon/CliService.java
|
BUGFIX: give a name to the argument for the -i command line option.
|
|
Java
|
apache-2.0
|
b4472c6b0403b177b37c513bf2a547b3be632d2b
| 0
|
jorgebay/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,apache/tinkerpop,pluradj/incubator-tinkerpop,artem-aliev/tinkerpop,jorgebay/tinkerpop,apache/incubator-tinkerpop,pluradj/incubator-tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,krlohnes/tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,apache/tinkerpop
|
/*
* 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.tinkerpop.gremlin.server.jsr223;
import org.apache.tinkerpop.gremlin.jsr223.AbstractGremlinPlugin;
import org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin;
import org.apache.tinkerpop.gremlin.jsr223.DefaultImportCustomizer;
import org.apache.tinkerpop.gremlin.server.util.LifeCycleHook;
/**
* A {@link GremlinPlugin} implementation that adds Gremlin Server specific classes to the imports.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public final class GremlinServerGremlinPlugin extends AbstractGremlinPlugin {
private static final String MODULE_NAME = "tinkerpop.server-side";
private static final GremlinServerGremlinPlugin instance = new GremlinServerGremlinPlugin();
private GremlinServerGremlinPlugin() {
super(MODULE_NAME, DefaultImportCustomizer.build().addClassImports(LifeCycleHook.class, LifeCycleHook.Context.class).create());
}
public static GremlinServerGremlinPlugin instance() {
return instance;
}
}
|
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/jsr223/GremlinServerGremlinPlugin.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.tinkerpop.gremlin.server.jsr223;
import org.apache.tinkerpop.gremlin.jsr223.AbstractGremlinPlugin;
import org.apache.tinkerpop.gremlin.jsr223.GremlinPlugin;
import org.apache.tinkerpop.gremlin.jsr223.DefaultImportCustomizer;
import org.apache.tinkerpop.gremlin.server.util.LifeCycleHook;
/**
* A {@link GremlinPlugin} implementation that adds Gremlin Server specific classes to the imports.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public final class GremlinServerGremlinPlugin extends AbstractGremlinPlugin {
private static final String MODULE_NAME = "tinkerpop.server";
private static final GremlinServerGremlinPlugin instance = new GremlinServerGremlinPlugin();
private GremlinServerGremlinPlugin() {
super(MODULE_NAME, DefaultImportCustomizer.build().addClassImports(LifeCycleHook.class, LifeCycleHook.Context.class).create());
}
public static GremlinServerGremlinPlugin instance() {
return instance;
}
}
|
TINKERPOP-1612 Renamed server-side plugin to not match the driver
The console already holds the "tinkerpop.server" plugin for the driver and remoting. Had to name this one something else.
|
gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/jsr223/GremlinServerGremlinPlugin.java
|
TINKERPOP-1612 Renamed server-side plugin to not match the driver
|
|
Java
|
apache-2.0
|
272ac95222ef353fb151fbe25d30dca60faca2a1
| 0
|
liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* 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.jkiss.dbeaver.ui.actions.datasource;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.menus.UIElement;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.navigator.DBNModel;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.DBSObjectSelector;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.actions.AbstractDataSourceHandler;
import org.jkiss.dbeaver.ui.perspective.SelectDatabaseDialog;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.*;
public class SelectActiveSchemaHandler extends AbstractDataSourceHandler implements IElementUpdater {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
DBPDataSourceContainer dataSourceContainer = DataSourceToolbarUtils.getCurrentDataSource(HandlerUtil.getActiveWorkbenchWindow(event));
if (dataSourceContainer == null) {
log.debug("No active connection. Action is in disabled state.");
return null;
}
DatabaseListReader databaseListReader = new DatabaseListReader(dataSourceContainer.getDataSource());
try {
UIUtils.runInProgressService(databaseListReader);
} catch (InvocationTargetException e) {
DBWorkbench.getPlatformUI().showError("Schema list", "Error reading schema list", e.getTargetException());
return null;
} catch (InterruptedException e) {
return null;
}
DBNDatabaseNode selectedDB = null;
for (DBNDatabaseNode node : databaseListReader.nodeList) {
if (node.getObject() == databaseListReader.active) {
selectedDB = node;
}
}
SelectDatabaseDialog dialog = new SelectDatabaseDialog(
HandlerUtil.getActiveShell(event),
dataSourceContainer,
databaseListReader.currentDatabaseInstanceName,
databaseListReader.nodeList,
selectedDB == null ? null : Collections.singletonList(selectedDB));
dialog.setModeless(true);
if (dialog.open() == IDialogConstants.CANCEL_ID) {
return null;
}
DBNDatabaseNode node = dialog.getSelectedObject();
if (node != null && node != databaseListReader.active) {
// Change current schema
changeDataBaseSelection(dataSourceContainer, databaseListReader.currentDatabaseInstanceName, dialog.getCurrentInstanceName(), node.getNodeName());
}
return null;
}
@Override
public void updateElement(UIElement element, Map parameters) {
IWorkbenchWindow workbenchWindow = element.getServiceLocator().getService(IWorkbenchWindow.class);
if (workbenchWindow == null || workbenchWindow.getActivePage() == null) {
return;
}
IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor == null) {
return;
}
String schemaName = "<No active connection>";
DBIcon schemaIcon = DBIcon.TREE_SCHEMA;
String schemaTooltip = CoreMessages.toolbar_datasource_selector_combo_database_tooltip;
DBPDataSourceContainer dataSource = DataSourceToolbarUtils.getCurrentDataSource(workbenchWindow);
if (dataSource != null && dataSource.isConnected()) {
schemaName = "<no schema>";
DBSObject defObject = getSelectedSchema(dataSource);
if (defObject != null) {
schemaName = defObject.getName();
schemaIcon = DBIcon.TREE_SCHEMA;
}
}
element.setText(schemaName);
element.setIcon(DBeaverIcons.getImageDescriptor(schemaIcon));
element.setTooltip(schemaTooltip);
}
public static DBSObject getSelectedSchema(DBPDataSourceContainer dataSource) {
//DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, executionContext.getDataSource());
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
//objectContainer = (DBSObjectContainer) defObject;
return objectSelector.getDefaultObject();
}
}
}
return null;
}
private static void changeDataBaseSelection(DBPDataSourceContainer dsContainer, @Nullable String curInstanceName, @Nullable String newInstanceName, @NotNull String newSchemaName) {
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (os != null) {
if (newInstanceName != null && !CommonUtils.equalObjects(curInstanceName, newInstanceName)) {
// Change current instance
DBSObject newInstance = oc.getChild(monitor, newInstanceName);
if (newInstance != null) {
os.setDefaultObject(monitor, newInstance);
}
}
final DBSObject defObject = os.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// USe seconds level of active object
DBSObjectSelector os2 = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (os2 != null && os2.supportsDefaultChange()) {
oc = (DBSObjectContainer) defObject;
os = os2;
}
}
}
if (oc != null && os != null && os.supportsDefaultChange()) {
DBSObject newChild = oc.getChild(monitor, newSchemaName);
if (newChild != null) {
os.setDefaultObject(monitor, newChild);
} else {
throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newSchemaName));
}
} else {
throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported);
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
private static class DatabaseListReader implements DBRRunnableWithProgress {
private final DBPDataSource dataSource;
private final List<DBNDatabaseNode> nodeList = new ArrayList<>();
// Remote instance node
private DBSObject active;
private boolean enabled;
private String currentDatabaseInstanceName;
DatabaseListReader(DBPDataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectContainer == null || objectSelector == null) {
return;
}
try {
monitor.beginTask(CoreMessages.toolbar_datasource_selector_action_read_databases, 1);
currentDatabaseInstanceName = null;
Class<? extends DBSObject> childType = objectContainer.getChildType(monitor);
if (childType == null || !DBSObjectContainer.class.isAssignableFrom(childType)) {
enabled = false;
} else {
enabled = true;
DBNModel navigatorModel = DBWorkbench.getPlatform().getNavigatorModel();
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
currentDatabaseInstanceName = defObject.getName();
objectContainer = (DBSObjectContainer) defObject;
defObject = objectSelector.getDefaultObject();
}
}
Collection<? extends DBSObject> children = objectContainer.getChildren(monitor);
active = defObject;
// Cache navigator nodes
if (children != null) {
for (DBSObject child : children) {
if (DBUtils.getAdapter(DBSObjectContainer.class, child) != null) {
DBNDatabaseNode node = navigatorModel.getNodeByObject(monitor, child, false);
if (node != null) {
nodeList.add(node);
}
}
}
}
}
} catch (DBException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
}
public static class MenuContributor extends DataSourceMenuContributor {
@Override
protected void fillContributionItems(List<IContributionItem> menuItems) {
DBPDataSourceContainer dataSourceContainer = DataSourceToolbarUtils.getCurrentDataSource(UIUtils.getActiveWorkbenchWindow());
if (dataSourceContainer == null) {
return;
}
DatabaseListReader databaseListReader = new DatabaseListReader(dataSourceContainer.getDataSource());
try {
UIUtils.runInProgressService(databaseListReader);
} catch (InvocationTargetException e) {
DBWorkbench.getPlatformUI().showError("Schema list", "Error reading schema list", e.getTargetException());
return;
} catch (InterruptedException e) {
return;
}
DBSObject defObject = getSelectedSchema(dataSourceContainer);
for (DBNDatabaseNode node : databaseListReader.nodeList) {
menuItems.add(
new ActionContributionItem(new Action(node.getName(), Action.AS_CHECK_BOX) {
{
setImageDescriptor(DBeaverIcons.getImageDescriptor(node.getNodeIcon()));
}
@Override
public boolean isChecked() {
return node.getObject() == defObject;
}
@Override
public void run() {
changeDataBaseSelection(dataSourceContainer, databaseListReader.currentDatabaseInstanceName, databaseListReader.currentDatabaseInstanceName, node.getNodeName());
}
}
));
}
}
}
}
|
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/actions/datasource/SelectActiveSchemaHandler.java
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.org)
*
* 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.jkiss.dbeaver.ui.actions.datasource;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.commands.IElementUpdater;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.menus.UIElement;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.CoreMessages;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.navigator.DBNModel;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectContainer;
import org.jkiss.dbeaver.model.struct.DBSObjectSelector;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.actions.AbstractDataSourceHandler;
import org.jkiss.dbeaver.ui.perspective.SelectDatabaseDialog;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.utils.CommonUtils;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.*;
public class SelectActiveSchemaHandler extends AbstractDataSourceHandler implements IElementUpdater {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
DBPDataSourceContainer dataSourceContainer = DataSourceToolbarUtils.getCurrentDataSource(HandlerUtil.getActiveWorkbenchWindow(event));
if (dataSourceContainer == null) {
log.debug("No active connection. Action is in disabled state.");
return null;
}
DatabaseListReader databaseListReader = new DatabaseListReader(dataSourceContainer.getDataSource());
try {
UIUtils.runInProgressService(databaseListReader);
} catch (InvocationTargetException e) {
DBWorkbench.getPlatformUI().showError("Schema list", "Error reading schema list", e.getTargetException());
return null;
} catch (InterruptedException e) {
return null;
}
DBNDatabaseNode selectedDB = null;
for (DBNDatabaseNode node : databaseListReader.nodeList) {
if (node.getObject() == databaseListReader.active) {
selectedDB = node;
}
}
SelectDatabaseDialog dialog = new SelectDatabaseDialog(
HandlerUtil.getActiveShell(event),
dataSourceContainer,
databaseListReader.currentDatabaseInstanceName,
databaseListReader.nodeList,
selectedDB == null ? null : Collections.singletonList(selectedDB));
dialog.setModeless(true);
if (dialog.open() == IDialogConstants.CANCEL_ID) {
return null;
}
DBNDatabaseNode node = dialog.getSelectedObject();
if (node != null && node != databaseListReader.active) {
// Change current schema
changeDataBaseSelection(dataSourceContainer, databaseListReader.currentDatabaseInstanceName, dialog.getCurrentInstanceName(), node.getNodeName());
}
return null;
}
@Override
public void updateElement(UIElement element, Map parameters) {
IWorkbenchWindow workbenchWindow = element.getServiceLocator().getService(IWorkbenchWindow.class);
if (workbenchWindow == null || workbenchWindow.getActivePage() == null) {
return;
}
IEditorPart activeEditor = workbenchWindow.getActivePage().getActiveEditor();
if (activeEditor == null) {
return;
}
String schemaName = "<No active connection>";
DBIcon schemaIcon = DBIcon.TREE_SCHEMA;
String schemaTooltip = CoreMessages.toolbar_datasource_selector_combo_database_tooltip;
DBPDataSourceContainer dataSource = DataSourceToolbarUtils.getCurrentDataSource(workbenchWindow);
if (dataSource != null && dataSource.isConnected()) {
schemaName = "<no schema>";
//DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, executionContext.getDataSource());
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
//objectContainer = (DBSObjectContainer) defObject;
defObject = objectSelector.getDefaultObject();
}
}
if (defObject != null) {
schemaName = defObject.getName();
schemaIcon = DBIcon.TREE_SCHEMA;
}
}
}
element.setText(schemaName);
element.setIcon(DBeaverIcons.getImageDescriptor(schemaIcon));
element.setTooltip(schemaTooltip);
}
private void changeDataBaseSelection(DBPDataSourceContainer dsContainer, @Nullable String curInstanceName, @Nullable String newInstanceName, @NotNull String newSchemaName) {
if (dsContainer != null && dsContainer.isConnected()) {
final DBPDataSource dataSource = dsContainer.getDataSource();
new AbstractJob("Change active database") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (os != null) {
if (newInstanceName != null && !CommonUtils.equalObjects(curInstanceName, newInstanceName)) {
// Change current instance
DBSObject newInstance = oc.getChild(monitor, newInstanceName);
if (newInstance != null) {
os.setDefaultObject(monitor, newInstance);
}
}
final DBSObject defObject = os.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// USe seconds level of active object
DBSObjectSelector os2 = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (os2 != null && os2.supportsDefaultChange()) {
oc = (DBSObjectContainer) defObject;
os = os2;
}
}
}
if (oc != null && os != null && os.supportsDefaultChange()) {
DBSObject newChild = oc.getChild(monitor, newSchemaName);
if (newChild != null) {
os.setDefaultObject(monitor, newChild);
} else {
throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newSchemaName));
}
} else {
throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported);
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
}
}
private class DatabaseListReader implements DBRRunnableWithProgress {
private final DBPDataSource dataSource;
private final List<DBNDatabaseNode> nodeList = new ArrayList<>();
// Remote instance node
private DBSObject active;
private boolean enabled;
private String currentDatabaseInstanceName;
public DatabaseListReader(DBPDataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
if (objectContainer == null || objectSelector == null) {
return;
}
try {
monitor.beginTask(CoreMessages.toolbar_datasource_selector_action_read_databases, 1);
currentDatabaseInstanceName = null;
Class<? extends DBSObject> childType = objectContainer.getChildType(monitor);
if (childType == null || !DBSObjectContainer.class.isAssignableFrom(childType)) {
enabled = false;
} else {
enabled = true;
DBNModel navigatorModel = DBWorkbench.getPlatform().getNavigatorModel();
DBSObject defObject = objectSelector.getDefaultObject();
if (defObject instanceof DBSObjectContainer) {
// Default object can be object container + object selector (e.g. in PG)
objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
if (objectSelector != null && objectSelector.supportsDefaultChange()) {
currentDatabaseInstanceName = defObject.getName();
objectContainer = (DBSObjectContainer) defObject;
defObject = objectSelector.getDefaultObject();
}
}
Collection<? extends DBSObject> children = objectContainer.getChildren(monitor);
active = defObject;
// Cache navigator nodes
if (children != null) {
for (DBSObject child : children) {
if (DBUtils.getAdapter(DBSObjectContainer.class, child) != null) {
DBNDatabaseNode node = navigatorModel.getNodeByObject(monitor, child, false);
if (node != null) {
nodeList.add(node);
}
}
}
}
}
} catch (DBException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
}
public static class MenuContributor extends DataSourceMenuContributor {
@Override
protected void fillContributionItems(List<IContributionItem> menuItems) {
}
}
}
|
#4553 Schema list reading
|
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/actions/datasource/SelectActiveSchemaHandler.java
|
#4553 Schema list reading
|
|
Java
|
apache-2.0
|
43db180e6c687a506ee40edbd053533ff8c0db40
| 0
|
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
|
package org.slc.sli.ingestion.transformation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.uuid.Type1UUIDGeneratorStrategy;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.ingestion.NeutralRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
/**
* Transforms disjoint set of attendance events into cleaner set of {school year : list of attendance events} mappings and
* stores in the appropriate student-school or student-section associations.
*
* @author shalka
*/
@Component("attendanceTransformationStrategy")
public class AttendanceTransformer extends AbstractTransformationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(AttendanceTransformer.class);
private Map<String, Map<Object, NeutralRecord>> collections;
private Map<String, Map<Object, NeutralRecord>> transformedCollections;
/**
* Default constructor.
*/
public AttendanceTransformer() {
collections = new HashMap<String, Map<Object, NeutralRecord>>();
transformedCollections = new HashMap<String, Map<Object, NeutralRecord>>();
}
/**
* The chaining of transformation steps. This implementation assumes that all data will be
* processed in "one-go."
*/
@Override
public void performTransformation() {
loadData();
transform();
persist();
}
/**
* Pre-requisite interchanges for daily attendance data to be successfully transformed:
* student, education organization, education organization calendar, master schedule,
* student enrollment
*/
public void loadData() {
LOG.info("Loading data for attendance transformation.");
List<String> collectionsToLoad = Arrays.asList(EntityNames.STUDENT_SCHOOL_ASSOCIATION);
for (String collectionName : collectionsToLoad) {
Map<Object, NeutralRecord> collection = getCollectionFromDb(collectionName);
collections.put(collectionName, collection);
LOG.info("{} is loaded into local storage. Total Count = {}", collectionName, collection.size());
}
LOG.info("Finished loading data for attendance transformation.");
}
/**
* Transforms attendance events from Ed-Fi model into SLI model.
*/
public void transform() {
LOG.debug("Transforming daily attendance data");
HashMap<Object, NeutralRecord> newCollection = new HashMap<Object, NeutralRecord>();
Set<Pair<String, String>> studentSchoolPairs = new HashSet<Pair<String, String>>();
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collections.get(EntityNames.STUDENT_SCHOOL_ASSOCIATION).entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
Map<String, Object> attributes = neutralRecord.getAttributes();
String studentId = (String) attributes.get("studentId");
String schoolId = (String) attributes.get("schoolId");
if (studentSchoolPairs.contains(Pair.of(studentId, schoolId))) {
LOG.info("Already assembled attendance data for student: {} at school: {}", studentId, schoolId);
} else {
studentSchoolPairs.add(Pair.of(studentId, schoolId));
NeutralRecord attendanceRecord = createTransformedAttendanceRecord();
Map<String, Object> attendanceAttributes = attendanceRecord.getAttributes();
attendanceAttributes.put("studentId", studentId);
attendanceAttributes.put("schoolId", schoolId);
Map<Object, NeutralRecord> studentAttendance = getAttendanceEvents(studentId);
Map<Object, NeutralRecord> sessions = getSessions(studentId, schoolId);
// LOG.info("For student with id: {} in school: {}", studentId, schoolId);
// LOG.info(" Found {} associated sessions.", sessions.size());
// LOG.info(" Found {} attendance events.", studentAttendance.size());
Map<String, Object> schoolYears = mapAttendanceIntoSchoolYears(studentAttendance, sessions);
if (schoolYears.entrySet().size() > 0) {
List<Map<String, Object>> daily = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, Object> entry : schoolYears.entrySet()) {
String schoolYear = (String) entry.getKey();
@SuppressWarnings("unchecked")
List<Map<String, Object>> events = (List<Map<String, Object>>) entry.getValue();
Map<String, Object> attendance = new HashMap<String, Object>();
attendance.put("schoolYear", schoolYear);
attendance.put("attendanceEvent", events);
daily.add(attendance);
}
attendanceAttributes.put("schoolYearAttendance", daily);
attendanceRecord.setAttributes(attendanceAttributes);
newCollection.put(attendanceRecord.getRecordId(), attendanceRecord);
// } else {
// LOG.warn(" No daily attendance for student: {}", studentId);
}
}
}
transformedCollections.put(EntityNames.ATTENDANCE, newCollection);
LOG.info("Finished transforming daily attendance data for {} student-school associations.", newCollection.entrySet().size());
}
/**
* Creates a Neutral Record of type 'dailyAttendance'.
* @return newly created 'dailyAttendance' Neutral Record.
*/
private NeutralRecord createTransformedAttendanceRecord() {
NeutralRecord record = new NeutralRecord();
Type1UUIDGeneratorStrategy uuidGenerator = new Type1UUIDGeneratorStrategy();
record.setRecordId(uuidGenerator.randomUUID().toString());
record.setRecordType(EntityNames.ATTENDANCE);
return record;
}
/**
* Persists the transformed data into mongo.
*/
public void persist() {
LOG.info("Persisting transformed data into attendance_transformed staging collection.");
for (Map.Entry<String, Map<Object, NeutralRecord>> collectionEntry : transformedCollections.entrySet()) {
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collectionEntry.getValue().entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
neutralRecord.setRecordType(neutralRecord.getRecordType() + "_transformed");
getNeutralRecordMongoAccess().getRecordRepository().create(neutralRecord);
}
}
LOG.info("Finished persisting transformed data into attendance_transformed staging collection.");
}
/**
* Returns all collection entities found in temp ingestion database
*
* @param collectionName
*/
private Map<Object, NeutralRecord> getCollectionFromDb(String collectionName) {
Criteria jobIdCriteria = Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId());
@SuppressWarnings("deprecation")
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByQuery(collectionName,
new Query(jobIdCriteria), 0, 0);
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr;
Iterator<NeutralRecord> neutralRecordIterator = data.iterator();
while (neutralRecordIterator.hasNext()) {
tempNr = neutralRecordIterator.next();
collection.put(tempNr.getRecordId(), tempNr);
}
return collection;
}
/**
* Gets attendance events for the specified student.
* @param studentId StudentUniqueStateId for student.
* @return Map of Attendance Events for student.
*/
private Map<Object, NeutralRecord> getAttendanceEvents(String studentId) {
NeutralQuery query = new NeutralQuery();
query.setLimit(0);
query.addCriteria(new NeutralCriteria("studentId", "=", studentId));
Iterable<NeutralRecord> records = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.ATTENDANCE, query);
Map<Object, NeutralRecord> studentAttendance = new HashMap<Object, NeutralRecord>();
if (records != null) {
for (NeutralRecord record : records) {
studentAttendance.put(record.getRecordId(), record);
}
}
return studentAttendance;
}
/**
* Gets all sessions associated with the specified student-school pair.
* @param studentId StudentUniqueStateId for student.
* @param schoolId StateOrganizationId for school.
* @return Map of Sessions for student-school pair.
*/
private Map<Object, NeutralRecord> getSessions(String studentId, String schoolId) {
NeutralQuery query = new NeutralQuery();
query.setLimit(0);
query.addCriteria(new NeutralCriteria("studentId", "=", studentId));
Iterable<NeutralRecord> associations = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.STUDENT_SECTION_ASSOCIATION, query);
Map<Object, NeutralRecord> studentSchoolSessions = new HashMap<Object, NeutralRecord>();
if (associations != null) {
List<String> sectionIds = new ArrayList<String>();
for (NeutralRecord association : associations) {
Map<String, Object> associationAttributes = association.getAttributes();
String sectionId = (String) associationAttributes.get("sectionId");
sectionIds.add(sectionId);
}
NeutralQuery sectionQuery = new NeutralQuery();
sectionQuery.setLimit(0);
sectionQuery.addCriteria(new NeutralCriteria("schoolId", "=", schoolId));
sectionQuery.addCriteria(new NeutralCriteria("uniqueSectionCode", "=", sectionIds));
Iterable<NeutralRecord> sections = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.SECTION, sectionQuery);
if (sections != null) {
List<String> sessionIds = new ArrayList<String>();
for (NeutralRecord section : sections) {
Map<String, Object> sectionAttributes = section.getAttributes();
String sessionId = (String) sectionAttributes.get("sessionId");
sessionIds.add(sessionId);
}
NeutralQuery sessionQuery = new NeutralQuery();
sessionQuery.addCriteria(new NeutralCriteria("sessionName", "=", sessionIds));
Iterable<NeutralRecord> sessions = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.SESSION, sessionQuery);
if (sessions != null) {
for (NeutralRecord session : sessions) {
studentSchoolSessions.put(session.getRecordId(), session);
}
}
}
}
return studentSchoolSessions;
}
/**
* Maps the set of student attendance events into a transformed map of form {school year : list of attendance events} based
* on dates published in the sessions.
* @param studentAttendance Set of student attendance events.
* @param sessions Set of sessions that correspond to the school the student attends.
* @return Map containing transformed attendance information.
*/
private Map<String, Object> mapAttendanceIntoSchoolYears(Map<Object, NeutralRecord> studentAttendance, Map<Object, NeutralRecord> sessions) {
Map<String, Object> schoolYears = new HashMap<String, Object>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get("schoolYear");
DateTime sessionBegin = DateTimeUtil.parseDateTime((String) sessionAttributes.get("beginDate"));
DateTime sessionEnd = DateTimeUtil.parseDateTime((String) sessionAttributes.get("endDate"));
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
for (Iterator<Map.Entry<Object, NeutralRecord>> recordItr = studentAttendance.entrySet().iterator(); recordItr.hasNext(); ) {
Map.Entry<Object, NeutralRecord> record = recordItr.next();
NeutralRecord eventRecord = record.getValue();
Map<String, Object> eventAttributes = eventRecord.getAttributes();
String eventDate = (String) eventAttributes.get("eventDate");
DateTime date = DateTimeUtil.parseDateTime(eventDate);
if (DateTimeUtil.isLeftDateBeforeRightDate(sessionBegin, date) && DateTimeUtil.isLeftDateBeforeRightDate(date, sessionEnd)) {
Map<String, Object> event = new HashMap<String, Object>();
String eventCategory = (String) eventAttributes.get("attendanceEventCategory");
event.put("date", eventDate);
event.put("event", eventCategory);
if (eventAttributes.containsKey("attendanceEventReason")) {
String eventReason = (String) eventAttributes.get("attendanceEventReason");
event.put("reason", eventReason);
}
events.add(event);
recordItr.remove();
}
}
if (events.size() > 0) {
schoolYears.put(schoolYear, events);
}
}
// if student attendance still has attendance events --> orphaned events
Iterator<Map.Entry<Object, NeutralRecord>> recordItr = studentAttendance.entrySet().iterator();
if (recordItr.hasNext()) {
int orphanedEvents = 0;
while (recordItr.hasNext()) {
recordItr.next();
orphanedEvents++;
}
// LOG.warn(" {} attendance events still need to be mapped into a school year.", orphanedEvents);
}
return schoolYears;
}
}
|
sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AttendanceTransformer.java
|
package org.slc.sli.ingestion.transformation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.common.util.datetime.DateTimeUtil;
import org.slc.sli.common.util.uuid.Type1UUIDGeneratorStrategy;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.ingestion.NeutralRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
/**
* Transforms disjoint set of attendance events into cleaner set of {school year : list of attendance events} mappings and
* stores in the appropriate student-school or student-section associations.
*
* @author shalka
*/
@Component("attendanceTransformationStrategy")
public class AttendanceTransformer extends AbstractTransformationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(AttendanceTransformer.class);
private Map<String, Map<Object, NeutralRecord>> collections;
private Map<String, Map<Object, NeutralRecord>> transformedCollections;
/**
* Default constructor.
*/
public AttendanceTransformer() {
collections = new HashMap<String, Map<Object, NeutralRecord>>();
transformedCollections = new HashMap<String, Map<Object, NeutralRecord>>();
}
/**
* The chaining of transformation steps. This implementation assumes that all data will be
* processed in "one-go."
*/
@Override
public void performTransformation() {
loadData();
transform();
persist();
}
/**
* Pre-requisite interchanges for daily attendance data to be successfully transformed:
* student, education organization, education organization calendar, master schedule,
* student enrollment
*/
public void loadData() {
LOG.info("Loading data for attendance transformation.");
List<String> collectionsToLoad = Arrays.asList(EntityNames.STUDENT_SCHOOL_ASSOCIATION);
for (String collectionName : collectionsToLoad) {
Map<Object, NeutralRecord> collection = getCollectionFromDb(collectionName);
collections.put(collectionName, collection);
LOG.info("{} is loaded into local storage. Total Count = {}", collectionName, collection.size());
}
LOG.info("Finished loading data for attendance transformation.");
}
/**
* Transforms attendance events from Ed-Fi model into SLI model.
*/
public void transform() {
LOG.debug("Transforming daily attendance data");
HashMap<Object, NeutralRecord> newCollection = new HashMap<Object, NeutralRecord>();
Set<Pair<String, String>> studentSchoolPairs = new HashSet<Pair<String, String>>();
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collections.get(EntityNames.STUDENT_SCHOOL_ASSOCIATION).entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
Map<String, Object> attributes = neutralRecord.getAttributes();
String studentId = (String) attributes.get("studentId");
String schoolId = (String) attributes.get("schoolId");
if (studentSchoolPairs.contains(Pair.of(studentId, schoolId))) {
LOG.info("Already assembled attendance data for student: {} at school: {}", studentId, schoolId);
} else {
studentSchoolPairs.add(Pair.of(studentId, schoolId));
NeutralRecord attendanceRecord = createTransformedAttendanceRecord();
Map<String, Object> attendanceAttributes = attendanceRecord.getAttributes();
attendanceAttributes.put("studentId", studentId);
attendanceAttributes.put("schoolId", schoolId);
Map<Object, NeutralRecord> studentAttendance = getAttendanceEvents(studentId);
Map<Object, NeutralRecord> sessions = getSessions(studentId, schoolId);
LOG.info("For student with id: {} in school: {}", studentId, schoolId);
LOG.info(" Found {} associated sessions.", sessions.size());
LOG.info(" Found {} attendance events.", studentAttendance.size());
Map<String, Object> schoolYears = mapAttendanceIntoSchoolYears(studentAttendance, sessions);
if (schoolYears.entrySet().size() > 0) {
List<Map<String, Object>> daily = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, Object> entry : schoolYears.entrySet()) {
String schoolYear = (String) entry.getKey();
@SuppressWarnings("unchecked")
List<Map<String, Object>> events = (List<Map<String, Object>>) entry.getValue();
Map<String, Object> attendance = new HashMap<String, Object>();
attendance.put("schoolYear", schoolYear);
attendance.put("attendanceEvent", events);
daily.add(attendance);
}
attendanceAttributes.put("schoolYearAttendance", daily);
attendanceRecord.setAttributes(attendanceAttributes);
newCollection.put(attendanceRecord.getRecordId(), attendanceRecord);
} else {
LOG.warn(" No daily attendance for student: {}", studentId);
}
}
}
transformedCollections.put(EntityNames.ATTENDANCE, newCollection);
LOG.info("Finished transforming daily attendance data for {} student-school associations.", newCollection.entrySet().size());
}
/**
* Creates a Neutral Record of type 'dailyAttendance'.
* @return newly created 'dailyAttendance' Neutral Record.
*/
private NeutralRecord createTransformedAttendanceRecord() {
NeutralRecord record = new NeutralRecord();
record.setRecordId(new Type1UUIDGeneratorStrategy().randomUUID().toString());
record.setRecordType(EntityNames.ATTENDANCE);
return record;
}
/**
* Persists the transformed data into mongo.
*/
public void persist() {
LOG.info("Persisting transformed data into attendance_transformed staging collection.");
for (Map.Entry<String, Map<Object, NeutralRecord>> collectionEntry : transformedCollections.entrySet()) {
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collectionEntry.getValue().entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
neutralRecord.setRecordType(neutralRecord.getRecordType() + "_transformed");
getNeutralRecordMongoAccess().getRecordRepository().create(neutralRecord);
}
}
LOG.info("Finished persisting transformed data into attendance_transformed staging collection.");
}
/**
* Returns all collection entities found in temp ingestion database
*
* @param collectionName
*/
private Map<Object, NeutralRecord> getCollectionFromDb(String collectionName) {
Criteria jobIdCriteria = Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId());
@SuppressWarnings("deprecation")
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByQuery(collectionName,
new Query(jobIdCriteria), 0, 0);
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr;
Iterator<NeutralRecord> neutralRecordIterator = data.iterator();
while (neutralRecordIterator.hasNext()) {
tempNr = neutralRecordIterator.next();
collection.put(tempNr.getRecordId(), tempNr);
}
return collection;
}
/**
* Gets attendance events for the specified student.
* @param studentId StudentUniqueStateId for student.
* @return Map of Attendance Events for student.
*/
private Map<Object, NeutralRecord> getAttendanceEvents(String studentId) {
NeutralQuery query = new NeutralQuery();
query.setLimit(0);
query.addCriteria(new NeutralCriteria("studentId", "=", studentId));
Iterable<NeutralRecord> records = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.ATTENDANCE, query);
Map<Object, NeutralRecord> studentAttendance = new HashMap<Object, NeutralRecord>();
if (records != null) {
for (NeutralRecord record : records) {
studentAttendance.put(record.getRecordId(), record);
}
}
return studentAttendance;
}
/**
* Gets all sessions associated with the specified student-school pair.
* @param studentId StudentUniqueStateId for student.
* @param schoolId StateOrganizationId for school.
* @return Map of Sessions for student-school pair.
*/
private Map<Object, NeutralRecord> getSessions(String studentId, String schoolId) {
NeutralQuery query = new NeutralQuery();
query.setLimit(0);
query.addCriteria(new NeutralCriteria("studentId", "=", studentId));
Iterable<NeutralRecord> associations = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.STUDENT_SECTION_ASSOCIATION, query);
Map<Object, NeutralRecord> studentSchoolSessions = new HashMap<Object, NeutralRecord>();
if (associations != null) {
List<String> sectionIds = new ArrayList<String>();
for (NeutralRecord association : associations) {
Map<String, Object> associationAttributes = association.getAttributes();
String sectionId = (String) associationAttributes.get("sectionId");
sectionIds.add(sectionId);
}
NeutralQuery sectionQuery = new NeutralQuery();
sectionQuery.setLimit(0);
sectionQuery.addCriteria(new NeutralCriteria("schoolId", "=", schoolId));
sectionQuery.addCriteria(new NeutralCriteria("uniqueSectionCode", "=", sectionIds));
Iterable<NeutralRecord> sections = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.SECTION, sectionQuery);
if (sections != null) {
List<String> sessionIds = new ArrayList<String>();
for (NeutralRecord section : sections) {
Map<String, Object> sectionAttributes = section.getAttributes();
String sessionId = (String) sectionAttributes.get("sessionId");
sessionIds.add(sessionId);
}
NeutralQuery sessionQuery = new NeutralQuery();
sessionQuery.addCriteria(new NeutralCriteria("sessionName", "=", sessionIds));
Iterable<NeutralRecord> sessions = getNeutralRecordMongoAccess().getRecordRepository().findAll(EntityNames.SESSION, sessionQuery);
if (sessions != null) {
for (NeutralRecord session : sessions) {
studentSchoolSessions.put(session.getRecordId(), session);
}
}
}
}
return studentSchoolSessions;
}
/**
* Maps the set of student attendance events into a transformed map of form {school year : list of attendance events} based
* on dates published in the sessions.
* @param studentAttendance Set of student attendance events.
* @param sessions Set of sessions that correspond to the school the student attends.
* @return Map containing transformed attendance information.
*/
private Map<String, Object> mapAttendanceIntoSchoolYears(Map<Object, NeutralRecord> studentAttendance, Map<Object, NeutralRecord> sessions) {
Map<String, Object> schoolYears = new HashMap<String, Object>();
for (Map.Entry<Object, NeutralRecord> session : sessions.entrySet()) {
NeutralRecord sessionRecord = session.getValue();
Map<String, Object> sessionAttributes = sessionRecord.getAttributes();
String schoolYear = (String) sessionAttributes.get("schoolYear");
DateTime sessionBegin = DateTimeUtil.parseDateTime((String) sessionAttributes.get("beginDate"));
DateTime sessionEnd = DateTimeUtil.parseDateTime((String) sessionAttributes.get("endDate"));
List<Map<String, Object>> events = new ArrayList<Map<String, Object>>();
for (Iterator<Map.Entry<Object, NeutralRecord>> recordItr = studentAttendance.entrySet().iterator(); recordItr.hasNext(); ) {
Map.Entry<Object, NeutralRecord> record = recordItr.next();
NeutralRecord eventRecord = record.getValue();
Map<String, Object> eventAttributes = eventRecord.getAttributes();
String eventDate = (String) eventAttributes.get("eventDate");
DateTime date = DateTimeUtil.parseDateTime(eventDate);
if (DateTimeUtil.isLeftDateBeforeRightDate(sessionBegin, date) && DateTimeUtil.isLeftDateBeforeRightDate(date, sessionEnd)) {
Map<String, Object> event = new HashMap<String, Object>();
String eventCategory = (String) eventAttributes.get("attendanceEventCategory");
event.put("date", eventDate);
event.put("event", eventCategory);
if (eventAttributes.containsKey("attendanceEventReason")) {
String eventReason = (String) eventAttributes.get("attendanceEventReason");
event.put("reason", eventReason);
}
events.add(event);
recordItr.remove();
}
}
if (events.size() > 0) {
schoolYears.put(schoolYear, events);
}
LOG.info(" {} attendance events for session in school year: {}", events.size(), schoolYear);
}
// if student attendance still has attendance events --> orphaned events
Iterator<Map.Entry<Object, NeutralRecord>> recordItr = studentAttendance.entrySet().iterator();
if (recordItr.hasNext()) {
int orphanedEvents = 0;
while (recordItr.hasNext()) {
recordItr.next();
orphanedEvents++;
}
LOG.warn(" {} attendance events still need to be mapped into a school year.", orphanedEvents);
}
return schoolYears;
}
}
|
fix null pointer exception by instantiating uuid generator strategy before calling randomUUID(), remove extraneous logging
|
sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/AttendanceTransformer.java
|
fix null pointer exception by instantiating uuid generator strategy before calling randomUUID(), remove extraneous logging
|
|
Java
|
apache-2.0
|
f6ea75dbd5b096e5c75afb1666d5d097188a7250
| 0
|
sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,strongbox/strongbox,sbespalov/strongbox
|
package org.carlspring.strongbox.providers.layout;
import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.configuration.ConfigurationManager;
import org.carlspring.strongbox.providers.AbstractMappedProviderRegistry;
import org.carlspring.strongbox.providers.ProviderImplementationException;
import org.carlspring.strongbox.services.ConfigurationManagementService;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.Repository;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author carlspring
*/
@Component
public class LayoutProviderRegistry
extends AbstractMappedProviderRegistry<LayoutProvider>
{
private static final Logger logger = LoggerFactory.getLogger(LayoutProviderRegistry.class);
@Inject
private ConfigurationManager configurationManager;
@Inject
private ConfigurationManagementService configurationManagementService;
@Inject
private Optional<List<LayoutProvider>> layoutProviders;
public static LayoutProvider getLayoutProvider(Repository repository,
LayoutProviderRegistry layoutProviderRegistry)
throws ProviderImplementationException
{
return layoutProviderRegistry.getProvider(repository.getLayout());
}
@Override
@PostConstruct
public void initialize()
{
layoutProviders.ifPresent(providers -> providers.stream().forEach(lp -> addProvider(lp.getAlias(), lp)));
logger.info("Initialized the layout provider registry.");
}
public Configuration getConfiguration()
{
return configurationManager.getConfiguration();
}
public Storage getStorage(String storageId)
{
return configurationManager.getConfiguration().getStorage(storageId);
}
}
|
strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/providers/layout/LayoutProviderRegistry.java
|
package org.carlspring.strongbox.providers.layout;
import org.carlspring.strongbox.configuration.ConfigurationManager;
import org.carlspring.strongbox.configuration.Configuration;
import org.carlspring.strongbox.providers.AbstractMappedProviderRegistry;
import org.carlspring.strongbox.providers.ProviderImplementationException;
import org.carlspring.strongbox.services.ConfigurationManagementService;
import org.carlspring.strongbox.storage.Storage;
import org.carlspring.strongbox.storage.repository.Repository;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author carlspring
*/
@Component
public class LayoutProviderRegistry extends AbstractMappedProviderRegistry<LayoutProvider>
{
private static final Logger logger = LoggerFactory.getLogger(LayoutProviderRegistry.class);
@Inject
private ConfigurationManager configurationManager;
@Inject
private ConfigurationManagementService configurationManagementService;
@Inject
private List<LayoutProvider> layoutProviders;
@Override
@PostConstruct
public void initialize()
{
layoutProviders.stream().forEach(lp -> addProvider(lp.getAlias(), lp));
logger.info("Initialized the layout provider registry.");
}
public static LayoutProvider getLayoutProvider(Repository repository,
LayoutProviderRegistry layoutProviderRegistry)
throws ProviderImplementationException
{
return layoutProviderRegistry.getProvider(repository.getLayout());
}
public Configuration getConfiguration()
{
return configurationManager.getConfiguration();
}
public Storage getStorage(String storageId)
{
return configurationManager.getConfiguration().getStorage(storageId);
}
}
|
SB-1192 test fixes
|
strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/providers/layout/LayoutProviderRegistry.java
|
SB-1192 test fixes
|
|
Java
|
apache-2.0
|
2877dfbbaeee197dd99993d95108b5cf8fb1c883
| 0
|
eisnerd/mupeace,eisnerd/mupeace,eisnerd/mupeace
|
package com.namelessdev.mpdroid.tools;
import org.a0z.mpd.MPD;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper;
public class SettingsHelper implements OnSharedPreferenceChangeListener {
private static final int DEFAULT_MPD_PORT = 6600;
private static final int DEFAULT_STREAMING_PORT = 8000;
private WifiManager mWifiManager;
private SharedPreferences settings;
private MPDAsyncHelper oMPDAsyncHelper;
public SettingsHelper(ContextWrapper parent, MPDAsyncHelper MPDAsyncHelper) {
// Get Settings and register ourself for updates
settings = PreferenceManager.getDefaultSharedPreferences(parent);// getSharedPreferences("org.pmix", MODE_PRIVATE);
settings.registerOnSharedPreferenceChangeListener(this);
// get reference on WiFi service
mWifiManager = (WifiManager) parent.getSystemService(Context.WIFI_SERVICE);
oMPDAsyncHelper = MPDAsyncHelper;
}
public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
updateSettings();
}
public boolean warningShown() {
return getBooleanSetting("newWarningShown");
}
public void setHostname(String hostname) {
String wifiSSID = getCurrentConfiguredSSID();
settings
.edit()
.putString(getStringWithSSID("hostname", wifiSSID), hostname)
.commit();
}
public boolean updateSettings() {
MPD.setSortByTrackNumber(settings.getBoolean("albumTrackSort", MPD.sortByTrackNumber()));
MPD.setSortAlbumsByYear(settings.getBoolean("sortAlbumsByYear", MPD.sortAlbumsByYear()));
MPD.setUseAlbumArtist(settings.getBoolean("albumartist", MPD.useAlbumArtist()));
MPD.setShowAlbumTrackCount(settings.getBoolean("showAlbumTrackCount", MPD.showAlbumTrackCount()));
// MPD.setShowArtistAlbumCount(settings.getBoolean("showArtistAlbumCount", MPD.showArtistAlbumCount()));
return updateConnectionSettings();
}
public boolean updateConnectionSettings(){
return updateConnectionSettings(getCurrentConfiguredSSID());
}
private boolean updateConnectionSettings(String wifiSSID) {
if (getStringSetting(getStringWithSSID("hostname", wifiSSID)) == null)
return false;
oMPDAsyncHelper.getConnectionSettings().sServer = getStringSetting(getStringWithSSID("hostname", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().iPort = getIntegerSetting(getStringWithSSID("port", wifiSSID), DEFAULT_MPD_PORT);
oMPDAsyncHelper.getConnectionSettings().sPassword = getStringSetting(getStringWithSSID("password", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().sServerStreaming = getStringSetting(getStringWithSSID("hostnameStreaming", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().iPortStreaming = getIntegerSetting(getStringWithSSID("portStreaming", wifiSSID), DEFAULT_STREAMING_PORT);
oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = getStringSetting(getStringWithSSID("suffixStreaming", wifiSSID));
if (oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming == null)
oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = "";
return true;
}
private int getIntegerSetting(String name, int defaultValue) {
try {
return Integer.parseInt(settings.getString(name, Integer.toString(defaultValue)).trim());
} catch (NumberFormatException e) {
return DEFAULT_MPD_PORT;
}
}
private String getStringSetting(String name) {
String value = settings.getString(name, "").trim();
if (value.equals(""))
return null;
else
return value;
}
private boolean getBooleanSetting(String name) {
return settings.getBoolean(name, false);
}
private String getCurrentConfiguredSSID() {
String wifiSSID = getCurrentSSID();
return
getStringSetting(getStringWithSSID("hostname", wifiSSID)) == null ? null :
wifiSSID == null || wifiSSID.trim().equals("") ? null :
wifiSSID;
}
private String getCurrentSSID() {
WifiInfo info = mWifiManager.getConnectionInfo();
final String ssid = info.getSSID();
return ssid == null ? null : ssid.replace("\"", "");
}
private String getStringWithSSID(String param, String wifiSSID) {
if (wifiSSID == null)
return param;
else
return wifiSSID + param;
}
}
|
MPDroid/src/com/namelessdev/mpdroid/tools/SettingsHelper.java
|
package com.namelessdev.mpdroid.tools;
import org.a0z.mpd.MPD;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper;
public class SettingsHelper implements OnSharedPreferenceChangeListener {
private static final int DEFAULT_MPD_PORT = 6600;
private static final int DEFAULT_STREAMING_PORT = 8000;
private WifiManager mWifiManager;
private SharedPreferences settings;
private MPDAsyncHelper oMPDAsyncHelper;
public SettingsHelper(ContextWrapper parent, MPDAsyncHelper MPDAsyncHelper) {
// Get Settings and register ourself for updates
settings = PreferenceManager.getDefaultSharedPreferences(parent);// getSharedPreferences("org.pmix", MODE_PRIVATE);
settings.registerOnSharedPreferenceChangeListener(this);
// get reference on WiFi service
mWifiManager = (WifiManager) parent.getSystemService(Context.WIFI_SERVICE);
oMPDAsyncHelper = MPDAsyncHelper;
}
public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
updateSettings();
}
public boolean warningShown() {
return getBooleanSetting("newWarningShown");
}
public void setHostname(String hostname) {
String wifiSSID = getCurrentConfiguredSSID();
settings
.edit()
.putString(getStringWithSSID("hostname", wifiSSID), hostname)
.commit();
}
public boolean updateSettings() {
MPD.setSortByTrackNumber(settings.getBoolean("albumTrackSort", MPD.sortByTrackNumber()));
MPD.setSortAlbumsByYear(settings.getBoolean("sortAlbumsByYear", MPD.sortAlbumsByYear()));
MPD.setUseAlbumArtist(settings.getBoolean("albumartist", MPD.useAlbumArtist()));
MPD.setShowAlbumTrackCount(settings.getBoolean("showAlbumTrackCount", MPD.showAlbumTrackCount()));
// MPD.setShowArtistAlbumCount(settings.getBoolean("showArtistAlbumCount", MPD.showArtistAlbumCount()));
return updateConnectionSettings();
}
public boolean updateConnectionSettings(){
return updateConnectionSettings(getCurrentConfiguredSSID());
}
private boolean updateConnectionSettings(String wifiSSID) {
if (getStringSetting(getStringWithSSID("hostname", wifiSSID)) == null)
return false;
oMPDAsyncHelper.getConnectionSettings().sServer = getStringSetting(getStringWithSSID("hostname", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().iPort = getIntegerSetting(getStringWithSSID("port", wifiSSID), DEFAULT_MPD_PORT);
oMPDAsyncHelper.getConnectionSettings().sPassword = getStringSetting(getStringWithSSID("password", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().sServerStreaming = getStringSetting(getStringWithSSID("hostnameStreaming", wifiSSID));
oMPDAsyncHelper.getConnectionSettings().iPortStreaming = getIntegerSetting(getStringWithSSID("portStreaming", wifiSSID), DEFAULT_STREAMING_PORT);
oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = getStringSetting(getStringWithSSID("suffixStreaming", wifiSSID));
if (oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming == null)
oMPDAsyncHelper.getConnectionSettings().sSuffixStreaming = "";
return true;
}
private int getIntegerSetting(String name, int defaultValue) {
try {
return Integer.parseInt(settings.getString(name, Integer.toString(defaultValue)).trim());
} catch (NumberFormatException e) {
return DEFAULT_MPD_PORT;
}
}
private String getStringSetting(String name) {
String value = settings.getString(name, "").trim();
if (value.equals(""))
return null;
else
return value;
}
private boolean getBooleanSetting(String name) {
return settings.getBoolean(name, false);
}
private String getCurrentConfiguredSSID() {
String wifiSSID = getCurrentSSID();
return
getStringSetting(getStringWithSSID("hostname", wifiSSID)) == null ? null :
wifiSSID.trim().equals("") ? null :
wifiSSID;
}
private String getCurrentSSID() {
WifiInfo info = mWifiManager.getConnectionInfo();
final String ssid = info.getSSID();
return ssid == null ? null : ssid.replace("\"", "");
}
private String getStringWithSSID(String param, String wifiSSID) {
if (wifiSSID == null)
return param;
else
return wifiSSID + param;
}
}
|
Zeroconf connection chooser from the action bar
correction
|
MPDroid/src/com/namelessdev/mpdroid/tools/SettingsHelper.java
|
Zeroconf connection chooser from the action bar
|
|
Java
|
apache-2.0
|
376755b0ade8c49e14eaff83ab5a438e7a5efc3f
| 0
|
cedral/aws-sdk-cpp,ambasta/aws-sdk-cpp,svagionitis/aws-sdk-cpp,jt70471/aws-sdk-cpp,jt70471/aws-sdk-cpp,ambasta/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,svagionitis/aws-sdk-cpp,jt70471/aws-sdk-cpp,cedral/aws-sdk-cpp,jt70471/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,awslabs/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,ambasta/aws-sdk-cpp,ambasta/aws-sdk-cpp,aws/aws-sdk-cpp,svagionitis/aws-sdk-cpp,svagionitis/aws-sdk-cpp,aws/aws-sdk-cpp,cedral/aws-sdk-cpp,cedral/aws-sdk-cpp,cedral/aws-sdk-cpp,awslabs/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,cedral/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,svagionitis/aws-sdk-cpp,jt70471/aws-sdk-cpp,aws/aws-sdk-cpp,awslabs/aws-sdk-cpp,jt70471/aws-sdk-cpp,JoyIfBam5/aws-sdk-cpp,svagionitis/aws-sdk-cpp,awslabs/aws-sdk-cpp,aws/aws-sdk-cpp,aws/aws-sdk-cpp,aws/aws-sdk-cpp
|
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.util.awsclientgenerator.generators.cpp.sqs;
import com.amazonaws.util.awsclientgenerator.domainmodels.SdkFileEntry;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ServiceModel;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.Shape;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ShapeMember;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.cpp.CppViewHelper;
import com.amazonaws.util.awsclientgenerator.generators.cpp.QueryCppClientGenerator;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import java.util.HashMap;
public class SQSQueryXmlCppClientGenerator extends QueryCppClientGenerator {
public SQSQueryXmlCppClientGenerator() throws Exception {
super();
}
@Override
public SdkFileEntry[] generateSourceFiles(ServiceModel serviceModel) throws Exception {
Shape queueAttributeNameShape = serviceModel.getShapes().get("QueueAttributeName");
//currently SQS doesn't model some values that can be returned as "members" of the QueueAttributeName enum
//this is not the right solution. The right solution is to add a separate enum for use for ReceiveMessageRequest
//but backwards compatibility and all that...
//anyways, add the missing values here.
if(queueAttributeNameShape != null) {
queueAttributeNameShape.getEnumValues().add(0, "All");
queueAttributeNameShape.getEnumValues().add("SentTimestamp");
queueAttributeNameShape.getEnumValues().add("ApproximateFirstReceiveTimestamp");
queueAttributeNameShape.getEnumValues().add("ApproximateReceiveCount");
queueAttributeNameShape.getEnumValues().add("SenderId");
}
return super.generateSourceFiles(serviceModel);
}
@Override
protected SdkFileEntry generateClientSourceFile(final ServiceModel serviceModel) throws Exception {
Template template = velocityEngine.getTemplate("/com/amazonaws/util/awsclientgenerator/velocity/cpp/sqs/SQSServiceClientSource.vm");
VelocityContext context = createContext(serviceModel);
context.put("CppViewHelper", CppViewHelper.class);
String fileName = String.format("source/%sClient.cpp", serviceModel.getMetadata().getClassNamePrefix());
return makeFile(template, context, fileName);
}
}
|
code-generation/generator/src/main/java/com/amazonaws/util/awsclientgenerator/generators/cpp/sqs/SQSQueryXmlCppClientGenerator.java
|
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.util.awsclientgenerator.generators.cpp.sqs;
import com.amazonaws.util.awsclientgenerator.domainmodels.SdkFileEntry;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.ServiceModel;
import com.amazonaws.util.awsclientgenerator.domainmodels.codegeneration.cpp.CppViewHelper;
import com.amazonaws.util.awsclientgenerator.generators.cpp.QueryCppClientGenerator;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class SQSQueryXmlCppClientGenerator extends QueryCppClientGenerator {
public SQSQueryXmlCppClientGenerator() throws Exception {
super();
}
@Override
protected SdkFileEntry generateClientSourceFile(final ServiceModel serviceModel) throws Exception {
Template template = velocityEngine.getTemplate("/com/amazonaws/util/awsclientgenerator/velocity/cpp/sqs/SQSServiceClientSource.vm");
VelocityContext context = createContext(serviceModel);
context.put("CppViewHelper", CppViewHelper.class);
String fileName = String.format("source/%sClient.cpp", serviceModel.getMetadata().getClassNamePrefix());
return makeFile(template, context, fileName);
}
}
|
Added SentTimestamp, approximateFirstReceiveTimestamp, ApproximateReceiveCount, and SenderId to QueueAttributeName for SQS.
|
code-generation/generator/src/main/java/com/amazonaws/util/awsclientgenerator/generators/cpp/sqs/SQSQueryXmlCppClientGenerator.java
|
Added SentTimestamp, approximateFirstReceiveTimestamp, ApproximateReceiveCount, and SenderId to QueueAttributeName for SQS.
|
|
Java
|
apache-2.0
|
fda57c734d1dd85a676570e9bfc4add6d06e95c7
| 0
|
klausw/hackerskeyboard,klausw/hackerskeyboard,klausw/hackerskeyboard,klausw/hackerskeyboard
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.LatinIMEUtil.RingCharBuffer;
import com.android.inputmethod.voice.FieldContext;
import com.android.inputmethod.voice.SettingsUtil;
import com.android.inputmethod.voice.VoiceInput;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.media.AudioManager;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.speech.SpeechRecognizer;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodService
implements LatinKeyboardBaseView.OnKeyboardActionListener,
VoiceInput.UiListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIME";
private static final boolean PERF_DEBUG = false;
static final boolean DEBUG = false;
static final boolean TRACE = false;
static final boolean VOICE_INSTALLED = true;
static final boolean ENABLE_VOICE_BUTTON = true;
private static final String PREF_VIBRATE_ON = "vibrate_on";
private static final String PREF_SOUND_ON = "sound_on";
private static final String PREF_POPUP_ON = "popup_on";
private static final String PREF_AUTO_CAP = "auto_cap";
private static final String PREF_QUICK_FIXES = "quick_fixes";
private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions";
private static final String PREF_AUTO_COMPLETE = "auto_complete";
//private static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion";
private static final String PREF_VOICE_MODE = "voice_mode";
// Whether or not the user has used voice input before (and thus, whether to show the
// first-run warning dialog or not).
private static final String PREF_HAS_USED_VOICE_INPUT = "has_used_voice_input";
// Whether or not the user has used voice input from an unsupported locale UI before.
// For example, the user has a Chinese UI but activates voice input.
private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE =
"has_used_voice_input_unsupported_locale";
// A list of locales which are supported by default for voice input, unless we get a
// different list from Gservices.
public static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
"en " +
"en_US " +
"en_GB " +
"en_AU " +
"en_CA " +
"en_IE " +
"en_IN " +
"en_NZ " +
"en_SG " +
"en_ZA ";
// The private IME option used to indicate that no microphone should be shown for a
// given text field. For instance this is specified by the search dialog when the
// dialog is already showing a voice search button.
private static final String IME_OPTION_NO_MICROPHONE = "nm";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_INPUT_LANGUAGE = "input_language";
private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled";
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_START_TUTORIAL = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 4;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
static final int KEYCODE_ENTER = '\n';
static final int KEYCODE_SPACE = ' ';
static final int KEYCODE_PERIOD = '.';
// Contextual menu positions
private static final int POS_METHOD = 0;
private static final int POS_SETTINGS = 1;
//private LatinKeyboardView mInputView;
private LinearLayout mCandidateViewContainer;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mCompletions;
private AlertDialog mOptionsDialog;
private AlertDialog mVoiceWarningDialog;
KeyboardSwitcher mKeyboardSwitcher;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
private Hints mHints;
Resources mResources;
private String mInputLocale;
private String mSystemLocale;
private LanguageSwitcher mLanguageSwitcher;
private StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private int mCommittedLength;
private boolean mPredicting;
private boolean mRecognizing;
private boolean mAfterVoiceInput;
private boolean mImmediatelyAfterVoiceInput;
private boolean mShowingVoiceSuggestions;
private boolean mVoiceInputHighlighted;
private boolean mEnableVoiceButton;
private CharSequence mBestWord;
private boolean mPredictionOn;
private boolean mCompletionOn;
private boolean mHasDictionary;
private boolean mAutoSpace;
private boolean mJustAddedAutoSpace;
private boolean mAutoCorrectEnabled;
private boolean mReCorrectionEnabled;
// Bigram Suggestion is disabled in this version.
private final boolean mBigramSuggestionEnabled = false;
private boolean mAutoCorrectOn;
// TODO move this state variable outside LatinIME
private boolean mCapsLock;
private boolean mPasswordText;
private boolean mVibrateOn;
private boolean mSoundOn;
private boolean mPopupOn;
private boolean mAutoCap;
private boolean mQuickFixes;
private boolean mHasUsedVoiceInput;
private boolean mHasUsedVoiceInputUnsupportedLocale;
private boolean mLocaleSupportedForVoiceInput;
private boolean mShowSuggestions;
private boolean mIsShowingHint;
private int mCorrectionMode;
private boolean mEnableVoice = true;
private boolean mVoiceOnPrimary;
private int mOrientation;
private List<CharSequence> mSuggestPuncList;
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
// Input type is such that we should not auto-correct
private boolean mInputTypeNoAutoCorrect;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private CharSequence mJustRevertedSeparator;
private int mDeleteCount;
private long mLastKeyTime;
// Modifier keys state
private ModifierKeyState mShiftKeyState = new ModifierKeyState();
private ModifierKeyState mSymbolKeyState = new ModifierKeyState();
private Tutorial mTutorial;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private final float FX_VOLUME = -1.0f;
private boolean mSilentMode;
/* package */ String mWordSeparators;
private String mSentenceSeparators;
private String mSuggestPuncs;
private VoiceInput mVoiceInput;
private VoiceResults mVoiceResults = new VoiceResults();
private boolean mConfigurationChanging;
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mRefreshKeyboardRequired;
// For each word, a list of potential replacements, usually from voice.
private Map<String, List<CharSequence>> mWordToSuggestions =
new HashMap<String, List<CharSequence>>();
private ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>();
private class VoiceResults {
List<String> candidates;
Map<String, List<CharSequence>> alternatives;
}
public abstract static class WordAlternatives {
protected CharSequence mChosenWord;
public WordAlternatives() {
// Nothing
}
public WordAlternatives(CharSequence chosenWord) {
mChosenWord = chosenWord;
}
@Override
public int hashCode() {
return mChosenWord.hashCode();
}
public abstract CharSequence getOriginalWord();
public CharSequence getChosenWord() {
return mChosenWord;
}
public abstract List<CharSequence> getAlternatives();
}
public class TypedWordAlternatives extends WordAlternatives {
private WordComposer word;
public TypedWordAlternatives() {
// Nothing
}
public TypedWordAlternatives(CharSequence chosenWord, WordComposer wordComposer) {
super(chosenWord);
word = wordComposer;
}
@Override
public CharSequence getOriginalWord() {
return word.getTypedWord();
}
@Override
public List<CharSequence> getAlternatives() {
return getTypedSuggestions(word);
}
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
setOldSuggestions();
break;
case MSG_START_TUTORIAL:
if (mTutorial == null) {
if (mKeyboardSwitcher.getInputView().isShown()) {
mTutorial = new Tutorial(
LatinIME.this, mKeyboardSwitcher.getInputView());
mTutorial.start();
} else {
// Try again soon if the view is not yet showing
sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100);
}
}
break;
case MSG_UPDATE_SHIFT_STATE:
updateShiftKeyState(getCurrentInputEditorInfo());
break;
case MSG_VOICE_RESULTS:
handleVoiceResults();
break;
}
}
};
@Override public void onCreate() {
LatinImeLogger.init(this);
super.onCreate();
//setStatusIcon(R.drawable.ime_qwerty);
mResources = getResources();
final Configuration conf = mResources.getConfiguration();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mLanguageSwitcher = new LanguageSwitcher(this);
mLanguageSwitcher.loadLocales(prefs);
mKeyboardSwitcher = new KeyboardSwitcher(this);
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
mSystemLocale = conf.locale.toString();
mLanguageSwitcher.setSystemLocale(conf.locale);
String inputLanguage = mLanguageSwitcher.getInputLanguage();
if (inputLanguage == null) {
inputLanguage = conf.locale.toString();
}
mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest(inputLanguage);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(inputLanguage, e);
}
}
mOrientation = conf.orientation;
initSuggestPuncList();
// register to receive ringer mode changes for silent mode
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
if (VOICE_INSTALLED) {
mVoiceInput = new VoiceInput(this, this);
mHints = new Hints(this, new Hints.Display() {
public void showHint(int viewResource) {
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(viewResource, null);
setCandidatesView(view);
setCandidatesViewShown(true);
mIsShowingHint = true;
}
});
}
prefs.registerOnSharedPreferenceChangeListener(this);
}
/**
* Loads a dictionary or multiple separated dictionary
* @return returns array of dictionary resource ids
*/
static int[] getDictionary(Resources res) {
String packageName = LatinIME.class.getPackage().getName();
XmlResourceParser xrp = res.getXml(R.xml.dictionary);
ArrayList<Integer> dictionaries = new ArrayList<Integer>();
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("part")) {
String dictFileName = xrp.getAttributeValue(null, "name");
dictionaries.add(res.getIdentifier(dictFileName, "raw", packageName));
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
int count = dictionaries.size();
int[] dict = new int[count];
for (int i = 0; i < count; i++) {
dict[i] = dictionaries.get(i);
}
return dict;
}
private void initSuggest(String locale) {
mInputLocale = locale;
Resources orig = getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = new Locale(locale);
orig.updateConfiguration(conf, orig.getDisplayMetrics());
if (mSuggest != null) {
mSuggest.close();
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
int[] dictionaries = getDictionary(orig);
mSuggest = new Suggest(this, dictionaries);
updateAutoTextEnabled(saveLocale);
if (mUserDictionary != null) mUserDictionary.close();
mUserDictionary = new UserDictionary(this, mInputLocale);
if (mContactsDictionary == null) {
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
}
if (mAutoDictionary != null) {
mAutoDictionary.close();
}
mAutoDictionary = new AutoDictionary(this, this, mInputLocale, Suggest.DIC_AUTO);
if (mUserBigramDictionary != null) {
mUserBigramDictionary.close();
}
mUserBigramDictionary = new UserBigramDictionary(this, this, mInputLocale,
Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
mSuggest.setUserDictionary(mUserDictionary);
mSuggest.setContactsDictionary(mContactsDictionary);
mSuggest.setAutoDictionary(mAutoDictionary);
updateCorrectionMode();
mWordSeparators = mResources.getString(R.string.word_separators);
mSentenceSeparators = mResources.getString(R.string.sentence_separators);
conf.locale = saveLocale;
orig.updateConfiguration(conf, orig.getDisplayMetrics());
}
@Override
public void onDestroy() {
if (mUserDictionary != null) {
mUserDictionary.close();
}
if (mContactsDictionary != null) {
mContactsDictionary.close();
}
unregisterReceiver(mReceiver);
if (VOICE_INSTALLED && mVoiceInput != null) {
mVoiceInput.destroy();
}
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
// If the system locale changes and is different from the saved
// locale (mSystemLocale), then reload the input locale list from the
// latin ime settings (shared prefs) and reset the input locale
// to the first one.
final String systemLocale = conf.locale.toString();
if (!TextUtils.equals(systemLocale, mSystemLocale)) {
mSystemLocale = systemLocale;
if (mLanguageSwitcher != null) {
mLanguageSwitcher.loadLocales(
PreferenceManager.getDefaultSharedPreferences(this));
mLanguageSwitcher.setSystemLocale(conf.locale);
toggleLanguage(true, true);
} else {
reloadKeyboards();
}
}
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
reloadKeyboards();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
if (mRecognizing) {
switchToRecognitionStatusView();
}
mConfigurationChanging = false;
}
@Override
public View onCreateInputView() {
mKeyboardSwitcher.recreateInputView();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(
KeyboardSwitcher.MODE_TEXT, 0,
shouldShowVoiceButton(makeFieldContext(), getCurrentInputEditorInfo()));
return mKeyboardSwitcher.getInputView();
}
@Override
public View onCreateCandidatesView() {
mKeyboardSwitcher.makeKeyboards(true);
mCandidateViewContainer = (LinearLayout) getLayoutInflater().inflate(
R.layout.candidates, null);
mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return mCandidateViewContainer;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// In landscape mode, this method gets called without the input view being created.
if (inputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEnteredText = null;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
// fall through
// NOTE: For now, we use the phone keyboard for NUMBER and DATETIME until we get
// a dedicated number entry keypad.
// TODO: Use a dedicated number entry keypad here when we get one.
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = isFullscreenMode();
}
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
}
inputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
updateShiftKeyState(attribute);
setCandidatesViewShownInternal(isCandidateStripVisible() || mCompletionOn,
false /* needsInputViewShown */ );
updateSuggestions();
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
inputView.setPreviewEnabled(mPopupOn);
inputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
// If we just entered a text field, maybe it has some old text that requires correction
checkReCorrectionOnStart();
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
private void checkReCorrectionOnStart() {
if (mReCorrectionEnabled && isPredictionOn()) {
// First get the cursor position. This is required by setOldSuggestions(), so that
// it can pass the correct range to setComposingRegion(). At this point, we don't
// have valid values for mLastSelectionStart/Stop because onUpdateSelection() has
// not been called yet.
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ExtractedTextRequest etr = new ExtractedTextRequest();
etr.token = 0; // anything is fine here
ExtractedText et = ic.getExtractedText(etr, 0);
if (et == null) return;
mLastSelectionStart = et.startOffset + et.selectionStart;
mLastSelectionEnd = et.startOffset + et.selectionEnd;
// Then look for possible corrections in a delayed fashion
if (!TextUtils.isEmpty(et.text)) postUpdateOldSuggestions();
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (VOICE_INSTALLED && !mConfigurationChanging) {
if (mAfterVoiceInput) {
mVoiceInput.flushAllTextModificationCounters();
mVoiceInput.logInputEnded();
}
mVoiceInput.flushLogs();
mVoiceInput.cancel();
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().closing();
}
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
InputConnection ic = getCurrentInputConnection();
if (!mImmediatelyAfterVoiceInput && mAfterVoiceInput && ic != null) {
if (mHints.showPunctuationHintIfNecessary(ic)) {
mVoiceInput.logPunctuationHintDisplayed();
}
}
mImmediatelyAfterVoiceInput = false;
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
if (mAfterVoiceInput) {
mVoiceInput.setCursorPos(newSelEnd);
mVoiceInput.setSelectionSpan(newSelEnd - newSelStart);
}
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if ((((mComposing.length() > 0 && mPredicting) || mVoiceInputHighlighted)
&& (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd)
&& mLastSelectionStart != newSelStart)) {
mComposing.setLength(0);
mPredicting = false;
postUpdateSuggestions();
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceInputHighlighted = false;
} else if (!mPredicting && !mJustAccepted) {
switch (TextEntryState.getState()) {
case ACCEPTED_DEFAULT:
TextEntryState.reset();
// fall through
case SPACE_AFTER_PICKED:
mJustAddedAutoSpace = false; // The user moved the cursor.
break;
}
}
mJustAccepted = false;
postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
if (mReCorrectionEnabled) {
// Don't look for corrections if the keyboard is not visible
if (mKeyboardSwitcher != null && mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getInputView().isShown()) {
// Check if we should go in or out of correction mode.
if (isPredictionOn()
&& mJustRevertedSeparator == null
&& (candidatesStart == candidatesEnd || newSelStart != oldSelStart
|| TextEntryState.isCorrecting())
&& (newSelStart < newSelEnd - 1 || (!mPredicting))
&& !mVoiceInputHighlighted) {
if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) {
postUpdateOldSuggestions();
} else {
abortCorrection(false);
}
}
}
}
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the candidates view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
if (!mConfigurationChanging) {
if (mAfterVoiceInput) mVoiceInput.logInputEnded();
if (mVoiceWarningDialog != null && mVoiceWarningDialog.isShowing()) {
mVoiceInput.logKeyboardWarningDialogDismissed();
mVoiceWarningDialog.dismiss();
mVoiceWarningDialog = null;
}
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
}
mWordToSuggestions.clear();
mWordHistory.clear();
super.hideWindow();
TextEntryState.endSession();
}
@Override
public void onDisplayCompletions(CompletionInfo[] completions) {
if (DEBUG) {
Log.i("foo", "Received completions:");
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
Log.i("foo", " #" + i + ": " + completions[i]);
}
}
if (mCompletionOn) {
mCompletions = completions;
if (completions == null) {
clearSuggestions();
return;
}
List<CharSequence> stringList = new ArrayList<CharSequence>();
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText());
}
// When in fullscreen mode, show completions generated by the application
setSuggestions(stringList, true, true, true);
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
// TODO: Remove this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
super.setCandidatesViewShown(shown && mKeyboardSwitcher.getInputView() != null
&& (needsInputViewShown ? mKeyboardSwitcher.getInputView().isShown() : true));
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
if (!isFullscreenMode()) {
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
@Override
public boolean onEvaluateFullscreenMode() {
DisplayMetrics dm = getResources().getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen mode
float dimen = getResources().getDimension(R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
} else if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// Enable shift key and DPAD to do selections
if (inputView != null && inputView.isShown()
&& inputView.isShifted()) {
event = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.sendKeyEvent(event);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void revertVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.commitText("", 1);
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void commitVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.finishComposingText();
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void reloadKeyboards() {
if (mKeyboardSwitcher == null) {
mKeyboardSwitcher = new KeyboardSwitcher(this);
}
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
if (mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getKeyboardMode() != KeyboardSwitcher.MODE_NONE) {
mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton, mVoiceOnPrimary);
}
mKeyboardSwitcher.makeKeyboards(true);
}
private void commitTyped(InputConnection inputConnection) {
if (mPredicting) {
mPredicting = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
addToDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
private void postUpdateShiftKeyState() {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
// TODO: Should remove this 300ms delay?
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SHIFT_STATE), 300);
}
public void updateShiftKeyState(EditorInfo attr) {
InputConnection ic = getCurrentInputConnection();
if (ic != null && attr != null && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShifted(mShiftKeyState.isMomentary() || mCapsLock
|| getCursorCapsMode(ic, attr) != 0);
}
}
private int getCursorCapsMode(InputConnection ic, EditorInfo attr) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
caps = ic.getCursorCapsMode(attr.inputType);
}
return caps;
}
private void swapPunctuationAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == KEYCODE_SPACE && isSentenceSeparator(lastTwo.charAt(1))) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void reswapPeriodAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& lastThree.charAt(0) == KEYCODE_PERIOD
&& lastThree.charAt(1) == KEYCODE_SPACE
&& lastThree.charAt(2) == KEYCODE_PERIOD) {
ic.beginBatchEdit();
ic.deleteSurroundingText(3, 0);
ic.commitText(" ..", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
}
}
private void doubleSpace() {
//if (!mAutoPunctuate) return;
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_PERIOD
&& text.charAt(0) == KEYCODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word to the
// user dictionary
postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void showInputMethodPicker() {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
}
private void onOptionKeyPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showOptionsMenu();
} else {
launchSettings();
}
}
}
private void onOptionKeyLongPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showInputMethodPicker();
} else {
launchSettings();
}
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
// Implementation of KeyboardViewListener
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.KEYCODE_DELETE ||
when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.KEYCODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
handleShift();
break;
case Keyboard.KEYCODE_MODE_CHANGE:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
changeKeyboardMode();
break;
case Keyboard.KEYCODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case LatinKeyboardView.KEYCODE_OPTIONS:
onOptionKeyPressed();
break;
case LatinKeyboardView.KEYCODE_OPTIONS_LONGPRESS:
onOptionKeyLongPressed();
break;
case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE:
toggleLanguage(false, true);
break;
case LatinKeyboardView.KEYCODE_PREV_LANGUAGE:
toggleLanguage(false, false);
break;
case LatinKeyboardView.KEYCODE_VOICE:
if (VOICE_INSTALLED) {
startListening(false /* was a button press, was not a swipe */);
}
break;
case 9 /*Tab*/:
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
break;
default:
if (primaryCode != KEYCODE_ENTER) {
mJustAddedAutoSpace = false;
}
RingCharBuffer.getInstance().push((char)primaryCode, x, y);
LatinImeLogger.logOnInputChar();
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode);
} else {
handleCharacter(primaryCode, keyCodes);
}
// Cancel the just reverted state
mJustRevertedSeparator = null;
}
if (mKeyboardSwitcher.onKey(primaryCode)) {
changeKeyboardMode();
}
// Reset after any single keystroke
mEnteredText = null;
}
public void onText(CharSequence text) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
abortCorrection(false);
ic.beginBatchEdit();
if (mPredicting) {
commitTyped(ic);
}
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustRevertedSeparator = null;
mJustAddedAutoSpace = false;
mEnteredText = text;
}
public void onCancel() {
// User released a finger outside any key
}
private void handleBackspace() {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
mVoiceInput.incrementTextModificationDeleteCount(
mVoiceResults.candidates.get(0).toString().length());
revertVoiceInput();
return;
}
boolean deleteChar = false;
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mAfterVoiceInput) {
// Don't log delete if the user is pressing delete at
// the beginning of the text box (hence not deleting anything)
if (mVoiceInput.getCursorPos() > 0) {
// If anything was selected before the delete was pressed, increment the
// delete count by the length of the selection
int deleteLen = mVoiceInput.getSelectionSpan() > 0 ?
mVoiceInput.getSelectionSpan() : 1;
mVoiceInput.incrementTextModificationDeleteCount(deleteLen);
}
}
if (mPredicting) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mPredicting = false;
}
postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
} else if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Tap again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
mJustRevertedSeparator = null;
ic.endBatchEdit();
}
private void resetShift() {
handleShiftInternal(true);
}
private void handleShift() {
handleShiftInternal(false);
}
private void handleShiftInternal(boolean forceNormal) {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
KeyboardSwitcher switcher = mKeyboardSwitcher;
LatinKeyboardView inputView = switcher.getInputView();
if (switcher.isAlphabetMode()) {
if (mCapsLock || forceNormal) {
mCapsLock = false;
switcher.setShifted(false);
} else if (inputView != null) {
if (inputView.isShifted()) {
mCapsLock = true;
switcher.setShiftLocked(true);
} else {
switcher.setShifted(true);
}
}
} else {
switcher.toggleShift();
}
}
private void abortCorrection(boolean force) {
if (force || TextEntryState.isCorrecting()) {
getCurrentInputConnection().finishComposingText();
clearSuggestions();
}
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput) {
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertCount(1);
}
if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) {
abortCorrection(false);
}
if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) {
if (!mPredicting) {
mPredicting = true;
mComposing.setLength(0);
saveWordInHistory(mBestWord);
mWord.reset();
}
}
if (mKeyboardSwitcher.getInputView().isShifted()) {
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
primaryCode = keyCodes[0];
if (mKeyboardSwitcher.isAlphabetMode() && Character.isLowerCase(primaryCode)) {
int upperCaseCode = Character.toUpperCase(primaryCode);
if (upperCaseCode != primaryCode) {
primaryCode = upperCaseCode;
} else {
// Some keys, such as [eszett], have upper case as multi-characters.
String upperCase = new String(new int[] {primaryCode}, 0, 1).toUpperCase();
onText(upperCase);
return;
}
}
}
if (mPredicting) {
if (mKeyboardSwitcher.getInputView().isShifted()
&& mKeyboardSwitcher.isAlphabetMode()
&& mComposing.length() == 0) {
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) primaryCode);
mWord.add(primaryCode, keyCodes);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(
getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
}
ic.setComposingText(mComposing, 1);
}
postUpdateSuggestions();
} else {
sendKeyChar((char)primaryCode);
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (LatinIME.PERF_DEBUG) measureCps();
TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}
private void handleSeparator(int primaryCode) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput){
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertPunctuationCount(1);
}
// Should dismiss the "Tap again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
abortCorrection(false);
}
if (mPredicting) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
if (mAutoCorrectOn && primaryCode != '\'' &&
(mJustRevertedSeparator == null
|| mJustRevertedSeparator.length() == 0
|| mJustRevertedSeparator.charAt(0) != primaryCode)) {
pickedDefault = pickDefaultSuggestion();
// Picked the suggestion by the space key. We consider this
// as "added an auto space".
if (primaryCode == KEYCODE_SPACE) {
mJustAddedAutoSpace = true;
}
} else {
commitTyped(ic);
}
}
if (mJustAddedAutoSpace && primaryCode == KEYCODE_ENTER) {
removeTrailingSpace();
mJustAddedAutoSpace = false;
}
sendKeyChar((char)primaryCode);
// Handle the case of ". ." -> " .." with auto-space if necessary
// before changing the TextEntryState.
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode == KEYCODE_PERIOD) {
reswapPeriodAndSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true);
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode != KEYCODE_ENTER) {
swapPunctuationAndSpace();
} else if (isPredictionOn() && primaryCode == KEYCODE_SPACE) {
doubleSpace();
}
if (pickedDefault) {
TextEntryState.backToAcceptedDefault(mWord.getTypedWord());
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
requestHideSelf(0);
if (mKeyboardSwitcher != null) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.closing();
}
}
TextEntryState.endSession();
}
private void saveWordInHistory(CharSequence result) {
if (mWord.size() <= 1) {
mWord.reset();
return;
}
// Skip if result is null. It happens in some edge case.
if (TextUtils.isEmpty(result)) {
return;
}
// Make a copy of the CharSequence, since it is/could be a mutable CharSequence
final String resultCopy = result.toString();
TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy,
new WordComposer(mWord));
mWordHistory.add(entry);
}
private void postUpdateSuggestions() {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100);
}
private void postUpdateOldSuggestions() {
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), 300);
}
private boolean isPredictionOn() {
return mPredictionOn;
}
private boolean isCandidateStripVisible() {
return isPredictionOn() && mShowSuggestions;
}
public void onCancelVoice() {
if (mRecognizing) {
switchToKeyboardView();
}
}
private void switchToKeyboardView() {
mHandler.post(new Runnable() {
public void run() {
mRecognizing = false;
if (mKeyboardSwitcher.getInputView() != null) {
setInputView(mKeyboardSwitcher.getInputView());
}
setCandidatesViewShown(true);
updateInputViewShown();
postUpdateSuggestions();
}});
}
private void switchToRecognitionStatusView() {
final boolean configChanged = mConfigurationChanging;
mHandler.post(new Runnable() {
public void run() {
setCandidatesViewShown(false);
mRecognizing = true;
View v = mVoiceInput.getView();
ViewParent p = v.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup)v.getParent()).removeView(v);
}
setInputView(v);
updateInputViewShown();
if (configChanged) {
mVoiceInput.onConfigurationChanged();
}
}});
}
private void startListening(boolean swipe) {
if (!mHasUsedVoiceInput ||
(!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale)) {
// Calls reallyStartListening if user clicks OK, does nothing if user clicks Cancel.
showVoiceWarningDialog(swipe);
} else {
reallyStartListening(swipe);
}
}
private void reallyStartListening(boolean swipe) {
if (!mHasUsedVoiceInput) {
// The user has started a voice input, so remember that in the
// future (so we don't show the warning dialog after the first run).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInput = true;
}
if (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale) {
// The user has started a voice input from an unsupported locale, so remember that
// in the future (so we don't show the warning dialog the next time they do this).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInputUnsupportedLocale = true;
}
// Clear N-best suggestions
clearSuggestions();
FieldContext context = new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
mVoiceInput.startListening(context, swipe);
switchToRecognitionStatusView();
}
private void showVoiceWarningDialog(final boolean swipe) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_mic_dialog);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogOk();
reallyStartListening(swipe);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogCancel();
}
});
if (mLocaleSupportedForVoiceInput) {
String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
} else {
String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" +
getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
}
builder.setTitle(R.string.voice_warning_title);
mVoiceWarningDialog = builder.create();
Window window = mVoiceWarningDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mVoiceInput.logKeyboardWarningDialogShown();
mVoiceWarningDialog.show();
}
public void onVoiceResults(List<String> candidates,
Map<String, List<CharSequence>> alternatives) {
if (!mRecognizing) {
return;
}
mVoiceResults.candidates = candidates;
mVoiceResults.alternatives = alternatives;
mHandler.sendMessage(mHandler.obtainMessage(MSG_VOICE_RESULTS));
}
private void handleVoiceResults() {
mAfterVoiceInput = true;
mImmediatelyAfterVoiceInput = true;
InputConnection ic = getCurrentInputConnection();
if (!isFullscreenMode()) {
// Start listening for updates to the text from typing, etc.
if (ic != null) {
ExtractedTextRequest req = new ExtractedTextRequest();
ic.getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR);
}
}
vibrate();
switchToKeyboardView();
final List<CharSequence> nBest = new ArrayList<CharSequence>();
boolean capitalizeFirstWord = preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& mKeyboardSwitcher.getInputView().isShifted());
for (String c : mVoiceResults.candidates) {
if (capitalizeFirstWord) {
c = Character.toUpperCase(c.charAt(0)) + c.substring(1, c.length());
}
nBest.add(c);
}
if (nBest.size() == 0) {
return;
}
String bestResult = nBest.get(0).toString();
mVoiceInput.logVoiceInputDelivered(bestResult.length());
mHints.registerVoiceResult(bestResult);
if (ic != null) ic.beginBatchEdit(); // To avoid extra updates on committing older text
commitTyped(ic);
EditingUtil.appendText(ic, bestResult);
if (ic != null) ic.endBatchEdit();
mVoiceInputHighlighted = true;
mWordToSuggestions.putAll(mVoiceResults.alternatives);
}
private void clearSuggestions() {
setSuggestions(null, false, false, false);
}
private void setSuggestions(
List<CharSequence> suggestions,
boolean completions,
boolean typedWordValid,
boolean haveMinimalSuggestion) {
if (mIsShowingHint) {
setCandidatesView(mCandidateViewContainer);
mIsShowingHint = false;
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(
suggestions, completions, typedWordValid, haveMinimalSuggestion);
}
}
private void updateSuggestions() {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isPredictionOn()) && !mVoiceInputHighlighted) {
return;
}
if (!mPredicting) {
setNextSuggestions();
return;
}
showSuggestions(mWord);
}
private List<CharSequence> getTypedSuggestions(WordComposer word) {
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, null);
return stringList;
}
private void showCorrections(WordAlternatives alternatives) {
List<CharSequence> stringList = alternatives.getAlternatives();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(null);
showSuggestions(stringList, alternatives.getOriginalWord(), false, false);
}
private void showSuggestions(WordComposer word) {
// long startTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// TODO Maybe need better way of retrieving previous word
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mWordSeparators);
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, prevWord);
// long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime));
int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(
nextLettersFrequencies);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasMinimalCorrection();
//|| mCorrectionMode == mSuggest.CORRECTION_FULL;
CharSequence typedWord = word.getTypedWord();
// If we're in basic correct
boolean typedWordValid = mSuggest.isValidWord(typedWord) ||
(preferCapitalization()
&& mSuggest.isValidWord(typedWord.toString().toLowerCase()));
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isCorrecting();
showSuggestions(stringList, typedWord, typedWordValid, correctionAvailable);
}
private void showSuggestions(List<CharSequence> stringList, CharSequence typedWord,
boolean typedWordValid, boolean correctionAvailable) {
setSuggestions(stringList, false, typedWordValid, correctionAvailable);
if (stringList.size() > 0) {
if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
mBestWord = stringList.get(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
private boolean pickDefaultSuggestion() {
// Complete any pending candidate query first
if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
mJustAccepted = true;
pickSuggestion(mBestWord, false);
// Add the word to the auto dictionary if it's not a known word
addToDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
if (mAfterVoiceInput && mShowingVoiceSuggestions) mVoiceInput.logNBestChoose(index);
List<CharSequence> suggestions = mCandidateView.getSuggestions();
if (mAfterVoiceInput && !mShowingVoiceSuggestions) {
mVoiceInput.flushAllTextModificationCounters();
// send this intent AFTER logging any prior aggregated edits.
mVoiceInput.logTextModifiedByChooseSuggestion(suggestion.length());
}
final boolean correcting = TextEntryState.isCorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions);
onKey(suggestion.charAt(0), null, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
if (ic != null) {
ic.endBatchEdit();
}
return;
}
mJustAccepted = true;
pickSuggestion(suggestion, correcting);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mAutoSpace && !correcting) {
sendSpace();
mJustAddedAutoSpace = true;
}
final boolean showingAddToDictionaryHint = index == 0 && mCorrectionMode > 0
&& !mSuggest.isValidWord(suggestion)
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase());
if (!correcting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) KEYCODE_SPACE, true);
setNextSuggestions();
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Tap again to save hint", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
private void rememberReplacedWord(CharSequence suggestion) {
if (mShowingVoiceSuggestions) {
// Retain the replaced word in the alternatives array.
EditingUtil.Range range = new EditingUtil.Range();
String wordToBeReplaced = EditingUtil.getWordAtCursor(getCurrentInputConnection(),
mWordSeparators, range);
if (!mWordToSuggestions.containsKey(wordToBeReplaced)) {
wordToBeReplaced = wordToBeReplaced.toLowerCase();
}
if (mWordToSuggestions.containsKey(wordToBeReplaced)) {
List<CharSequence> suggestions = mWordToSuggestions.get(wordToBeReplaced);
if (suggestions.contains(suggestion)) {
suggestions.remove(suggestion);
}
suggestions.add(wordToBeReplaced);
mWordToSuggestions.remove(wordToBeReplaced);
mWordToSuggestions.put(suggestion.toString(), suggestions);
}
}
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
* @param suggestion the suggestion picked by the user to be committed to
* the text field
* @param correcting whether this is due to a correction of an existing
* word.
*/
private void pickSuggestion(CharSequence suggestion, boolean correcting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (mCapsLock) {
suggestion = suggestion.toString().toUpperCase();
} else if (preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& inputView.isShifted())) {
suggestion = suggestion.toString().toUpperCase().charAt(0)
+ suggestion.subSequence(1, suggestion.length()).toString();
}
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
rememberReplacedWord(suggestion);
ic.commitText(suggestion, 1);
}
saveWordInHistory(suggestion);
mPredicting = false;
mCommittedLength = suggestion.length();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// If we just corrected a word, then don't show punctuations
if (!correcting) {
setNextSuggestions();
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
/**
* Tries to apply any voice alternatives for the word if this was a spoken word and
* there are voice alternatives.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyVoiceAlternatives(EditingUtil.SelectedWord touching) {
// Search for result in spoken word alternatives
String selectedWord = touching.word.toString().trim();
if (!mWordToSuggestions.containsKey(selectedWord)) {
selectedWord = selectedWord.toLowerCase();
}
if (mWordToSuggestions.containsKey(selectedWord)) {
mShowingVoiceSuggestions = true;
List<CharSequence> suggestions = mWordToSuggestions.get(selectedWord);
// If the first letter of touching is capitalized, make all the suggestions
// start with a capital letter.
if (Character.isUpperCase(touching.word.charAt(0))) {
for (int i = 0; i < suggestions.size(); i++) {
String origSugg = (String) suggestions.get(i);
String capsSugg = origSugg.toUpperCase().charAt(0)
+ origSugg.subSequence(1, origSugg.length()).toString();
suggestions.set(i, capsSugg);
}
}
setSuggestions(suggestions, false, true, true);
setCandidatesViewShown(true);
return true;
}
return false;
}
/**
* Tries to apply any typed alternatives for the word if we have any cached alternatives,
* otherwise tries to find new corrections and completions for the word.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyTypedAlternatives(EditingUtil.SelectedWord touching) {
// If we didn't find a match, search for result in typed word history
WordComposer foundWord = null;
WordAlternatives alternatives = null;
for (WordAlternatives entry : mWordHistory) {
if (TextUtils.equals(entry.getChosenWord(), touching.word)) {
if (entry instanceof TypedWordAlternatives) {
foundWord = ((TypedWordAlternatives) entry).word;
}
alternatives = entry;
break;
}
}
// If we didn't find a match, at least suggest completions
if (foundWord == null
&& (mSuggest.isValidWord(touching.word)
|| mSuggest.isValidWord(touching.word.toString().toLowerCase()))) {
foundWord = new WordComposer();
for (int i = 0; i < touching.word.length(); i++) {
foundWord.add(touching.word.charAt(i), new int[] {
touching.word.charAt(i)
});
}
foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.word.charAt(0)));
}
// Found a match, show suggestions
if (foundWord != null || alternatives != null) {
if (alternatives == null) {
alternatives = new TypedWordAlternatives(touching.word, foundWord);
}
showCorrections(alternatives);
if (foundWord != null) {
mWord = new WordComposer(foundWord);
} else {
mWord.reset();
}
return true;
}
return false;
}
private void setOldSuggestions() {
mShowingVoiceSuggestions = false;
if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) {
return;
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
if (!mPredicting) {
// Extract the selected or touching text
EditingUtil.SelectedWord touching = EditingUtil.getWordAtCursorOrSelection(ic,
mLastSelectionStart, mLastSelectionEnd, mWordSeparators);
if (touching != null && touching.word.length() > 1) {
ic.beginBatchEdit();
if (!applyVoiceAlternatives(touching) && !applyTypedAlternatives(touching)) {
abortCorrection(true);
} else {
TextEntryState.selectedForCorrection();
EditingUtil.underlineWord(ic, touching);
}
ic.endBatchEdit();
} else {
abortCorrection(true);
setNextSuggestions();
}
} else {
abortCorrection(true);
}
}
private void setNextSuggestions() {
setSuggestions(mSuggestPuncList, false, false, false);
}
private void addToDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToBigramDictionary(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
* @param addToBigramDictionary true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta,
boolean addToBigramDictionary) {
if (suggestion == null || suggestion.length() < 1) return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
if (suggestion != null) {
if (!addToBigramDictionary && mAutoDictionary.isValidWord(suggestion)
|| (!mSuggest.isValidWord(suggestion.toString())
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase()))) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mSentenceSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
}
private boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !isWordSeparator(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !isWordSeparator(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mPredicting && length > 0) {
final InputConnection ic = getCurrentInputConnection();
mPredicting = true;
mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (toTheLeft != null && toTheLeft.length() > 0
&& isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
mJustRevertedSeparator = null;
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private boolean isSentenceSeparator(int code) {
return mSentenceSeparators.contains(String.valueOf((char)code));
}
private void sendSpace() {
sendKeyChar((char)KEYCODE_SPACE);
updateShiftKeyState(getCurrentInputEditorInfo());
//onKey(KEY_SPACE[0], KEY_SPACE);
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
private void toggleLanguage(boolean reset, boolean next) {
if (reset) {
mLanguageSwitcher.reset();
} else {
if (next) {
mLanguageSwitcher.next();
} else {
mLanguageSwitcher.prev();
}
}
int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode();
reloadKeyboards();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0,
mEnableVoiceButton && mEnableVoice);
initSuggest(mLanguageSwitcher.getInputLanguage());
mLanguageSwitcher.persist();
updateShiftKeyState(getCurrentInputEditorInfo());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PREF_SELECTED_LANGUAGES.equals(key)) {
mLanguageSwitcher.loadLocales(sharedPreferences);
mRefreshKeyboardRequired = true;
} else if (PREF_RECORRECTION_ENABLED.equals(key)) {
mReCorrectionEnabled = sharedPreferences.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
}
}
public void swipeRight() {
if (LatinKeyboardView.DEBUG_AUTO_PLAY) {
ClipboardManager cm = ((ClipboardManager)getSystemService(CLIPBOARD_SERVICE));
CharSequence text = cm.getText();
if (!TextUtils.isEmpty(text)) {
mKeyboardSwitcher.getInputView().startPlaying(text.toString());
}
}
}
public void swipeLeft() {
}
public void swipeDown() {
handleClose();
}
public void swipeUp() {
//launchSettings();
}
public void onPress(int primaryCode) {
vibrate();
playKeyClick(primaryCode);
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
mShiftKeyState.onPress();
handleShift();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
mSymbolKeyState.onPress();
changeKeyboardMode();
} else {
mShiftKeyState.onOtherKeyPressed();
mSymbolKeyState.onOtherKeyPressed();
}
}
public void onRelease(int primaryCode) {
// Reset any drag flags in the keyboard
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).keyReleased();
//vibrate();
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
if (mShiftKeyState.isMomentary())
resetShift();
mShiftKeyState.onRelease();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
if (mSymbolKeyState.isMomentary())
changeKeyboardMode();
mSymbolKeyState.onRelease();
}
}
private FieldContext makeFieldContext() {
return new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
}
private boolean fieldCanDoVoice(FieldContext fieldContext) {
return !mPasswordText
&& mVoiceInput != null
&& !mVoiceInput.isBlacklistedField(fieldContext);
}
private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) {
return ENABLE_VOICE_BUTTON && fieldCanDoVoice(fieldContext)
&& !(attribute != null && attribute.privateImeOptions != null
&& attribute.privateImeOptions.equals(IME_OPTION_NO_MICROPHONE))
&& SpeechRecognizer.isRecognitionAvailable(this);
}
// receive ringer mode changes to detect silent mode
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRingerMode();
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case KEYCODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case KEYCODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
private void vibrate() {
if (!mVibrateOn) {
return;
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
private void checkTutorial(String privateImeOptions) {
if (privateImeOptions == null) return;
if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) {
if (mTutorial == null) startTutorial();
} else if (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) {
if (mTutorial != null) {
if (mTutorial.close()) {
mTutorial = null;
}
}
}
}
private void startTutorial() {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500);
}
void tutorialDone() {
mTutorial = null;
}
void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
WordComposer getCurrentWord() {
return mWord;
}
boolean getPopupOn() {
return mPopupOn;
}
private void updateCorrectionMode() {
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled(Locale systemLocale) {
if (mSuggest == null) return;
boolean different =
!systemLocale.getLanguage().equalsIgnoreCase(mInputLocale.substring(0, 2));
mSuggest.setAutoTextEnabled(!different && mQuickFixes);
}
protected void launchSettings() {
launchSettings(LatinIMESettings.class);
}
public void launchDebugSettings() {
launchSettings(LatinIMEDebugSettings.class);
}
protected void launchSettings (Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings() {
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false);
mSoundOn = sp.getBoolean(PREF_SOUND_ON, false);
mPopupOn = sp.getBoolean(PREF_POPUP_ON,
mResources.getBoolean(R.bool.default_popup_preview));
mAutoCap = sp.getBoolean(PREF_AUTO_CAP, true);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mHasUsedVoiceInput = sp.getBoolean(PREF_HAS_USED_VOICE_INPUT, false);
mHasUsedVoiceInputUnsupportedLocale =
sp.getBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, false);
// Get the current list of supported locales and check the current locale against that
// list. We cache this value so as not to check it every time the user starts a voice
// input. Because this method is called by onStartInputView, this should mean that as
// long as the locale doesn't change while the user is keeping the IME open, the
// value should never be stale.
String supportedLocalesString = SettingsUtil.getSettingsString(
getContentResolver(),
SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
ArrayList<String> voiceInputSupportedLocales =
newArrayList(supportedLocalesString.split("\\s+"));
mLocaleSupportedForVoiceInput = voiceInputSupportedLocales.contains(mInputLocale);
mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, true);
if (VOICE_INSTALLED) {
final String voiceMode = sp.getString(PREF_VOICE_MODE,
getString(R.string.voice_mode_main));
boolean enableVoice = !voiceMode.equals(getString(R.string.voice_mode_off))
&& mEnableVoiceButton;
boolean voiceOnPrimary = voiceMode.equals(getString(R.string.voice_mode_main));
if (mKeyboardSwitcher != null &&
(enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) {
mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary);
}
mEnableVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
}
mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE,
mResources.getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions;
//mBigramSuggestionEnabled = sp.getBoolean(
// PREF_BIGRAM_SUGGESTIONS, true) & mShowSuggestions;
updateCorrectionMode();
updateAutoTextEnabled(mResources.getConfiguration().locale);
mLanguageSwitcher.loadLocales(sp);
}
private void initSuggestPuncList() {
mSuggestPuncList = new ArrayList<CharSequence>();
mSuggestPuncs = mResources.getString(R.string.suggested_punctuations);
if (mSuggestPuncs != null) {
for (int i = 0; i < mSuggestPuncs.length(); i++) {
mSuggestPuncList.add(mSuggestPuncs.subSequence(i, i + 1));
}
}
}
private boolean isSuggestedPunctuation(int code) {
return mSuggestPuncs.contains(String.valueOf((char)code));
}
private void showOptionsMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
CharSequence itemSettings = getString(R.string.english_ime_settings);
CharSequence itemInputMethod = getString(R.string.selectInputMethod);
builder.setItems(new CharSequence[] {
itemInputMethod, itemSettings},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case POS_SETTINGS:
launchSettings();
break;
case POS_METHOD:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
}
}
});
builder.setTitle(mResources.getString(R.string.english_ime_input_options));
mOptionsDialog = builder.create();
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
private void changeKeyboardMode() {
mKeyboardSwitcher.toggleSymbols();
if (mCapsLock && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShiftLocked(mCapsLock);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mCapsLock=" + mCapsLock);
p.println(" mComposing=" + mComposing.toString());
p.println(" mPredictionOn=" + mPredictionOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mPredicting=" + mPredicting);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mAutoSpace=" + mAutoSpace);
p.println(" mCompletionOn=" + mCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
p.println(" mPopupOn=" + mPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
public void onAutoCompletionStateChanged(boolean isAutoCompletion) {
mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion);
}
}
|
java/src/com/android/inputmethod/latin/LatinIME.java
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.LatinIMEUtil.RingCharBuffer;
import com.android.inputmethod.voice.FieldContext;
import com.android.inputmethod.voice.SettingsUtil;
import com.android.inputmethod.voice.VoiceInput;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.media.AudioManager;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.speech.SpeechRecognizer;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodService
implements LatinKeyboardBaseView.OnKeyboardActionListener,
VoiceInput.UiListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIME";
private static final boolean PERF_DEBUG = false;
static final boolean DEBUG = false;
static final boolean TRACE = false;
static final boolean VOICE_INSTALLED = true;
static final boolean ENABLE_VOICE_BUTTON = true;
private static final String PREF_VIBRATE_ON = "vibrate_on";
private static final String PREF_SOUND_ON = "sound_on";
private static final String PREF_POPUP_ON = "popup_on";
private static final String PREF_AUTO_CAP = "auto_cap";
private static final String PREF_QUICK_FIXES = "quick_fixes";
private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions";
private static final String PREF_AUTO_COMPLETE = "auto_complete";
//private static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion";
private static final String PREF_VOICE_MODE = "voice_mode";
// Whether or not the user has used voice input before (and thus, whether to show the
// first-run warning dialog or not).
private static final String PREF_HAS_USED_VOICE_INPUT = "has_used_voice_input";
// Whether or not the user has used voice input from an unsupported locale UI before.
// For example, the user has a Chinese UI but activates voice input.
private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE =
"has_used_voice_input_unsupported_locale";
// A list of locales which are supported by default for voice input, unless we get a
// different list from Gservices.
public static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
"en " +
"en_US " +
"en_GB " +
"en_AU " +
"en_CA " +
"en_IE " +
"en_IN " +
"en_NZ " +
"en_SG " +
"en_ZA ";
// The private IME option used to indicate that no microphone should be shown for a
// given text field. For instance this is specified by the search dialog when the
// dialog is already showing a voice search button.
private static final String IME_OPTION_NO_MICROPHONE = "nm";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_INPUT_LANGUAGE = "input_language";
private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled";
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_START_TUTORIAL = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 4;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
static final int KEYCODE_ENTER = '\n';
static final int KEYCODE_SPACE = ' ';
static final int KEYCODE_PERIOD = '.';
// Contextual menu positions
private static final int POS_METHOD = 0;
private static final int POS_SETTINGS = 1;
//private LatinKeyboardView mInputView;
private LinearLayout mCandidateViewContainer;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mCompletions;
private AlertDialog mOptionsDialog;
private AlertDialog mVoiceWarningDialog;
KeyboardSwitcher mKeyboardSwitcher;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
private Hints mHints;
Resources mResources;
private String mInputLocale;
private String mSystemLocale;
private LanguageSwitcher mLanguageSwitcher;
private StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private int mCommittedLength;
private boolean mPredicting;
private boolean mRecognizing;
private boolean mAfterVoiceInput;
private boolean mImmediatelyAfterVoiceInput;
private boolean mShowingVoiceSuggestions;
private boolean mVoiceInputHighlighted;
private boolean mEnableVoiceButton;
private CharSequence mBestWord;
private boolean mPredictionOn;
private boolean mCompletionOn;
private boolean mHasDictionary;
private boolean mAutoSpace;
private boolean mJustAddedAutoSpace;
private boolean mAutoCorrectEnabled;
private boolean mReCorrectionEnabled;
// Bigram Suggestion is disabled in this version.
private final boolean mBigramSuggestionEnabled = false;
private boolean mAutoCorrectOn;
// TODO move this state variable outside LatinIME
private boolean mCapsLock;
private boolean mPasswordText;
private boolean mVibrateOn;
private boolean mSoundOn;
private boolean mPopupOn;
private boolean mAutoCap;
private boolean mQuickFixes;
private boolean mHasUsedVoiceInput;
private boolean mHasUsedVoiceInputUnsupportedLocale;
private boolean mLocaleSupportedForVoiceInput;
private boolean mShowSuggestions;
private boolean mIsShowingHint;
private int mCorrectionMode;
private boolean mEnableVoice = true;
private boolean mVoiceOnPrimary;
private int mOrientation;
private List<CharSequence> mSuggestPuncList;
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
// Input type is such that we should not auto-correct
private boolean mInputTypeNoAutoCorrect;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private CharSequence mJustRevertedSeparator;
private int mDeleteCount;
private long mLastKeyTime;
// Modifier keys state
private ModifierKeyState mShiftKeyState = new ModifierKeyState();
private ModifierKeyState mSymbolKeyState = new ModifierKeyState();
private Tutorial mTutorial;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private final float FX_VOLUME = -1.0f;
private boolean mSilentMode;
/* package */ String mWordSeparators;
private String mSentenceSeparators;
private String mSuggestPuncs;
private VoiceInput mVoiceInput;
private VoiceResults mVoiceResults = new VoiceResults();
private boolean mConfigurationChanging;
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mRefreshKeyboardRequired;
// For each word, a list of potential replacements, usually from voice.
private Map<String, List<CharSequence>> mWordToSuggestions =
new HashMap<String, List<CharSequence>>();
private ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>();
private class VoiceResults {
List<String> candidates;
Map<String, List<CharSequence>> alternatives;
}
public abstract static class WordAlternatives {
protected CharSequence mChosenWord;
public WordAlternatives() {
// Nothing
}
public WordAlternatives(CharSequence chosenWord) {
mChosenWord = chosenWord;
}
@Override
public int hashCode() {
return mChosenWord.hashCode();
}
public abstract CharSequence getOriginalWord();
public CharSequence getChosenWord() {
return mChosenWord;
}
public abstract List<CharSequence> getAlternatives();
}
public class TypedWordAlternatives extends WordAlternatives {
private WordComposer word;
public TypedWordAlternatives() {
// Nothing
}
public TypedWordAlternatives(CharSequence chosenWord, WordComposer wordComposer) {
super(chosenWord);
word = wordComposer;
}
@Override
public CharSequence getOriginalWord() {
return word.getTypedWord();
}
@Override
public List<CharSequence> getAlternatives() {
return getTypedSuggestions(word);
}
}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
setOldSuggestions();
break;
case MSG_START_TUTORIAL:
if (mTutorial == null) {
if (mKeyboardSwitcher.getInputView().isShown()) {
mTutorial = new Tutorial(
LatinIME.this, mKeyboardSwitcher.getInputView());
mTutorial.start();
} else {
// Try again soon if the view is not yet showing
sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100);
}
}
break;
case MSG_UPDATE_SHIFT_STATE:
updateShiftKeyState(getCurrentInputEditorInfo());
break;
case MSG_VOICE_RESULTS:
handleVoiceResults();
break;
}
}
};
@Override public void onCreate() {
LatinImeLogger.init(this);
super.onCreate();
//setStatusIcon(R.drawable.ime_qwerty);
mResources = getResources();
final Configuration conf = mResources.getConfiguration();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mLanguageSwitcher = new LanguageSwitcher(this);
mLanguageSwitcher.loadLocales(prefs);
mKeyboardSwitcher = new KeyboardSwitcher(this);
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
mSystemLocale = conf.locale.toString();
mLanguageSwitcher.setSystemLocale(conf.locale);
String inputLanguage = mLanguageSwitcher.getInputLanguage();
if (inputLanguage == null) {
inputLanguage = conf.locale.toString();
}
mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest(inputLanguage);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(inputLanguage, e);
}
}
mOrientation = conf.orientation;
initSuggestPuncList();
// register to receive ringer mode changes for silent mode
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
if (VOICE_INSTALLED) {
mVoiceInput = new VoiceInput(this, this);
mHints = new Hints(this, new Hints.Display() {
public void showHint(int viewResource) {
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(viewResource, null);
setCandidatesView(view);
setCandidatesViewShown(true);
mIsShowingHint = true;
}
});
}
prefs.registerOnSharedPreferenceChangeListener(this);
}
/**
* Loads a dictionary or multiple separated dictionary
* @return returns array of dictionary resource ids
*/
static int[] getDictionary(Resources res) {
String packageName = LatinIME.class.getPackage().getName();
XmlResourceParser xrp = res.getXml(R.xml.dictionary);
ArrayList<Integer> dictionaries = new ArrayList<Integer>();
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("part")) {
String dictFileName = xrp.getAttributeValue(null, "name");
dictionaries.add(res.getIdentifier(dictFileName, "raw", packageName));
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
int count = dictionaries.size();
int[] dict = new int[count];
for (int i = 0; i < count; i++) {
dict[i] = dictionaries.get(i);
}
return dict;
}
private void initSuggest(String locale) {
mInputLocale = locale;
Resources orig = getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = new Locale(locale);
orig.updateConfiguration(conf, orig.getDisplayMetrics());
if (mSuggest != null) {
mSuggest.close();
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
int[] dictionaries = getDictionary(orig);
mSuggest = new Suggest(this, dictionaries);
updateAutoTextEnabled(saveLocale);
if (mUserDictionary != null) mUserDictionary.close();
mUserDictionary = new UserDictionary(this, mInputLocale);
if (mContactsDictionary == null) {
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
}
if (mAutoDictionary != null) {
mAutoDictionary.close();
}
mAutoDictionary = new AutoDictionary(this, this, mInputLocale, Suggest.DIC_AUTO);
if (mUserBigramDictionary != null) {
mUserBigramDictionary.close();
}
mUserBigramDictionary = new UserBigramDictionary(this, this, mInputLocale,
Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
mSuggest.setUserDictionary(mUserDictionary);
mSuggest.setContactsDictionary(mContactsDictionary);
mSuggest.setAutoDictionary(mAutoDictionary);
updateCorrectionMode();
mWordSeparators = mResources.getString(R.string.word_separators);
mSentenceSeparators = mResources.getString(R.string.sentence_separators);
conf.locale = saveLocale;
orig.updateConfiguration(conf, orig.getDisplayMetrics());
}
@Override
public void onDestroy() {
if (mUserDictionary != null) {
mUserDictionary.close();
}
if (mContactsDictionary != null) {
mContactsDictionary.close();
}
unregisterReceiver(mReceiver);
if (VOICE_INSTALLED && mVoiceInput != null) {
mVoiceInput.destroy();
}
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
// If the system locale changes and is different from the saved
// locale (mSystemLocale), then reload the input locale list from the
// latin ime settings (shared prefs) and reset the input locale
// to the first one.
final String systemLocale = conf.locale.toString();
if (!TextUtils.equals(systemLocale, mSystemLocale)) {
mSystemLocale = systemLocale;
if (mLanguageSwitcher != null) {
mLanguageSwitcher.loadLocales(
PreferenceManager.getDefaultSharedPreferences(this));
mLanguageSwitcher.setSystemLocale(conf.locale);
toggleLanguage(true, true);
} else {
reloadKeyboards();
}
}
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
reloadKeyboards();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
if (mRecognizing) {
switchToRecognitionStatusView();
}
mConfigurationChanging = false;
}
@Override
public View onCreateInputView() {
mKeyboardSwitcher.recreateInputView();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(
KeyboardSwitcher.MODE_TEXT, 0,
shouldShowVoiceButton(makeFieldContext(), getCurrentInputEditorInfo()));
return mKeyboardSwitcher.getInputView();
}
@Override
public View onCreateCandidatesView() {
mKeyboardSwitcher.makeKeyboards(true);
mCandidateViewContainer = (LinearLayout) getLayoutInflater().inflate(
R.layout.candidates, null);
mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return mCandidateViewContainer;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// In landscape mode, this method gets called without the input view being created.
if (inputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEnteredText = null;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
// fall through
// NOTE: For now, we use the phone keyboard for NUMBER and DATETIME until we get
// a dedicated number entry keypad.
// TODO: Use a dedicated number entry keypad here when we get one.
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = isFullscreenMode();
}
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
}
inputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
updateShiftKeyState(attribute);
setCandidatesViewShownInternal(isCandidateStripVisible() || mCompletionOn,
false /* needsInputViewShown */ );
updateSuggestions();
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
inputView.setPreviewEnabled(mPopupOn);
inputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
// If we just entered a text field, maybe it has some old text that requires correction
checkReCorrectionOnStart();
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
private void checkReCorrectionOnStart() {
if (mReCorrectionEnabled && isPredictionOn()) {
// First get the cursor position. This is required by setOldSuggestions(), so that
// it can pass the correct range to setComposingRegion(). At this point, we don't
// have valid values for mLastSelectionStart/Stop because onUpdateSelection() has
// not been called yet.
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ExtractedTextRequest etr = new ExtractedTextRequest();
etr.token = 0; // anything is fine here
ExtractedText et = ic.getExtractedText(etr, 0);
if (et == null) return;
mLastSelectionStart = et.startOffset + et.selectionStart;
mLastSelectionEnd = et.startOffset + et.selectionEnd;
// Then look for possible corrections in a delayed fashion
if (!TextUtils.isEmpty(et.text)) postUpdateOldSuggestions();
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (VOICE_INSTALLED && !mConfigurationChanging) {
if (mAfterVoiceInput) {
mVoiceInput.flushAllTextModificationCounters();
mVoiceInput.logInputEnded();
}
mVoiceInput.flushLogs();
mVoiceInput.cancel();
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().closing();
}
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
InputConnection ic = getCurrentInputConnection();
if (!mImmediatelyAfterVoiceInput && mAfterVoiceInput && ic != null) {
if (mHints.showPunctuationHintIfNecessary(ic)) {
mVoiceInput.logPunctuationHintDisplayed();
}
}
mImmediatelyAfterVoiceInput = false;
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
if (mAfterVoiceInput) {
mVoiceInput.setCursorPos(newSelEnd);
mVoiceInput.setSelectionSpan(newSelEnd - newSelStart);
}
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if ((((mComposing.length() > 0 && mPredicting) || mVoiceInputHighlighted)
&& (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd)
&& mLastSelectionStart != newSelStart)) {
mComposing.setLength(0);
mPredicting = false;
postUpdateSuggestions();
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceInputHighlighted = false;
} else if (!mPredicting && !mJustAccepted) {
switch (TextEntryState.getState()) {
case ACCEPTED_DEFAULT:
TextEntryState.reset();
// fall through
case SPACE_AFTER_PICKED:
mJustAddedAutoSpace = false; // The user moved the cursor.
break;
}
}
mJustAccepted = false;
postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
if (mReCorrectionEnabled) {
// Don't look for corrections if the keyboard is not visible
if (mKeyboardSwitcher != null && mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getInputView().isShown()) {
// Check if we should go in or out of correction mode.
if (isPredictionOn()
&& mJustRevertedSeparator == null
&& (candidatesStart == candidatesEnd || newSelStart != oldSelStart
|| TextEntryState.isCorrecting())
&& (newSelStart < newSelEnd - 1 || (!mPredicting))
&& !mVoiceInputHighlighted) {
if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) {
postUpdateOldSuggestions();
} else {
abortCorrection(false);
}
}
}
}
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the candidates view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
if (!mConfigurationChanging) {
if (mAfterVoiceInput) mVoiceInput.logInputEnded();
if (mVoiceWarningDialog != null && mVoiceWarningDialog.isShowing()) {
mVoiceInput.logKeyboardWarningDialogDismissed();
mVoiceWarningDialog.dismiss();
mVoiceWarningDialog = null;
}
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
}
mWordToSuggestions.clear();
mWordHistory.clear();
super.hideWindow();
TextEntryState.endSession();
}
@Override
public void onDisplayCompletions(CompletionInfo[] completions) {
if (DEBUG) {
Log.i("foo", "Received completions:");
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
Log.i("foo", " #" + i + ": " + completions[i]);
}
}
if (mCompletionOn) {
mCompletions = completions;
if (completions == null) {
clearSuggestions();
return;
}
List<CharSequence> stringList = new ArrayList<CharSequence>();
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText());
}
// When in fullscreen mode, show completions generated by the application
setSuggestions(stringList, true, true, true);
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
// TODO: Remove this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
super.setCandidatesViewShown(shown && mKeyboardSwitcher.getInputView() != null
&& (needsInputViewShown ? mKeyboardSwitcher.getInputView().isShown() : true));
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
if (!isFullscreenMode()) {
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
@Override
public boolean onEvaluateFullscreenMode() {
DisplayMetrics dm = getResources().getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen mode
float dimen = getResources().getDimension(R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
} else if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// Enable shift key and DPAD to do selections
if (inputView != null && inputView.isShown()
&& inputView.isShifted()) {
event = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.sendKeyEvent(event);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void revertVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.commitText("", 1);
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void commitVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.finishComposingText();
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void reloadKeyboards() {
if (mKeyboardSwitcher == null) {
mKeyboardSwitcher = new KeyboardSwitcher(this);
}
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
if (mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getKeyboardMode() != KeyboardSwitcher.MODE_NONE) {
mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton, mVoiceOnPrimary);
}
mKeyboardSwitcher.makeKeyboards(true);
}
private void commitTyped(InputConnection inputConnection) {
if (mPredicting) {
mPredicting = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
addToDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
private void postUpdateShiftKeyState() {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
// TODO: Should remove this 300ms delay?
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SHIFT_STATE), 300);
}
public void updateShiftKeyState(EditorInfo attr) {
InputConnection ic = getCurrentInputConnection();
if (ic != null && attr != null && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShifted(mShiftKeyState.isMomentary() || mCapsLock
|| getCursorCapsMode(ic, attr) != 0);
}
}
private int getCursorCapsMode(InputConnection ic, EditorInfo attr) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
caps = ic.getCursorCapsMode(attr.inputType);
}
return caps;
}
private void swapPunctuationAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == KEYCODE_SPACE && isSentenceSeparator(lastTwo.charAt(1))) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void reswapPeriodAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& lastThree.charAt(0) == KEYCODE_PERIOD
&& lastThree.charAt(1) == KEYCODE_SPACE
&& lastThree.charAt(2) == KEYCODE_PERIOD) {
ic.beginBatchEdit();
ic.deleteSurroundingText(3, 0);
ic.commitText(" ..", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
}
}
private void doubleSpace() {
//if (!mAutoPunctuate) return;
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_PERIOD
&& text.charAt(0) == KEYCODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word to the
// user dictionary
postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void showInputMethodPicker() {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
}
private void onOptionKeyPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showOptionsMenu();
} else {
launchSettings();
}
}
}
private void onOptionKeyLongPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showInputMethodPicker();
} else {
launchSettings();
}
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
// Implementation of KeyboardViewListener
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.KEYCODE_DELETE ||
when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.KEYCODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
handleShift();
break;
case Keyboard.KEYCODE_MODE_CHANGE:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
changeKeyboardMode();
break;
case Keyboard.KEYCODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case LatinKeyboardView.KEYCODE_OPTIONS:
onOptionKeyPressed();
break;
case LatinKeyboardView.KEYCODE_OPTIONS_LONGPRESS:
onOptionKeyLongPressed();
break;
case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE:
toggleLanguage(false, true);
break;
case LatinKeyboardView.KEYCODE_PREV_LANGUAGE:
toggleLanguage(false, false);
break;
case LatinKeyboardView.KEYCODE_VOICE:
if (VOICE_INSTALLED) {
startListening(false /* was a button press, was not a swipe */);
}
break;
case 9 /*Tab*/:
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
break;
default:
if (primaryCode != KEYCODE_ENTER) {
mJustAddedAutoSpace = false;
}
RingCharBuffer.getInstance().push((char)primaryCode, x, y);
LatinImeLogger.logOnInputChar();
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode);
} else {
handleCharacter(primaryCode, keyCodes);
}
// Cancel the just reverted state
mJustRevertedSeparator = null;
}
if (mKeyboardSwitcher.onKey(primaryCode)) {
changeKeyboardMode();
}
// Reset after any single keystroke
mEnteredText = null;
}
public void onText(CharSequence text) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
abortCorrection(false);
ic.beginBatchEdit();
if (mPredicting) {
commitTyped(ic);
}
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustRevertedSeparator = null;
mJustAddedAutoSpace = false;
mEnteredText = text;
}
public void onCancel() {
// User released a finger outside any key
}
private void handleBackspace() {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
mVoiceInput.incrementTextModificationDeleteCount(
mVoiceResults.candidates.get(0).toString().length());
revertVoiceInput();
return;
}
boolean deleteChar = false;
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mAfterVoiceInput) {
// Don't log delete if the user is pressing delete at
// the beginning of the text box (hence not deleting anything)
if (mVoiceInput.getCursorPos() > 0) {
// If anything was selected before the delete was pressed, increment the
// delete count by the length of the selection
int deleteLen = mVoiceInput.getSelectionSpan() > 0 ?
mVoiceInput.getSelectionSpan() : 1;
mVoiceInput.incrementTextModificationDeleteCount(deleteLen);
}
}
if (mPredicting) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mPredicting = false;
}
postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
} else if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Tap again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
mJustRevertedSeparator = null;
ic.endBatchEdit();
}
private void resetShift() {
handleShiftInternal(true);
}
private void handleShift() {
handleShiftInternal(false);
}
private void handleShiftInternal(boolean forceNormal) {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
KeyboardSwitcher switcher = mKeyboardSwitcher;
LatinKeyboardView inputView = switcher.getInputView();
if (switcher.isAlphabetMode()) {
if (mCapsLock || forceNormal) {
mCapsLock = false;
switcher.setShifted(false);
} else if (inputView != null) {
if (inputView.isShifted()) {
mCapsLock = true;
switcher.setShiftLocked(true);
} else {
switcher.setShifted(true);
}
}
} else {
switcher.toggleShift();
}
}
private void abortCorrection(boolean force) {
if (force || TextEntryState.isCorrecting()) {
getCurrentInputConnection().finishComposingText();
clearSuggestions();
}
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput) {
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertCount(1);
}
if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) {
abortCorrection(false);
}
if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) {
if (!mPredicting) {
mPredicting = true;
mComposing.setLength(0);
saveWordInHistory(mBestWord);
mWord.reset();
}
}
if (mKeyboardSwitcher.getInputView().isShifted()) {
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
primaryCode = keyCodes[0];
if (mKeyboardSwitcher.isAlphabetMode() && Character.isLowerCase(primaryCode)) {
int upperCaseCode = Character.toUpperCase(primaryCode);
if (upperCaseCode != primaryCode) {
primaryCode = upperCaseCode;
} else {
// Some keys, such as [eszett], have upper case as multi-characters.
String upperCase = new String(new int[] {primaryCode}, 0, 1).toUpperCase();
onText(upperCase);
return;
}
}
}
if (mPredicting) {
if (mKeyboardSwitcher.getInputView().isShifted()
&& mKeyboardSwitcher.isAlphabetMode()
&& mComposing.length() == 0) {
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) primaryCode);
mWord.add(primaryCode, keyCodes);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(
getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
}
ic.setComposingText(mComposing, 1);
}
postUpdateSuggestions();
} else {
sendKeyChar((char)primaryCode);
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (LatinIME.PERF_DEBUG) measureCps();
TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}
private void handleSeparator(int primaryCode) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput){
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertPunctuationCount(1);
}
// Should dismiss the "Tap again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
abortCorrection(false);
}
if (mPredicting) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
if (mAutoCorrectOn && primaryCode != '\'' &&
(mJustRevertedSeparator == null
|| mJustRevertedSeparator.length() == 0
|| mJustRevertedSeparator.charAt(0) != primaryCode)) {
pickedDefault = pickDefaultSuggestion();
// Picked the suggestion by the space key. We consider this
// as "added an auto space".
if (primaryCode == KEYCODE_SPACE) {
mJustAddedAutoSpace = true;
}
} else {
commitTyped(ic);
}
}
if (mJustAddedAutoSpace && primaryCode == KEYCODE_ENTER) {
removeTrailingSpace();
mJustAddedAutoSpace = false;
}
sendKeyChar((char)primaryCode);
// Handle the case of ". ." -> " .." with auto-space if necessary
// before changing the TextEntryState.
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode == KEYCODE_PERIOD) {
reswapPeriodAndSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true);
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode != KEYCODE_ENTER) {
swapPunctuationAndSpace();
} else if (isPredictionOn() && primaryCode == KEYCODE_SPACE) {
doubleSpace();
}
if (pickedDefault) {
TextEntryState.backToAcceptedDefault(mWord.getTypedWord());
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
requestHideSelf(0);
if (mKeyboardSwitcher != null) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.closing();
}
}
TextEntryState.endSession();
}
private void saveWordInHistory(CharSequence result) {
if (mWord.size() <= 1) {
mWord.reset();
return;
}
// Skip if result is null. It happens in some edge case.
if (TextUtils.isEmpty(result)) {
return;
}
// Make a copy of the CharSequence, since it is/could be a mutable CharSequence
final String resultCopy = result.toString();
TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy,
new WordComposer(mWord));
mWordHistory.add(entry);
}
private void postUpdateSuggestions() {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100);
}
private void postUpdateOldSuggestions() {
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), 300);
}
private boolean isPredictionOn() {
return mPredictionOn;
}
private boolean isCandidateStripVisible() {
return isPredictionOn() && mShowSuggestions;
}
public void onCancelVoice() {
if (mRecognizing) {
switchToKeyboardView();
}
}
private void switchToKeyboardView() {
mHandler.post(new Runnable() {
public void run() {
mRecognizing = false;
if (mKeyboardSwitcher.getInputView() != null) {
setInputView(mKeyboardSwitcher.getInputView());
}
updateInputViewShown();
}});
}
private void switchToRecognitionStatusView() {
final boolean configChanged = mConfigurationChanging;
mHandler.post(new Runnable() {
public void run() {
mRecognizing = true;
View v = mVoiceInput.getView();
ViewParent p = v.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup)v.getParent()).removeView(v);
}
setInputView(v);
updateInputViewShown();
if (configChanged) {
mVoiceInput.onConfigurationChanged();
}
}});
}
private void startListening(boolean swipe) {
if (!mHasUsedVoiceInput ||
(!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale)) {
// Calls reallyStartListening if user clicks OK, does nothing if user clicks Cancel.
showVoiceWarningDialog(swipe);
} else {
reallyStartListening(swipe);
}
}
private void reallyStartListening(boolean swipe) {
if (!mHasUsedVoiceInput) {
// The user has started a voice input, so remember that in the
// future (so we don't show the warning dialog after the first run).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInput = true;
}
if (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale) {
// The user has started a voice input from an unsupported locale, so remember that
// in the future (so we don't show the warning dialog the next time they do this).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInputUnsupportedLocale = true;
}
// Clear N-best suggestions
clearSuggestions();
FieldContext context = new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
mVoiceInput.startListening(context, swipe);
switchToRecognitionStatusView();
}
private void showVoiceWarningDialog(final boolean swipe) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_mic_dialog);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogOk();
reallyStartListening(swipe);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogCancel();
}
});
if (mLocaleSupportedForVoiceInput) {
String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
} else {
String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" +
getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
}
builder.setTitle(R.string.voice_warning_title);
mVoiceWarningDialog = builder.create();
Window window = mVoiceWarningDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mVoiceInput.logKeyboardWarningDialogShown();
mVoiceWarningDialog.show();
}
public void onVoiceResults(List<String> candidates,
Map<String, List<CharSequence>> alternatives) {
if (!mRecognizing) {
return;
}
mVoiceResults.candidates = candidates;
mVoiceResults.alternatives = alternatives;
mHandler.sendMessage(mHandler.obtainMessage(MSG_VOICE_RESULTS));
}
private void handleVoiceResults() {
mAfterVoiceInput = true;
mImmediatelyAfterVoiceInput = true;
InputConnection ic = getCurrentInputConnection();
if (!isFullscreenMode()) {
// Start listening for updates to the text from typing, etc.
if (ic != null) {
ExtractedTextRequest req = new ExtractedTextRequest();
ic.getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR);
}
}
vibrate();
switchToKeyboardView();
final List<CharSequence> nBest = new ArrayList<CharSequence>();
boolean capitalizeFirstWord = preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& mKeyboardSwitcher.getInputView().isShifted());
for (String c : mVoiceResults.candidates) {
if (capitalizeFirstWord) {
c = Character.toUpperCase(c.charAt(0)) + c.substring(1, c.length());
}
nBest.add(c);
}
if (nBest.size() == 0) {
return;
}
String bestResult = nBest.get(0).toString();
mVoiceInput.logVoiceInputDelivered(bestResult.length());
mHints.registerVoiceResult(bestResult);
if (ic != null) ic.beginBatchEdit(); // To avoid extra updates on committing older text
commitTyped(ic);
EditingUtil.appendText(ic, bestResult);
if (ic != null) ic.endBatchEdit();
mVoiceInputHighlighted = true;
mWordToSuggestions.putAll(mVoiceResults.alternatives);
}
private void clearSuggestions() {
setSuggestions(null, false, false, false);
}
private void setSuggestions(
List<CharSequence> suggestions,
boolean completions,
boolean typedWordValid,
boolean haveMinimalSuggestion) {
if (mIsShowingHint) {
setCandidatesView(mCandidateViewContainer);
mIsShowingHint = false;
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(
suggestions, completions, typedWordValid, haveMinimalSuggestion);
}
}
private void updateSuggestions() {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isPredictionOn()) && !mVoiceInputHighlighted) {
return;
}
if (!mPredicting) {
setNextSuggestions();
return;
}
showSuggestions(mWord);
}
private List<CharSequence> getTypedSuggestions(WordComposer word) {
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, null);
return stringList;
}
private void showCorrections(WordAlternatives alternatives) {
List<CharSequence> stringList = alternatives.getAlternatives();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(null);
showSuggestions(stringList, alternatives.getOriginalWord(), false, false);
}
private void showSuggestions(WordComposer word) {
// long startTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// TODO Maybe need better way of retrieving previous word
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mWordSeparators);
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, prevWord);
// long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime));
int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(
nextLettersFrequencies);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasMinimalCorrection();
//|| mCorrectionMode == mSuggest.CORRECTION_FULL;
CharSequence typedWord = word.getTypedWord();
// If we're in basic correct
boolean typedWordValid = mSuggest.isValidWord(typedWord) ||
(preferCapitalization()
&& mSuggest.isValidWord(typedWord.toString().toLowerCase()));
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isCorrecting();
showSuggestions(stringList, typedWord, typedWordValid, correctionAvailable);
}
private void showSuggestions(List<CharSequence> stringList, CharSequence typedWord,
boolean typedWordValid, boolean correctionAvailable) {
setSuggestions(stringList, false, typedWordValid, correctionAvailable);
if (stringList.size() > 0) {
if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
mBestWord = stringList.get(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
private boolean pickDefaultSuggestion() {
// Complete any pending candidate query first
if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
mJustAccepted = true;
pickSuggestion(mBestWord, false);
// Add the word to the auto dictionary if it's not a known word
addToDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
if (mAfterVoiceInput && mShowingVoiceSuggestions) mVoiceInput.logNBestChoose(index);
List<CharSequence> suggestions = mCandidateView.getSuggestions();
if (mAfterVoiceInput && !mShowingVoiceSuggestions) {
mVoiceInput.flushAllTextModificationCounters();
// send this intent AFTER logging any prior aggregated edits.
mVoiceInput.logTextModifiedByChooseSuggestion(suggestion.length());
}
final boolean correcting = TextEntryState.isCorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions);
onKey(suggestion.charAt(0), null, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
if (ic != null) {
ic.endBatchEdit();
}
return;
}
mJustAccepted = true;
pickSuggestion(suggestion, correcting);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mAutoSpace && !correcting) {
sendSpace();
mJustAddedAutoSpace = true;
}
final boolean showingAddToDictionaryHint = index == 0 && mCorrectionMode > 0
&& !mSuggest.isValidWord(suggestion)
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase());
if (!correcting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) KEYCODE_SPACE, true);
setNextSuggestions();
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Tap again to save hint", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
private void rememberReplacedWord(CharSequence suggestion) {
if (mShowingVoiceSuggestions) {
// Retain the replaced word in the alternatives array.
EditingUtil.Range range = new EditingUtil.Range();
String wordToBeReplaced = EditingUtil.getWordAtCursor(getCurrentInputConnection(),
mWordSeparators, range);
if (!mWordToSuggestions.containsKey(wordToBeReplaced)) {
wordToBeReplaced = wordToBeReplaced.toLowerCase();
}
if (mWordToSuggestions.containsKey(wordToBeReplaced)) {
List<CharSequence> suggestions = mWordToSuggestions.get(wordToBeReplaced);
if (suggestions.contains(suggestion)) {
suggestions.remove(suggestion);
}
suggestions.add(wordToBeReplaced);
mWordToSuggestions.remove(wordToBeReplaced);
mWordToSuggestions.put(suggestion.toString(), suggestions);
}
}
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
* @param suggestion the suggestion picked by the user to be committed to
* the text field
* @param correcting whether this is due to a correction of an existing
* word.
*/
private void pickSuggestion(CharSequence suggestion, boolean correcting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (mCapsLock) {
suggestion = suggestion.toString().toUpperCase();
} else if (preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& inputView.isShifted())) {
suggestion = suggestion.toString().toUpperCase().charAt(0)
+ suggestion.subSequence(1, suggestion.length()).toString();
}
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
rememberReplacedWord(suggestion);
ic.commitText(suggestion, 1);
}
saveWordInHistory(suggestion);
mPredicting = false;
mCommittedLength = suggestion.length();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// If we just corrected a word, then don't show punctuations
if (!correcting) {
setNextSuggestions();
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
/**
* Tries to apply any voice alternatives for the word if this was a spoken word and
* there are voice alternatives.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyVoiceAlternatives(EditingUtil.SelectedWord touching) {
// Search for result in spoken word alternatives
String selectedWord = touching.word.toString().trim();
if (!mWordToSuggestions.containsKey(selectedWord)) {
selectedWord = selectedWord.toLowerCase();
}
if (mWordToSuggestions.containsKey(selectedWord)) {
mShowingVoiceSuggestions = true;
List<CharSequence> suggestions = mWordToSuggestions.get(selectedWord);
// If the first letter of touching is capitalized, make all the suggestions
// start with a capital letter.
if (Character.isUpperCase(touching.word.charAt(0))) {
for (int i = 0; i < suggestions.size(); i++) {
String origSugg = (String) suggestions.get(i);
String capsSugg = origSugg.toUpperCase().charAt(0)
+ origSugg.subSequence(1, origSugg.length()).toString();
suggestions.set(i, capsSugg);
}
}
setSuggestions(suggestions, false, true, true);
setCandidatesViewShown(true);
return true;
}
return false;
}
/**
* Tries to apply any typed alternatives for the word if we have any cached alternatives,
* otherwise tries to find new corrections and completions for the word.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyTypedAlternatives(EditingUtil.SelectedWord touching) {
// If we didn't find a match, search for result in typed word history
WordComposer foundWord = null;
WordAlternatives alternatives = null;
for (WordAlternatives entry : mWordHistory) {
if (TextUtils.equals(entry.getChosenWord(), touching.word)) {
if (entry instanceof TypedWordAlternatives) {
foundWord = ((TypedWordAlternatives) entry).word;
}
alternatives = entry;
break;
}
}
// If we didn't find a match, at least suggest completions
if (foundWord == null
&& (mSuggest.isValidWord(touching.word)
|| mSuggest.isValidWord(touching.word.toString().toLowerCase()))) {
foundWord = new WordComposer();
for (int i = 0; i < touching.word.length(); i++) {
foundWord.add(touching.word.charAt(i), new int[] {
touching.word.charAt(i)
});
}
foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.word.charAt(0)));
}
// Found a match, show suggestions
if (foundWord != null || alternatives != null) {
if (alternatives == null) {
alternatives = new TypedWordAlternatives(touching.word, foundWord);
}
showCorrections(alternatives);
if (foundWord != null) {
mWord = new WordComposer(foundWord);
} else {
mWord.reset();
}
return true;
}
return false;
}
private void setOldSuggestions() {
mShowingVoiceSuggestions = false;
if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) {
return;
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
if (!mPredicting) {
// Extract the selected or touching text
EditingUtil.SelectedWord touching = EditingUtil.getWordAtCursorOrSelection(ic,
mLastSelectionStart, mLastSelectionEnd, mWordSeparators);
if (touching != null && touching.word.length() > 1) {
ic.beginBatchEdit();
if (!applyVoiceAlternatives(touching) && !applyTypedAlternatives(touching)) {
abortCorrection(true);
} else {
TextEntryState.selectedForCorrection();
EditingUtil.underlineWord(ic, touching);
}
ic.endBatchEdit();
} else {
abortCorrection(true);
setNextSuggestions();
}
} else {
abortCorrection(true);
}
}
private void setNextSuggestions() {
setSuggestions(mSuggestPuncList, false, false, false);
}
private void addToDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToBigramDictionary(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
* @param addToBigramDictionary true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta,
boolean addToBigramDictionary) {
if (suggestion == null || suggestion.length() < 1) return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
if (suggestion != null) {
if (!addToBigramDictionary && mAutoDictionary.isValidWord(suggestion)
|| (!mSuggest.isValidWord(suggestion.toString())
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase()))) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mSentenceSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
}
private boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !isWordSeparator(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !isWordSeparator(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mPredicting && length > 0) {
final InputConnection ic = getCurrentInputConnection();
mPredicting = true;
mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (toTheLeft != null && toTheLeft.length() > 0
&& isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
mJustRevertedSeparator = null;
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private boolean isSentenceSeparator(int code) {
return mSentenceSeparators.contains(String.valueOf((char)code));
}
private void sendSpace() {
sendKeyChar((char)KEYCODE_SPACE);
updateShiftKeyState(getCurrentInputEditorInfo());
//onKey(KEY_SPACE[0], KEY_SPACE);
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
private void toggleLanguage(boolean reset, boolean next) {
if (reset) {
mLanguageSwitcher.reset();
} else {
if (next) {
mLanguageSwitcher.next();
} else {
mLanguageSwitcher.prev();
}
}
int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode();
reloadKeyboards();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0,
mEnableVoiceButton && mEnableVoice);
initSuggest(mLanguageSwitcher.getInputLanguage());
mLanguageSwitcher.persist();
updateShiftKeyState(getCurrentInputEditorInfo());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PREF_SELECTED_LANGUAGES.equals(key)) {
mLanguageSwitcher.loadLocales(sharedPreferences);
mRefreshKeyboardRequired = true;
} else if (PREF_RECORRECTION_ENABLED.equals(key)) {
mReCorrectionEnabled = sharedPreferences.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
}
}
public void swipeRight() {
if (LatinKeyboardView.DEBUG_AUTO_PLAY) {
ClipboardManager cm = ((ClipboardManager)getSystemService(CLIPBOARD_SERVICE));
CharSequence text = cm.getText();
if (!TextUtils.isEmpty(text)) {
mKeyboardSwitcher.getInputView().startPlaying(text.toString());
}
}
}
public void swipeLeft() {
}
public void swipeDown() {
handleClose();
}
public void swipeUp() {
//launchSettings();
}
public void onPress(int primaryCode) {
vibrate();
playKeyClick(primaryCode);
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
mShiftKeyState.onPress();
handleShift();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
mSymbolKeyState.onPress();
changeKeyboardMode();
} else {
mShiftKeyState.onOtherKeyPressed();
mSymbolKeyState.onOtherKeyPressed();
}
}
public void onRelease(int primaryCode) {
// Reset any drag flags in the keyboard
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).keyReleased();
//vibrate();
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
if (mShiftKeyState.isMomentary())
resetShift();
mShiftKeyState.onRelease();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
if (mSymbolKeyState.isMomentary())
changeKeyboardMode();
mSymbolKeyState.onRelease();
}
}
private FieldContext makeFieldContext() {
return new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
}
private boolean fieldCanDoVoice(FieldContext fieldContext) {
return !mPasswordText
&& mVoiceInput != null
&& !mVoiceInput.isBlacklistedField(fieldContext);
}
private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) {
return ENABLE_VOICE_BUTTON && fieldCanDoVoice(fieldContext)
&& !(attribute != null && attribute.privateImeOptions != null
&& attribute.privateImeOptions.equals(IME_OPTION_NO_MICROPHONE))
&& SpeechRecognizer.isRecognitionAvailable(this);
}
// receive ringer mode changes to detect silent mode
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRingerMode();
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case KEYCODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case KEYCODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
private void vibrate() {
if (!mVibrateOn) {
return;
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
private void checkTutorial(String privateImeOptions) {
if (privateImeOptions == null) return;
if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) {
if (mTutorial == null) startTutorial();
} else if (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) {
if (mTutorial != null) {
if (mTutorial.close()) {
mTutorial = null;
}
}
}
}
private void startTutorial() {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500);
}
void tutorialDone() {
mTutorial = null;
}
void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
WordComposer getCurrentWord() {
return mWord;
}
boolean getPopupOn() {
return mPopupOn;
}
private void updateCorrectionMode() {
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled(Locale systemLocale) {
if (mSuggest == null) return;
boolean different =
!systemLocale.getLanguage().equalsIgnoreCase(mInputLocale.substring(0, 2));
mSuggest.setAutoTextEnabled(!different && mQuickFixes);
}
protected void launchSettings() {
launchSettings(LatinIMESettings.class);
}
public void launchDebugSettings() {
launchSettings(LatinIMEDebugSettings.class);
}
protected void launchSettings (Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings() {
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false);
mSoundOn = sp.getBoolean(PREF_SOUND_ON, false);
mPopupOn = sp.getBoolean(PREF_POPUP_ON,
mResources.getBoolean(R.bool.default_popup_preview));
mAutoCap = sp.getBoolean(PREF_AUTO_CAP, true);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mHasUsedVoiceInput = sp.getBoolean(PREF_HAS_USED_VOICE_INPUT, false);
mHasUsedVoiceInputUnsupportedLocale =
sp.getBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, false);
// Get the current list of supported locales and check the current locale against that
// list. We cache this value so as not to check it every time the user starts a voice
// input. Because this method is called by onStartInputView, this should mean that as
// long as the locale doesn't change while the user is keeping the IME open, the
// value should never be stale.
String supportedLocalesString = SettingsUtil.getSettingsString(
getContentResolver(),
SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
ArrayList<String> voiceInputSupportedLocales =
newArrayList(supportedLocalesString.split("\\s+"));
mLocaleSupportedForVoiceInput = voiceInputSupportedLocales.contains(mInputLocale);
mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, true);
if (VOICE_INSTALLED) {
final String voiceMode = sp.getString(PREF_VOICE_MODE,
getString(R.string.voice_mode_main));
boolean enableVoice = !voiceMode.equals(getString(R.string.voice_mode_off))
&& mEnableVoiceButton;
boolean voiceOnPrimary = voiceMode.equals(getString(R.string.voice_mode_main));
if (mKeyboardSwitcher != null &&
(enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) {
mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary);
}
mEnableVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
}
mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE,
mResources.getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions;
//mBigramSuggestionEnabled = sp.getBoolean(
// PREF_BIGRAM_SUGGESTIONS, true) & mShowSuggestions;
updateCorrectionMode();
updateAutoTextEnabled(mResources.getConfiguration().locale);
mLanguageSwitcher.loadLocales(sp);
}
private void initSuggestPuncList() {
mSuggestPuncList = new ArrayList<CharSequence>();
mSuggestPuncs = mResources.getString(R.string.suggested_punctuations);
if (mSuggestPuncs != null) {
for (int i = 0; i < mSuggestPuncs.length(); i++) {
mSuggestPuncList.add(mSuggestPuncs.subSequence(i, i + 1));
}
}
}
private boolean isSuggestedPunctuation(int code) {
return mSuggestPuncs.contains(String.valueOf((char)code));
}
private void showOptionsMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
CharSequence itemSettings = getString(R.string.english_ime_settings);
CharSequence itemInputMethod = getString(R.string.selectInputMethod);
builder.setItems(new CharSequence[] {
itemInputMethod, itemSettings},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case POS_SETTINGS:
launchSettings();
break;
case POS_METHOD:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
}
}
});
builder.setTitle(mResources.getString(R.string.english_ime_input_options));
mOptionsDialog = builder.create();
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
private void changeKeyboardMode() {
mKeyboardSwitcher.toggleSymbols();
if (mCapsLock && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShiftLocked(mCapsLock);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mCapsLock=" + mCapsLock);
p.println(" mComposing=" + mComposing.toString());
p.println(" mPredictionOn=" + mPredictionOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mPredicting=" + mPredicting);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mAutoSpace=" + mAutoSpace);
p.println(" mCompletionOn=" + mCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
p.println(" mPopupOn=" + mPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
public void onAutoCompletionStateChanged(boolean isAutoCompletion) {
mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion);
}
}
|
Disable suggestion bar before invoke Voice input
Bug: 3002817
Change-Id: I099dd63e58d5159a609c1d934dbb6f5aab914305
|
java/src/com/android/inputmethod/latin/LatinIME.java
|
Disable suggestion bar before invoke Voice input
|
|
Java
|
apache-2.0
|
a1675ff70ff90785781a77ca392421065bc812e7
| 0
|
malinthaprasan/carbon-apimgt,chamilaadhi/carbon-apimgt,tharindu1st/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,prasa7/carbon-apimgt,praminda/carbon-apimgt,tharindu1st/carbon-apimgt,praminda/carbon-apimgt,ruks/carbon-apimgt,wso2/carbon-apimgt,praminda/carbon-apimgt,ruks/carbon-apimgt,prasa7/carbon-apimgt,prasa7/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,wso2/carbon-apimgt,ruks/carbon-apimgt,chamilaadhi/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,wso2/carbon-apimgt,ruks/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,tharindu1st/carbon-apimgt,malinthaprasan/carbon-apimgt,wso2/carbon-apimgt,chamilaadhi/carbon-apimgt,malinthaprasan/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.impl;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import feign.Feign;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.AccessTokenInfo;
import org.wso2.carbon.apimgt.api.model.AccessTokenRequest;
import org.wso2.carbon.apimgt.api.model.ApplicationConstants;
import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration;
import org.wso2.carbon.apimgt.api.model.OAuthAppRequest;
import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.dto.ScopeDTO;
import org.wso2.carbon.apimgt.impl.dto.UserInfoDTO;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.kmclient.ApacheFeignHttpClient;
import org.wso2.carbon.apimgt.impl.kmclient.FormEncoder;
import org.wso2.carbon.apimgt.impl.kmclient.KMClientErrorDecoder;
import org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException;
import org.wso2.carbon.apimgt.impl.kmclient.model.AuthClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.Claim;
import org.wso2.carbon.apimgt.impl.kmclient.model.ClaimsList;
import org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.DCRClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectionClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.ScopeClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.TenantHeaderInterceptor;
import org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.UserClient;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* This class holds the key manager implementation considering WSO2 as the identity provider
* This is the default key manager supported by API Manager.
*/
public class AMDefaultKeyManagerImpl extends AbstractKeyManager {
private static final Log log = LogFactory.getLog(AMDefaultKeyManagerImpl.class);
private static final String GRANT_TYPE_VALUE = "client_credentials";
private static final String ENCODE_CONSUMER_KEY = "encodeConsumerKey";
private DCRClient dcrClient;
private IntrospectionClient introspectionClient;
private AuthClient authClient;
private ScopeClient scopeClient;
private UserClient userClient;
@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException {
// OAuthApplications are created by calling to APIKeyMgtSubscriber Service
OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();
// Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created.
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.
OAUTH_CLIENT_USERNAME);
if (StringUtils.isEmpty(userId)) {
throw new APIManagementException("Missing user ID for OAuth application creation.");
}
String applicationName = oAuthApplicationInfo.getClientName();
String oauthClientName = oauthAppRequest.getOAuthApplicationInfo().getApplicationUUID();
String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
String domain = UserCoreUtil.extractDomainFromName(userId);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.
getTenantAwareUsername(userId)), oauthClientName, keyType);
} else {
throw new APIManagementException("Missing required information for OAuth application creation.");
}
if (log.isDebugEnabled()) {
log.debug("Trying to create OAuth application : " + oauthClientName + " for application: " + applicationName
+ " and key type: " + keyType);
}
String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
String[] tokenScopes = new String[1];
tokenScopes[0] = tokenScope;
ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, false);
ClientInfo createdClient;
try {
createdClient = dcrClient.createApplication(request);
buildDTOFromClientInfo(createdClient, oAuthApplicationInfo);
oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
oAuthApplicationInfo.setIsSaasApplication(false);
return oAuthApplicationInfo;
} catch (KeyManagerClientException e) {
handleException(
"Can not create OAuth application : " + oauthClientName + " for application: " + applicationName
+ " and key type: " + keyType, e);
return null;
}
}
/**
* Construct ClientInfo object for application create request
*
* @param info The OAuthApplicationInfo object
* @param oauthClientName The name of the OAuth application to be created
* @param isUpdate To determine whether the ClientInfo object is related to application update call
* @return constructed ClientInfo object
* @throws JSONException for errors in parsing the OAuthApplicationInfo json string
* @throws APIManagementException if an error occurs while constructing the ClientInfo object
*/
private ClientInfo createClientInfo(OAuthApplicationInfo info, String oauthClientName, boolean isUpdate)
throws JSONException, APIManagementException {
ClientInfo clientInfo = new ClientInfo();
JSONObject infoJson = new JSONObject(info.getJsonString());
String applicationOwner = (String) info.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
if (infoJson.has(ApplicationConstants.OAUTH_CLIENT_GRANT)) {
// this is done as there are instances where the grant string begins with a comma character.
String grantString = infoJson.getString(ApplicationConstants.OAUTH_CLIENT_GRANT);
if (grantString.startsWith(",")) {
grantString = grantString.substring(1);
}
String[] grantTypes = grantString.split(",");
clientInfo.setGrantTypes(Arrays.asList(grantTypes));
}
if (StringUtils.isNotEmpty(info.getCallBackURL())) {
String callBackURL = info.getCallBackURL();
String[] callbackURLs = callBackURL.trim().split("\\s*,\\s*");
clientInfo.setRedirectUris(Arrays.asList(callbackURLs));
}
clientInfo.setClientName(oauthClientName);
//todo: run tests by commenting the type
if (StringUtils.isEmpty(info.getTokenType())) {
clientInfo.setTokenType(APIConstants.TOKEN_TYPE_JWT);
} else {
clientInfo.setTokenType(info.getTokenType());
}
// Use a generated user as the app owner for cross tenant subscription scenarios, to avoid the tenant admin
// being exposed in the JWT token.
if (APIUtil.isCrossTenantSubscriptionsEnabled()
&& !tenantDomain.equals(MultitenantUtils.getTenantDomain(applicationOwner))) {
clientInfo.setApplication_owner(APIUtil.retrieveDefaultReservedUsername());
} else {
clientInfo.setApplication_owner(MultitenantUtils.getTenantAwareUsername(applicationOwner));
}
if (StringUtils.isNotEmpty(info.getClientId())) {
if (isUpdate) {
clientInfo.setClientId(info.getClientId());
} else {
clientInfo.setPresetClientId(info.getClientId());
}
}
if (StringUtils.isNotEmpty(info.getClientSecret())) {
if (isUpdate) {
clientInfo.setClientId(info.getClientSecret());
} else {
clientInfo.setPresetClientSecret(info.getClientSecret());
}
}
Object parameter = info.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
Map<String, Object> additionalProperties = new HashMap<>();
if (parameter instanceof String) {
additionalProperties = new Gson().fromJson((String) parameter, Map.class);
}
if (additionalProperties.containsKey(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
if (expiry < 0) {
throw new APIManagementException("Invalid application access token expiry time given for "
+ oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
}
clientInfo.setApplicationAccessTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
if (expiry < 0) {
throw new APIManagementException("Invalid user access token expiry time given for "
+ oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
}
clientInfo.setUserAccessTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
clientInfo.setRefreshTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
clientInfo.setIdTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_MANDATORY)) {
Object pkceMandatoryValue =
additionalProperties.get(APIConstants.KeyManager.PKCE_MANDATORY);
if (pkceMandatoryValue instanceof String) {
if (!APIConstants.KeyManager.PKCE_MANDATORY.equals(pkceMandatoryValue)) {
try {
Boolean pkceMandatory = Boolean.parseBoolean((String) pkceMandatoryValue);
clientInfo.setPkceMandatory(pkceMandatory);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN)) {
Object pkceSupportPlainValue =
additionalProperties.get(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN);
if (pkceSupportPlainValue instanceof String) {
if (!APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(pkceSupportPlainValue)) {
try {
Boolean pkceSupportPlain = Boolean.parseBoolean((String) pkceSupportPlainValue);
clientInfo.setPkceSupportPlain(pkceSupportPlain);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS)) {
Object bypassClientCredentialsValue =
additionalProperties.get(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS);
if (bypassClientCredentialsValue instanceof String) {
if (!APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(bypassClientCredentialsValue)) {
try {
Boolean bypassClientCredentials = Boolean.parseBoolean((String) bypassClientCredentialsValue);
clientInfo.setBypassClientCredentials(bypassClientCredentials);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
// Set the display name of the application. This name would appear in the consent page of the app.
clientInfo.setApplicationDisplayName(info.getClientName());
return clientInfo;
}
@Override
public OAuthApplicationInfo updateApplication(OAuthAppRequest appInfoDTO) throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
String applicationName = oAuthApplicationInfo.getClientName();
String oauthClientName = oAuthApplicationInfo.getApplicationUUID();
String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
// First we attempt to get the tenant domain from the userID and if it is not possible, we fetch it
// from the ThreadLocalCarbonContext
if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
// Replace the domain name separator with an underscore for secondary user stores
String domain = UserCoreUtil.extractDomainFromName(userId);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
// Construct the application name subsequent to replacing email domain separator
oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.
getTenantAwareUsername(userId)), oauthClientName, keyType);
} else {
throw new APIManagementException("Missing required information for OAuth application update.");
}
log.debug("Updating OAuth Client with ID : " + oAuthApplicationInfo.getClientId());
if (log.isDebugEnabled() && oAuthApplicationInfo.getCallBackURL() != null) {
log.debug("CallBackURL : " + oAuthApplicationInfo.getCallBackURL());
}
if (log.isDebugEnabled() && applicationName != null) {
log.debug("Client Name : " + oauthClientName);
}
ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, true);
ClientInfo createdClient;
try {
createdClient = dcrClient.updateApplication(Base64.getUrlEncoder().encodeToString(
oAuthApplicationInfo.getClientId().getBytes(StandardCharsets.UTF_8)), request);
return buildDTOFromClientInfo(createdClient, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
handleException("Error occurred while updating OAuth Client : ", e);
return null;
}
}
@Override
public OAuthApplicationInfo updateApplicationOwner(OAuthAppRequest appInfoDTO, String owner)
throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
log.debug("Updating Application Owner : " + oAuthApplicationInfo.getClientId());
ClientInfo updatedClient;
try {
updatedClient = dcrClient.updateApplicationOwner(owner, Base64.getUrlEncoder().encodeToString(
oAuthApplicationInfo.getClientId().getBytes(StandardCharsets.UTF_8)));
return buildDTOFromClientInfo(updatedClient, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
handleException("Error occurred while updating OAuth Client : ", e);
return null;
}
}
@Override
public void deleteApplication(String consumerKey) throws APIManagementException {
if (log.isDebugEnabled()) {
log.debug("Trying to delete OAuth application for consumer key :" + consumerKey);
}
try {
dcrClient.deleteApplication(Base64.getUrlEncoder().encodeToString(
consumerKey.getBytes(StandardCharsets.UTF_8)));
} catch (KeyManagerClientException e) {
handleException("Cannot remove service provider for the given consumer key : " + consumerKey, e);
}
}
@Override
public OAuthApplicationInfo retrieveApplication(String consumerKey) throws APIManagementException {
if (log.isDebugEnabled()) {
log.debug("Trying to retrieve OAuth application for consumer key :" + consumerKey);
}
try {
ClientInfo clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(
consumerKey.getBytes(StandardCharsets.UTF_8)));
return buildDTOFromClientInfo(clientInfo, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
if (e.getStatusCode() == 404) {
return null;
}
handleException("Cannot retrieve service provider for the given consumer key : " + consumerKey, e);
return null;
}
}
@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {
AccessTokenInfo tokenInfo;
if (tokenRequest == null) {
log.warn("No information available to generate Token.");
return null;
}
//We do not revoke the previously obtained token anymore since we do not possess the access token.
// When validity time set to a negative value, a token is considered never to expire.
if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
// Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
tokenRequest.setValidityPeriod(-2L);
}
//Generate New Access Token
String scopes = String.join(" ", tokenRequest.getScope());
TokenInfo tokenResponse;
try {
String credentials = tokenRequest.getClientId() + ':' + tokenRequest.getClientSecret();
String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
tokenResponse = authClient.generate(authToken, GRANT_TYPE_VALUE, scopes);
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred while calling token endpoint - " + e.getReason(), e);
}
tokenInfo = new AccessTokenInfo();
if (StringUtils.isNotEmpty(tokenResponse.getScope())) {
tokenInfo.setScope(tokenResponse.getScope().split(" "));
} else {
tokenInfo.setScope(new String[0]);
}
tokenInfo.setAccessToken(tokenResponse.getToken());
tokenInfo.setValidityPeriod(tokenResponse.getExpiry());
return tokenInfo;
}
@Override
public String getNewApplicationConsumerSecret(AccessTokenRequest tokenRequest) throws APIManagementException {
ClientInfo updatedClient;
try {
updatedClient = dcrClient.updateApplicationSecret(tokenRequest.getClientId());
return updatedClient.getClientSecret();
} catch (KeyManagerClientException e) {
handleException("Error while generating new consumer secret", e);
}
return null;
}
@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
try {
IntrospectInfo introspectInfo = introspectionClient.introspect(accessToken);
tokenInfo.setAccessToken(accessToken);
boolean isActive = introspectInfo.isActive();
if (!isActive) {
tokenInfo.setTokenValid(false);
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
return tokenInfo;
}
tokenInfo.setTokenValid(true);
if (introspectInfo.getIat() > 0 && introspectInfo.getExpiry() > 0) {
if (introspectInfo.getExpiry() != Long.MAX_VALUE) {
long validityPeriod = introspectInfo.getExpiry() - introspectInfo.getIat();
tokenInfo.setValidityPeriod(validityPeriod * 1000L);
} else {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
}
tokenInfo.setIssuedTime(introspectInfo.getIat() * 1000L);
}
if (StringUtils.isNotEmpty(introspectInfo.getScope())) {
String[] scopes = introspectInfo.getScope().split(" ");
tokenInfo.setScope(scopes);
}
tokenInfo.setConsumerKey(introspectInfo.getClientId());
String username = introspectInfo.getUsername();
if (!StringUtils.isEmpty(username)) {
tokenInfo.setEndUserName(username);
}
return tokenInfo;
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred in token introspection!", e);
}
}
@Override
public KeyManagerConfiguration getKeyManagerConfiguration() throws APIManagementException {
return configuration;
}
/**
* This method will create a new record at CLIENT_INFO table by given OauthAppRequest.
*
* @param appInfoRequest oAuth application properties will contain in this object
* @return OAuthApplicationInfo with created oAuth application details.
* @throws org.wso2.carbon.apimgt.api.APIManagementException
*/
@Override
public OAuthApplicationInfo mapOAuthApplication(OAuthAppRequest appInfoRequest)
throws APIManagementException {
//initiate OAuthApplicationInfo
OAuthApplicationInfo oAuthApplicationInfo = appInfoRequest.getOAuthApplicationInfo();
String consumerKey = oAuthApplicationInfo.getClientId();
String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
String[] tokenScopes = new String[1];
tokenScopes[0] = tokenScope;
String clientSecret = (String) oAuthApplicationInfo.getParameter("client_secret");
//for the first time we set default time period.
oAuthApplicationInfo.addParameter(ApplicationConstants.VALIDITY_PERIOD,
getConfigurationParamValue(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD));
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
//check whether given consumer key and secret match or not. If it does not match throw an exception.
ClientInfo clientInfo;
try {
clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(
consumerKey.getBytes(StandardCharsets.UTF_8)));
buildDTOFromClientInfo(clientInfo, oAuthApplicationInfo);
} catch (KeyManagerClientException e) {
handleException("Some thing went wrong while getting OAuth application for given consumer key " +
oAuthApplicationInfo.getClientId(), e);
}
if (!clientSecret.equals(oAuthApplicationInfo.getClientSecret())) {
throw new APIManagementException("The secret key is wrong for the given consumer key " + consumerKey);
}
oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
oAuthApplicationInfo.setIsSaasApplication(false);
if (log.isDebugEnabled()) {
log.debug("Creating semi-manual application for consumer id : " + oAuthApplicationInfo.getClientId());
}
return oAuthApplicationInfo;
}
/**
* Builds an OAuthApplicationInfo object using the ClientInfo response
*
* @param appResponse ClientInfo response object
* @param oAuthApplicationInfo original OAuthApplicationInfo object
* @return OAuthApplicationInfo object with response information added
*/
private OAuthApplicationInfo buildDTOFromClientInfo(ClientInfo appResponse,
OAuthApplicationInfo oAuthApplicationInfo) {
oAuthApplicationInfo.setClientName(appResponse.getClientName());
oAuthApplicationInfo.setClientId(appResponse.getClientId());
if (appResponse.getRedirectUris() != null) {
oAuthApplicationInfo.setCallBackURL(String.join(",", appResponse.getRedirectUris()));
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS,
String.join(",", appResponse.getRedirectUris()));
}
oAuthApplicationInfo.setClientSecret(appResponse.getClientSecret());
if (appResponse.getGrantTypes() != null) {
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT,
String.join(" ", appResponse.getGrantTypes()));
} else if (oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_GRANT) instanceof String) {
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT, ((String) oAuthApplicationInfo.
getParameter(ApplicationConstants.OAUTH_CLIENT_GRANT)).replace(",", " "));
}
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_NAME, appResponse.getClientName());
Map<String, Object> additionalProperties = new HashMap<>();
additionalProperties.put(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME,
appResponse.getApplicationAccessTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME,
appResponse.getUserAccessTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME,
appResponse.getRefreshTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME, appResponse.getIdTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.PKCE_MANDATORY, appResponse.getPkceMandatory());
additionalProperties.put(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN, appResponse.getPkceSupportPlain());
additionalProperties.put(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS,
appResponse.getBypassClientCredentials());
oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, additionalProperties);
return oAuthApplicationInfo;
}
@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {
this.configuration = configuration;
String username = (String) configuration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
String password = (String) configuration.getParameter(APIConstants.KEY_MANAGER_PASSWORD);
String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);
String dcrEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
} else {
dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat
(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_DCR_ENDPOINT);
}
String tokenEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
} else {
tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
"/oauth2/token");
}
addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
String revokeEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
} else {
revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
"/oauth2/revoke");
}
String scopeEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
} else {
scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim())
.concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
}
String introspectionEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
} else {
introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
}
String userInfoEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT) != null) {
userInfoEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT);
} else {
userInfoEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat
(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_USERINFO_ENDPOINT);
}
dcrClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(dcrEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(DCRClient.class, dcrEndpoint);
authClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(tokenEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.errorDecoder(new KMClientErrorDecoder())
.encoder(new FormEncoder())
.target(AuthClient.class, tokenEndpoint);
introspectionClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(introspectionEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.encoder(new FormEncoder())
.target(IntrospectionClient.class, introspectionEndpoint);
scopeClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(scopeEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(ScopeClient.class, scopeEndpoint);
userClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(userInfoEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(UserClient.class, userInfoEndpoint);
}
@Override
public boolean registerNewResource(API api, Map resourceAttributes) throws APIManagementException {
// //Register new resource means create new API with given Scopes.
//todo commented below code because of blocker due to API publish fail. need to find a better way of doing this
// ApiMgtDAO apiMgtDAO = new ApiMgtDAO();
// apiMgtDAO.addAPI(api, CarbonContext.getThreadLocalCarbonContext().getTenantId());
return true;
}
@Override
public Map getResourceByApiId(String apiId) throws APIManagementException {
return null;
}
@Override
public boolean updateRegisteredResource(API api, Map resourceAttributes) throws APIManagementException {
return false;
}
@Override
public void deleteRegisteredResourceByAPIId(String apiID) throws APIManagementException {
}
@Override
public void deleteMappedApplication(String consumerKey) throws APIManagementException {
}
@Override
public Set<String> getActiveTokensByConsumerKey(String consumerKey) throws APIManagementException {
return new HashSet<>();
}
/**
* Returns the access token information of the provided consumer key.
*
* @param consumerKey The consumer key.
* @return AccessTokenInfo The access token information.
* @throws APIManagementException
*/
@Override
public AccessTokenInfo getAccessTokenByConsumerKey(String consumerKey) throws APIManagementException {
return new AccessTokenInfo();
}
@Override
public Map<String, Set<Scope>> getScopesForAPIS(String apiIdsString)
throws APIManagementException {
return null;
}
/**
* This method will be used to register a Scope in the authorization server.
*
* @param scope Scope to register
* @throws APIManagementException if there is an error while registering a new scope.
*/
@Override
public void registerScope(Scope scope) throws APIManagementException {
String scopeKey = scope.getKey();
ScopeDTO scopeDTO = new ScopeDTO();
scopeDTO.setName(scopeKey);
scopeDTO.setDisplayName(scope.getName());
scopeDTO.setDescription(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) {
scopeDTO.setBindings(Arrays.asList(scope.getRoles().trim().split(",")));
}
try (Response response = scopeClient.registerScope(scopeDTO)) {
if (response.status() != HttpStatus.SC_CREATED) {
String responseString = readHttpResponseAsString(response.body());
throw new APIManagementException("Error occurred while registering scope: " + scopeKey + ". Error" +
" Status: " + response.status() + " . Error Response: " + responseString);
}
} catch (KeyManagerClientException e) {
handleException("Cannot register scope : " + scopeKey, e);
}
}
/**
* Read response body for HTTPResponse as a string.
*
* @param httpResponse HTTPResponse
* @return Response Body String
* @throws APIManagementException If an error occurs while reading the response
*/
protected String readHttpResponseAsString(Response.Body httpResponse) throws APIManagementException {
try (InputStream inputStream = httpResponse.asInputStream()) {
return IOUtils.toString(inputStream);
} catch (IOException e) {
String errorMessage = "Error occurred while reading response body as string";
throw new APIManagementException(errorMessage, e);
}
}
/**
* This method will be used to retrieve details of a Scope in the authorization server.
*
* @param name Scope Name to retrieve
* @return Scope object
* @throws APIManagementException if an error while retrieving scope
*/
@Override
public Scope getScopeByName(String name) throws APIManagementException {
ScopeDTO scopeDTO = null;
try {
scopeDTO = scopeClient.getScopeByName(name);
} catch (KeyManagerClientException ex) {
handleException("Cannot read scope : " + name, ex);
}
return fromDTOToScope(scopeDTO);
}
/**
* Get Scope object from ScopeDTO response received from authorization server.
*
* @param scopeDTO ScopeDTO response
* @return Scope model object
*/
private Scope fromDTOToScope(ScopeDTO scopeDTO) {
Scope scope = new Scope();
scope.setName(scopeDTO.getDisplayName());
scope.setKey(scopeDTO.getName());
scope.setDescription(scopeDTO.getDescription());
scope.setRoles((scopeDTO.getBindings() != null && !scopeDTO.getBindings().isEmpty())
? String.join(",", scopeDTO.getBindings()) : StringUtils.EMPTY);
return scope;
}
/**
* Get Scope object list from ScopeDTO List response received from authorization server.
*
* @param scopeDTOS Scope DTO Array
* @return Scope Object to Scope Name Mappings
*/
private Map<String, Scope> fromDTOListToScopeListMapping(ScopeDTO[] scopeDTOS) {
Map<String, Scope> scopeListMapping = new HashMap<>();
for (ScopeDTO scopeDTO : scopeDTOS) {
scopeListMapping.put(scopeDTO.getName(), fromDTOToScope(scopeDTO));
}
return scopeListMapping;
}
/**
* This method will be used to retrieve all the scopes available in the authorization server for the given tenant
* domain.
*
* @return Mapping of Scope object to scope key
* @throws APIManagementException if an error occurs while getting scopes list
*/
@Override
public Map<String, Scope> getAllScopes() throws APIManagementException {
ScopeDTO[] scopes = new ScopeDTO[0];
try {
scopes = scopeClient.getScopes();
} catch (KeyManagerClientException ex) {
handleException("Error while retrieving scopes", ex);
}
return fromDTOListToScopeListMapping(scopes);
}
/**
* This method will be used to attach a Scope in the authorization server to a API resource.
*
* @param api API
* @param uriTemplates URITemplate set with attached scopes
* @throws APIManagementException if an error occurs while attaching scope to resource
*/
@Override
public void attachResourceScopes(API api, Set<URITemplate> uriTemplates)
throws APIManagementException {
//TODO: Nothing to do here
}
/**
* This method will be used to update the local scopes and resource to scope attachments of an API in the
* authorization server.
*
* @param api API
* @param oldLocalScopeKeys Old local scopes of the API before update (excluding the versioned local scopes
* @param newLocalScopes New local scopes of the API after update
* @param oldURITemplates Old URI templates of the API before update
* @param newURITemplates New URI templates of the API after update
* @throws APIManagementException if fails to update resources scopes
*/
@Override
public void updateResourceScopes(API api, Set<String> oldLocalScopeKeys, Set<Scope> newLocalScopes,
Set<URITemplate> oldURITemplates, Set<URITemplate> newURITemplates)
throws APIManagementException {
detachResourceScopes(api, oldURITemplates);
// remove the old local scopes from the KM
for (String oldScope : oldLocalScopeKeys) {
deleteScope(oldScope);
}
//Register scopes
for (Scope scope : newLocalScopes) {
String scopeKey = scope.getKey();
// Check if key already registered in KM. Scope Key may be already registered for a different version.
if (!isScopeExists(scopeKey)) {
//register scope in KM
registerScope(scope);
} else {
if (log.isDebugEnabled()) {
log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope.");
}
}
}
attachResourceScopes(api, newURITemplates);
}
/**
* This method will be used to detach the resource scopes of an API and delete the local scopes of that API from
* the authorization server.
*
* @param api API API
* @param uriTemplates URITemplate Set with attach scopes to detach
* @throws APIManagementException if an error occurs while detaching resource scopes of the API.
*/
@Override
public void detachResourceScopes(API api, Set<URITemplate> uriTemplates)
throws APIManagementException {
//TODO: Nothing to do here
}
/**
* This method will be used to delete a Scope in the authorization server.
*
* @param scopeName Scope name
* @throws APIManagementException if an error occurs while deleting the scope
*/
@Override
public void deleteScope(String scopeName) throws APIManagementException {
try {
Response response = scopeClient.deleteScope(scopeName);
if (response.status() != HttpStatus.SC_OK) {
String responseString = readHttpResponseAsString(response.body());
String errorMessage =
"Error occurred while deleting scope: " + scopeName + ". Error Status: " + response.status() +
" . Error Response: " + responseString;
throw new APIManagementException(errorMessage);
}
} catch (KeyManagerClientException ex) {
handleException("Error occurred while deleting scope", ex);
}
}
/**
* This method will be used to update a Scope in the authorization server.
*
* @param scope Scope object
* @throws APIManagementException if an error occurs while updating the scope
*/
@Override
public void updateScope(Scope scope) throws APIManagementException {
String scopeKey = scope.getKey();
try {
ScopeDTO scopeDTO = new ScopeDTO();
scopeDTO.setDisplayName(scope.getName());
scopeDTO.setDescription(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) {
scopeDTO.setBindings(Arrays.asList(scope.getRoles().trim().split(",")));
}
scopeClient.updateScope(scopeDTO, scope.getKey());
} catch (KeyManagerClientException e) {
String errorMessage = "Error occurred while updating scope: " + scopeKey;
handleException(errorMessage, e);
}
}
/**
* This method will be used to check whether the a Scope exists for the given scope name in the authorization
* server.
*
* @param scopeName Scope Name
* @return whether scope exists or not
* @throws APIManagementException if an error occurs while checking the existence of the scope
*/
@Override
public boolean isScopeExists(String scopeName) throws APIManagementException {
try (Response response = scopeClient.isScopeExist(scopeName)) {
if (response.status() == HttpStatus.SC_OK) {
return true;
} else if (response.status() != HttpStatus.SC_NOT_FOUND) {
String responseString = readHttpResponseAsString(response.body());
String errorMessage = "Error occurred while checking existence of scope: " + scopeName + ". Error " +
"Status: " + response.status() + " . Error Response: " + responseString;
throw new APIManagementException(errorMessage);
}
} catch (KeyManagerClientException e) {
handleException("Error while check scope exist", e);
}
return false;
}
/**
* This method will be used to validate the scope set provided and populate the additional parameters
* (description and bindings) for each Scope object.
*
* @param scopes Scope set to validate
* @throws APIManagementException if an error occurs while validating and populating
*/
@Override
public void validateScopes(Set<Scope> scopes) throws APIManagementException {
for (Scope scope : scopes) {
Scope sharedScope = getScopeByName(scope.getKey());
scope.setName(sharedScope.getName());
scope.setDescription(sharedScope.getDescription());
scope.setRoles(sharedScope.getRoles());
}
}
@Override
public String getType() {
return APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE;
}
/**
* Return the value of the provided configuration parameter.
*
* @param parameter Parameter name
* @return Parameter value
*/
protected String getConfigurationParamValue(String parameter) {
return (String) configuration.getParameter(parameter);
}
/**
* Check whether Token partitioning is enabled.
*
* @return true/false
*/
protected boolean checkAccessTokenPartitioningEnabled() {
return APIUtil.checkAccessTokenPartitioningEnabled();
}
/**
* Check whether user name assertion is enabled.
*
* @return true/false
*/
protected boolean checkUserNameAssertionEnabled() {
return APIUtil.checkUserNameAssertionEnabled();
}
private String getTenantAwareContext() {
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
return "/t/".concat(tenantDomain);
}
return "";
}
private void addKeyManagerConfigsAsSystemProperties(String serviceUrl) {
URL keyManagerURL;
try {
keyManagerURL = new URL(serviceUrl);
String hostname = keyManagerURL.getHost();
int port = keyManagerURL.getPort();
if (port == -1) {
if (APIConstants.HTTPS_PROTOCOL.equals(keyManagerURL.getProtocol())) {
port = APIConstants.HTTPS_PROTOCOL_PORT;
} else {
port = APIConstants.HTTP_PROTOCOL_PORT;
}
}
System.setProperty(APIConstants.KEYMANAGER_PORT, String.valueOf(port));
if (hostname.equals(System.getProperty(APIConstants.CARBON_LOCALIP))) {
System.setProperty(APIConstants.KEYMANAGER_HOSTNAME, "localhost");
} else {
System.setProperty(APIConstants.KEYMANAGER_HOSTNAME, hostname);
}
//Since this is the server startup.Ignore the exceptions,invoked at the server startup
} catch (MalformedURLException e) {
log.error("Exception While resolving KeyManager Server URL or Port " + e.getMessage(), e);
}
}
@Override
public Map<String, String> getUserClaims(String username, Map<String, Object> properties)
throws APIManagementException {
Map<String, String> map = new HashMap<String, String>();
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
UserInfoDTO userinfo = new UserInfoDTO();
userinfo.setUsername(tenantAwareUserName);
if (tenantAwareUserName.contains(CarbonConstants.DOMAIN_SEPARATOR)) {
userinfo.setDomain(tenantAwareUserName.split(CarbonConstants.DOMAIN_SEPARATOR)[0]);
}
if (properties.containsKey(APIConstants.KeyManager.ACCESS_TOKEN)) {
userinfo.setAccessToken(properties.get(APIConstants.KeyManager.ACCESS_TOKEN).toString());
}
if (properties.containsKey(APIConstants.KeyManager.CLAIM_DIALECT)) {
userinfo.setDialectURI(properties.get(APIConstants.KeyManager.CLAIM_DIALECT).toString());
}
try {
ClaimsList claims = userClient.generateClaims(userinfo);
if (claims != null && claims.getList() != null) {
for (Claim claim : claims.getList()) {
map.put(claim.getUri(), claim.getValue());
}
}
} catch (KeyManagerClientException e) {
handleException("Error while getting user info", e);
}
return map;
}
@Override
protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo)
throws APIManagementException {
super.validateOAuthAppCreationProperties(oAuthApplicationInfo);
String type = getType();
KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance()
.getKeyManagerConnectorConfiguration(type);
if (keyManagerConnectorConfiguration != null) {
Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
if (additionalProperties != null) {
JsonObject additionalPropertiesJson = (JsonObject) new JsonParser()
.parse((String) additionalProperties);
for (Map.Entry<String, JsonElement> entry : additionalPropertiesJson.entrySet()) {
String additionalProperty = entry.getValue().getAsString();
if (StringUtils.isNotBlank(additionalProperty) && !StringUtils
.equals(additionalProperty, APIConstants.KeyManager.NOT_APPLICABLE_VALUE)) {
try {
if (APIConstants.KeyManager.PKCE_MANDATORY.equals(entry.getKey()) ||
APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(entry.getKey()) ||
APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(entry.getKey())) {
if (!(additionalProperty.equalsIgnoreCase(Boolean.TRUE.toString()) ||
additionalProperty.equalsIgnoreCase(Boolean.FALSE.toString()))) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
} else {
Long longValue = Long.parseLong(additionalProperty);
if (longValue < 0) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
} catch (NumberFormatException e) {
String errMsg = "Application configuration values cannot have string values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
}
}
}
}
}
|
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AMDefaultKeyManagerImpl.java
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.apimgt.impl;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import feign.Feign;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.AccessTokenInfo;
import org.wso2.carbon.apimgt.api.model.AccessTokenRequest;
import org.wso2.carbon.apimgt.api.model.ApplicationConstants;
import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration;
import org.wso2.carbon.apimgt.api.model.OAuthAppRequest;
import org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.dto.ScopeDTO;
import org.wso2.carbon.apimgt.impl.dto.UserInfoDTO;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.kmclient.ApacheFeignHttpClient;
import org.wso2.carbon.apimgt.impl.kmclient.FormEncoder;
import org.wso2.carbon.apimgt.impl.kmclient.KMClientErrorDecoder;
import org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException;
import org.wso2.carbon.apimgt.impl.kmclient.model.AuthClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.Claim;
import org.wso2.carbon.apimgt.impl.kmclient.model.ClaimsList;
import org.wso2.carbon.apimgt.impl.kmclient.model.ClientInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.DCRClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectionClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.ScopeClient;
import org.wso2.carbon.apimgt.impl.kmclient.model.TenantHeaderInterceptor;
import org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo;
import org.wso2.carbon.apimgt.impl.kmclient.model.UserClient;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* This class holds the key manager implementation considering WSO2 as the identity provider
* This is the default key manager supported by API Manager.
*/
public class AMDefaultKeyManagerImpl extends AbstractKeyManager {
private static final Log log = LogFactory.getLog(AMDefaultKeyManagerImpl.class);
private static final String GRANT_TYPE_VALUE = "client_credentials";
private static final String ENCODE_CONSUMER_KEY = "encodeConsumerKey";
private DCRClient dcrClient;
private IntrospectionClient introspectionClient;
private AuthClient authClient;
private ScopeClient scopeClient;
private UserClient userClient;
@Override
public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws APIManagementException {
// OAuthApplications are created by calling to APIKeyMgtSubscriber Service
OAuthApplicationInfo oAuthApplicationInfo = oauthAppRequest.getOAuthApplicationInfo();
// Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created.
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.
OAUTH_CLIENT_USERNAME);
if (StringUtils.isEmpty(userId)) {
throw new APIManagementException("Missing user ID for OAuth application creation.");
}
String applicationName = oAuthApplicationInfo.getClientName();
String oauthClientName = oauthAppRequest.getOAuthApplicationInfo().getApplicationUUID();
String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
String domain = UserCoreUtil.extractDomainFromName(userId);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.
getTenantAwareUsername(userId)), oauthClientName, keyType);
} else {
throw new APIManagementException("Missing required information for OAuth application creation.");
}
if (log.isDebugEnabled()) {
log.debug("Trying to create OAuth application : " + oauthClientName + " for application: " + applicationName
+ " and key type: " + keyType);
}
String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
String[] tokenScopes = new String[1];
tokenScopes[0] = tokenScope;
ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, false);
ClientInfo createdClient;
try {
createdClient = dcrClient.createApplication(request);
buildDTOFromClientInfo(createdClient, oAuthApplicationInfo);
oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
oAuthApplicationInfo.setIsSaasApplication(false);
return oAuthApplicationInfo;
} catch (KeyManagerClientException e) {
handleException(
"Can not create OAuth application : " + oauthClientName + " for application: " + applicationName
+ " and key type: " + keyType, e);
return null;
}
}
/**
* Construct ClientInfo object for application create request
*
* @param info The OAuthApplicationInfo object
* @param oauthClientName The name of the OAuth application to be created
* @param isUpdate To determine whether the ClientInfo object is related to application update call
* @return constructed ClientInfo object
* @throws JSONException for errors in parsing the OAuthApplicationInfo json string
* @throws APIManagementException if an error occurs while constructing the ClientInfo object
*/
private ClientInfo createClientInfo(OAuthApplicationInfo info, String oauthClientName, boolean isUpdate)
throws JSONException, APIManagementException {
ClientInfo clientInfo = new ClientInfo();
JSONObject infoJson = new JSONObject(info.getJsonString());
String applicationOwner = (String) info.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
if (infoJson.has(ApplicationConstants.OAUTH_CLIENT_GRANT)) {
// this is done as there are instances where the grant string begins with a comma character.
String grantString = infoJson.getString(ApplicationConstants.OAUTH_CLIENT_GRANT);
if (grantString.startsWith(",")) {
grantString = grantString.substring(1);
}
String[] grantTypes = grantString.split(",");
clientInfo.setGrantTypes(Arrays.asList(grantTypes));
}
if (StringUtils.isNotEmpty(info.getCallBackURL())) {
String callBackURL = info.getCallBackURL();
String[] callbackURLs = callBackURL.trim().split("\\s*,\\s*");
clientInfo.setRedirectUris(Arrays.asList(callbackURLs));
}
clientInfo.setClientName(oauthClientName);
//todo: run tests by commenting the type
if (StringUtils.isEmpty(info.getTokenType())) {
clientInfo.setTokenType(APIConstants.TOKEN_TYPE_JWT);
} else {
clientInfo.setTokenType(info.getTokenType());
}
// Use a generated user as the app owner for cross tenant subscription scenarios, to avoid the tenant admin
// being exposed in the JWT token.
if (APIUtil.isCrossTenantSubscriptionsEnabled()
&& !tenantDomain.equals(MultitenantUtils.getTenantDomain(applicationOwner))) {
clientInfo.setApplication_owner(APIUtil.retrieveDefaultReservedUsername());
} else {
clientInfo.setApplication_owner(MultitenantUtils.getTenantAwareUsername(applicationOwner));
}
if (StringUtils.isNotEmpty(info.getClientId())) {
if (isUpdate) {
clientInfo.setClientId(info.getClientId());
} else {
clientInfo.setPresetClientId(info.getClientId());
}
}
if (StringUtils.isNotEmpty(info.getClientSecret())) {
if (isUpdate) {
clientInfo.setClientId(info.getClientSecret());
} else {
clientInfo.setPresetClientSecret(info.getClientSecret());
}
}
Object parameter = info.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
Map<String, Object> additionalProperties = new HashMap<>();
if (parameter instanceof String) {
additionalProperties = new Gson().fromJson((String) parameter, Map.class);
}
if (additionalProperties.containsKey(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
if (expiry < 0) {
throw new APIManagementException("Invalid application access token expiry time given for "
+ oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
}
clientInfo.setApplicationAccessTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
if (expiry < 0) {
throw new APIManagementException("Invalid user access token expiry time given for "
+ oauthClientName, ExceptionCodes.INVALID_APPLICATION_PROPERTIES);
}
clientInfo.setUserAccessTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
clientInfo.setRefreshTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME)) {
Object expiryTimeObject =
additionalProperties.get(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME);
if (expiryTimeObject instanceof String) {
if (!APIConstants.KeyManager.NOT_APPLICABLE_VALUE.equals(expiryTimeObject)) {
try {
long expiry = Long.parseLong((String) expiryTimeObject);
clientInfo.setIdTokenLifeTime(expiry);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_MANDATORY)) {
Object pkceMandatoryValue =
additionalProperties.get(APIConstants.KeyManager.PKCE_MANDATORY);
if (pkceMandatoryValue instanceof String) {
if (!APIConstants.KeyManager.PKCE_MANDATORY.equals(pkceMandatoryValue)) {
try {
Boolean pkceMandatory = Boolean.parseBoolean((String) pkceMandatoryValue);
clientInfo.setPkceMandatory(pkceMandatory);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN)) {
Object pkceSupportPlainValue =
additionalProperties.get(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN);
if (pkceSupportPlainValue instanceof String) {
if (!APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(pkceSupportPlainValue)) {
try {
Boolean pkceSupportPlain = Boolean.parseBoolean((String) pkceSupportPlainValue);
clientInfo.setPkceSupportPlain(pkceSupportPlain);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
if (additionalProperties.containsKey(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS)) {
Object bypassClientCredentialsValue =
additionalProperties.get(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS);
if (bypassClientCredentialsValue instanceof String) {
if (!APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(bypassClientCredentialsValue)) {
try {
Boolean bypassClientCredentials = Boolean.parseBoolean((String) bypassClientCredentialsValue);
clientInfo.setBypassClientCredentials(bypassClientCredentials);
} catch (NumberFormatException e) {
// No need to throw as its due to not a number sent.
}
}
}
}
// Set the display name of the application. This name would appear in the consent page of the app.
clientInfo.setApplicationDisplayName(info.getClientName());
return clientInfo;
}
@Override
public OAuthApplicationInfo updateApplication(OAuthAppRequest appInfoDTO) throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
String applicationName = oAuthApplicationInfo.getClientName();
String oauthClientName = oAuthApplicationInfo.getApplicationUUID();
String keyType = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.APP_KEY_TYPE);
// First we attempt to get the tenant domain from the userID and if it is not possible, we fetch it
// from the ThreadLocalCarbonContext
if (StringUtils.isNotEmpty(applicationName) && StringUtils.isNotEmpty(keyType)) {
// Replace the domain name separator with an underscore for secondary user stores
String domain = UserCoreUtil.extractDomainFromName(userId);
if (domain != null && !domain.isEmpty() && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equals(domain)) {
userId = userId.replace(UserCoreConstants.DOMAIN_SEPARATOR, "_");
}
// Construct the application name subsequent to replacing email domain separator
oauthClientName = String.format("%s_%s_%s", APIUtil.replaceEmailDomain(MultitenantUtils.
getTenantAwareUsername(userId)), oauthClientName, keyType);
} else {
throw new APIManagementException("Missing required information for OAuth application update.");
}
log.debug("Updating OAuth Client with ID : " + oAuthApplicationInfo.getClientId());
if (log.isDebugEnabled() && oAuthApplicationInfo.getCallBackURL() != null) {
log.debug("CallBackURL : " + oAuthApplicationInfo.getCallBackURL());
}
if (log.isDebugEnabled() && applicationName != null) {
log.debug("Client Name : " + oauthClientName);
}
ClientInfo request = createClientInfo(oAuthApplicationInfo, oauthClientName, true);
ClientInfo createdClient;
try {
createdClient = dcrClient.updateApplication(oAuthApplicationInfo.getClientId(), request);
return buildDTOFromClientInfo(createdClient, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
handleException("Error occurred while updating OAuth Client : ", e);
return null;
}
}
@Override
public OAuthApplicationInfo updateApplicationOwner(OAuthAppRequest appInfoDTO, String owner)
throws APIManagementException {
OAuthApplicationInfo oAuthApplicationInfo = appInfoDTO.getOAuthApplicationInfo();
log.debug("Updating Application Owner : " + oAuthApplicationInfo.getClientId());
ClientInfo updatedClient;
try {
updatedClient = dcrClient.updateApplicationOwner(owner, oAuthApplicationInfo.getClientId());
return buildDTOFromClientInfo(updatedClient, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
handleException("Error occurred while updating OAuth Client : ", e);
return null;
}
}
@Override
public void deleteApplication(String consumerKey) throws APIManagementException {
if (log.isDebugEnabled()) {
log.debug("Trying to delete OAuth application for consumer key :" + consumerKey);
}
try {
dcrClient.deleteApplication(consumerKey);
} catch (KeyManagerClientException e) {
handleException("Cannot remove service provider for the given consumer key : " + consumerKey, e);
}
}
@Override
public OAuthApplicationInfo retrieveApplication(String consumerKey) throws APIManagementException {
if (log.isDebugEnabled()) {
log.debug("Trying to retrieve OAuth application for consumer key :" + consumerKey);
}
try {
ClientInfo clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(
consumerKey.getBytes(StandardCharsets.UTF_8)));
return buildDTOFromClientInfo(clientInfo, new OAuthApplicationInfo());
} catch (KeyManagerClientException e) {
if (e.getStatusCode() == 404) {
return null;
}
handleException("Cannot retrieve service provider for the given consumer key : " + consumerKey, e);
return null;
}
}
@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {
AccessTokenInfo tokenInfo;
if (tokenRequest == null) {
log.warn("No information available to generate Token.");
return null;
}
//We do not revoke the previously obtained token anymore since we do not possess the access token.
// When validity time set to a negative value, a token is considered never to expire.
if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
// Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
tokenRequest.setValidityPeriod(-2L);
}
//Generate New Access Token
String scopes = String.join(" ", tokenRequest.getScope());
TokenInfo tokenResponse;
try {
String credentials = tokenRequest.getClientId() + ':' + tokenRequest.getClientSecret();
String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
tokenResponse = authClient.generate(authToken, GRANT_TYPE_VALUE, scopes);
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred while calling token endpoint - " + e.getReason(), e);
}
tokenInfo = new AccessTokenInfo();
if (StringUtils.isNotEmpty(tokenResponse.getScope())) {
tokenInfo.setScope(tokenResponse.getScope().split(" "));
} else {
tokenInfo.setScope(new String[0]);
}
tokenInfo.setAccessToken(tokenResponse.getToken());
tokenInfo.setValidityPeriod(tokenResponse.getExpiry());
return tokenInfo;
}
@Override
public String getNewApplicationConsumerSecret(AccessTokenRequest tokenRequest) throws APIManagementException {
ClientInfo updatedClient;
try {
updatedClient = dcrClient.updateApplicationSecret(tokenRequest.getClientId());
return updatedClient.getClientSecret();
} catch (KeyManagerClientException e) {
handleException("Error while generating new consumer secret", e);
}
return null;
}
@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
AccessTokenInfo tokenInfo = new AccessTokenInfo();
try {
IntrospectInfo introspectInfo = introspectionClient.introspect(accessToken);
tokenInfo.setAccessToken(accessToken);
boolean isActive = introspectInfo.isActive();
if (!isActive) {
tokenInfo.setTokenValid(false);
tokenInfo.setErrorcode(APIConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
return tokenInfo;
}
tokenInfo.setTokenValid(true);
if (introspectInfo.getIat() > 0 && introspectInfo.getExpiry() > 0) {
if (introspectInfo.getExpiry() != Long.MAX_VALUE) {
long validityPeriod = introspectInfo.getExpiry() - introspectInfo.getIat();
tokenInfo.setValidityPeriod(validityPeriod * 1000L);
} else {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
}
tokenInfo.setIssuedTime(introspectInfo.getIat() * 1000L);
}
if (StringUtils.isNotEmpty(introspectInfo.getScope())) {
String[] scopes = introspectInfo.getScope().split(" ");
tokenInfo.setScope(scopes);
}
tokenInfo.setConsumerKey(introspectInfo.getClientId());
String username = introspectInfo.getUsername();
if (!StringUtils.isEmpty(username)) {
tokenInfo.setEndUserName(username);
}
return tokenInfo;
} catch (KeyManagerClientException e) {
throw new APIManagementException("Error occurred in token introspection!", e);
}
}
@Override
public KeyManagerConfiguration getKeyManagerConfiguration() throws APIManagementException {
return configuration;
}
/**
* This method will create a new record at CLIENT_INFO table by given OauthAppRequest.
*
* @param appInfoRequest oAuth application properties will contain in this object
* @return OAuthApplicationInfo with created oAuth application details.
* @throws org.wso2.carbon.apimgt.api.APIManagementException
*/
@Override
public OAuthApplicationInfo mapOAuthApplication(OAuthAppRequest appInfoRequest)
throws APIManagementException {
//initiate OAuthApplicationInfo
OAuthApplicationInfo oAuthApplicationInfo = appInfoRequest.getOAuthApplicationInfo();
String consumerKey = oAuthApplicationInfo.getClientId();
String tokenScope = (String) oAuthApplicationInfo.getParameter("tokenScope");
String[] tokenScopes = new String[1];
tokenScopes[0] = tokenScope;
String clientSecret = (String) oAuthApplicationInfo.getParameter("client_secret");
//for the first time we set default time period.
oAuthApplicationInfo.addParameter(ApplicationConstants.VALIDITY_PERIOD,
getConfigurationParamValue(APIConstants.IDENTITY_OAUTH2_FIELD_VALIDITY_PERIOD));
String userId = (String) oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_USERNAME);
//check whether given consumer key and secret match or not. If it does not match throw an exception.
ClientInfo clientInfo;
try {
clientInfo = dcrClient.getApplication(Base64.getUrlEncoder().encodeToString(
consumerKey.getBytes(StandardCharsets.UTF_8)));
buildDTOFromClientInfo(clientInfo, oAuthApplicationInfo);
} catch (KeyManagerClientException e) {
handleException("Some thing went wrong while getting OAuth application for given consumer key " +
oAuthApplicationInfo.getClientId(), e);
}
if (!clientSecret.equals(oAuthApplicationInfo.getClientSecret())) {
throw new APIManagementException("The secret key is wrong for the given consumer key " + consumerKey);
}
oAuthApplicationInfo.addParameter("tokenScope", tokenScopes);
oAuthApplicationInfo.setIsSaasApplication(false);
if (log.isDebugEnabled()) {
log.debug("Creating semi-manual application for consumer id : " + oAuthApplicationInfo.getClientId());
}
return oAuthApplicationInfo;
}
/**
* Builds an OAuthApplicationInfo object using the ClientInfo response
*
* @param appResponse ClientInfo response object
* @param oAuthApplicationInfo original OAuthApplicationInfo object
* @return OAuthApplicationInfo object with response information added
*/
private OAuthApplicationInfo buildDTOFromClientInfo(ClientInfo appResponse,
OAuthApplicationInfo oAuthApplicationInfo) {
oAuthApplicationInfo.setClientName(appResponse.getClientName());
oAuthApplicationInfo.setClientId(appResponse.getClientId());
if (appResponse.getRedirectUris() != null) {
oAuthApplicationInfo.setCallBackURL(String.join(",", appResponse.getRedirectUris()));
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS,
String.join(",", appResponse.getRedirectUris()));
}
oAuthApplicationInfo.setClientSecret(appResponse.getClientSecret());
if (appResponse.getGrantTypes() != null) {
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT,
String.join(" ", appResponse.getGrantTypes()));
} else if (oAuthApplicationInfo.getParameter(ApplicationConstants.OAUTH_CLIENT_GRANT) instanceof String) {
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_GRANT, ((String) oAuthApplicationInfo.
getParameter(ApplicationConstants.OAUTH_CLIENT_GRANT)).replace(",", " "));
}
oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_CLIENT_NAME, appResponse.getClientName());
Map<String, Object> additionalProperties = new HashMap<>();
additionalProperties.put(APIConstants.KeyManager.APPLICATION_ACCESS_TOKEN_EXPIRY_TIME,
appResponse.getApplicationAccessTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.USER_ACCESS_TOKEN_EXPIRY_TIME,
appResponse.getUserAccessTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.REFRESH_TOKEN_EXPIRY_TIME,
appResponse.getRefreshTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.ID_TOKEN_EXPIRY_TIME, appResponse.getIdTokenLifeTime());
additionalProperties.put(APIConstants.KeyManager.PKCE_MANDATORY, appResponse.getPkceMandatory());
additionalProperties.put(APIConstants.KeyManager.PKCE_SUPPORT_PLAIN, appResponse.getPkceSupportPlain());
additionalProperties.put(APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS,
appResponse.getBypassClientCredentials());
oAuthApplicationInfo.addParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES, additionalProperties);
return oAuthApplicationInfo;
}
@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {
this.configuration = configuration;
String username = (String) configuration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
String password = (String) configuration.getParameter(APIConstants.KEY_MANAGER_PASSWORD);
String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);
String dcrEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
} else {
dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat
(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_DCR_ENDPOINT);
}
String tokenEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
} else {
tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
"/oauth2/token");
}
addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
String revokeEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
} else {
revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(
"/oauth2/revoke");
}
String scopeEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
} else {
scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim())
.concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
}
String introspectionEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
} else {
introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
}
String userInfoEndpoint;
if (configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT) != null) {
userInfoEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT);
} else {
userInfoEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0]
.concat(getTenantAwareContext().trim()).concat
(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_USERINFO_ENDPOINT);
}
dcrClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(dcrEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(DCRClient.class, dcrEndpoint);
authClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(tokenEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.errorDecoder(new KMClientErrorDecoder())
.encoder(new FormEncoder())
.target(AuthClient.class, tokenEndpoint);
introspectionClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(introspectionEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.encoder(new FormEncoder())
.target(IntrospectionClient.class, introspectionEndpoint);
scopeClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(scopeEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(ScopeClient.class, scopeEndpoint);
userClient = Feign.builder()
.client(new ApacheFeignHttpClient(APIUtil.getHttpClient(userInfoEndpoint)))
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger())
.requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.requestInterceptor(new TenantHeaderInterceptor(tenantDomain))
.errorDecoder(new KMClientErrorDecoder())
.target(UserClient.class, userInfoEndpoint);
}
@Override
public boolean registerNewResource(API api, Map resourceAttributes) throws APIManagementException {
// //Register new resource means create new API with given Scopes.
//todo commented below code because of blocker due to API publish fail. need to find a better way of doing this
// ApiMgtDAO apiMgtDAO = new ApiMgtDAO();
// apiMgtDAO.addAPI(api, CarbonContext.getThreadLocalCarbonContext().getTenantId());
return true;
}
@Override
public Map getResourceByApiId(String apiId) throws APIManagementException {
return null;
}
@Override
public boolean updateRegisteredResource(API api, Map resourceAttributes) throws APIManagementException {
return false;
}
@Override
public void deleteRegisteredResourceByAPIId(String apiID) throws APIManagementException {
}
@Override
public void deleteMappedApplication(String consumerKey) throws APIManagementException {
}
@Override
public Set<String> getActiveTokensByConsumerKey(String consumerKey) throws APIManagementException {
return new HashSet<>();
}
/**
* Returns the access token information of the provided consumer key.
*
* @param consumerKey The consumer key.
* @return AccessTokenInfo The access token information.
* @throws APIManagementException
*/
@Override
public AccessTokenInfo getAccessTokenByConsumerKey(String consumerKey) throws APIManagementException {
return new AccessTokenInfo();
}
@Override
public Map<String, Set<Scope>> getScopesForAPIS(String apiIdsString)
throws APIManagementException {
return null;
}
/**
* This method will be used to register a Scope in the authorization server.
*
* @param scope Scope to register
* @throws APIManagementException if there is an error while registering a new scope.
*/
@Override
public void registerScope(Scope scope) throws APIManagementException {
String scopeKey = scope.getKey();
ScopeDTO scopeDTO = new ScopeDTO();
scopeDTO.setName(scopeKey);
scopeDTO.setDisplayName(scope.getName());
scopeDTO.setDescription(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) {
scopeDTO.setBindings(Arrays.asList(scope.getRoles().trim().split(",")));
}
try (Response response = scopeClient.registerScope(scopeDTO)) {
if (response.status() != HttpStatus.SC_CREATED) {
String responseString = readHttpResponseAsString(response.body());
throw new APIManagementException("Error occurred while registering scope: " + scopeKey + ". Error" +
" Status: " + response.status() + " . Error Response: " + responseString);
}
} catch (KeyManagerClientException e) {
handleException("Cannot register scope : " + scopeKey, e);
}
}
/**
* Read response body for HTTPResponse as a string.
*
* @param httpResponse HTTPResponse
* @return Response Body String
* @throws APIManagementException If an error occurs while reading the response
*/
protected String readHttpResponseAsString(Response.Body httpResponse) throws APIManagementException {
try (InputStream inputStream = httpResponse.asInputStream()) {
return IOUtils.toString(inputStream);
} catch (IOException e) {
String errorMessage = "Error occurred while reading response body as string";
throw new APIManagementException(errorMessage, e);
}
}
/**
* This method will be used to retrieve details of a Scope in the authorization server.
*
* @param name Scope Name to retrieve
* @return Scope object
* @throws APIManagementException if an error while retrieving scope
*/
@Override
public Scope getScopeByName(String name) throws APIManagementException {
ScopeDTO scopeDTO = null;
try {
scopeDTO = scopeClient.getScopeByName(name);
} catch (KeyManagerClientException ex) {
handleException("Cannot read scope : " + name, ex);
}
return fromDTOToScope(scopeDTO);
}
/**
* Get Scope object from ScopeDTO response received from authorization server.
*
* @param scopeDTO ScopeDTO response
* @return Scope model object
*/
private Scope fromDTOToScope(ScopeDTO scopeDTO) {
Scope scope = new Scope();
scope.setName(scopeDTO.getDisplayName());
scope.setKey(scopeDTO.getName());
scope.setDescription(scopeDTO.getDescription());
scope.setRoles((scopeDTO.getBindings() != null && !scopeDTO.getBindings().isEmpty())
? String.join(",", scopeDTO.getBindings()) : StringUtils.EMPTY);
return scope;
}
/**
* Get Scope object list from ScopeDTO List response received from authorization server.
*
* @param scopeDTOS Scope DTO Array
* @return Scope Object to Scope Name Mappings
*/
private Map<String, Scope> fromDTOListToScopeListMapping(ScopeDTO[] scopeDTOS) {
Map<String, Scope> scopeListMapping = new HashMap<>();
for (ScopeDTO scopeDTO : scopeDTOS) {
scopeListMapping.put(scopeDTO.getName(), fromDTOToScope(scopeDTO));
}
return scopeListMapping;
}
/**
* This method will be used to retrieve all the scopes available in the authorization server for the given tenant
* domain.
*
* @return Mapping of Scope object to scope key
* @throws APIManagementException if an error occurs while getting scopes list
*/
@Override
public Map<String, Scope> getAllScopes() throws APIManagementException {
ScopeDTO[] scopes = new ScopeDTO[0];
try {
scopes = scopeClient.getScopes();
} catch (KeyManagerClientException ex) {
handleException("Error while retrieving scopes", ex);
}
return fromDTOListToScopeListMapping(scopes);
}
/**
* This method will be used to attach a Scope in the authorization server to a API resource.
*
* @param api API
* @param uriTemplates URITemplate set with attached scopes
* @throws APIManagementException if an error occurs while attaching scope to resource
*/
@Override
public void attachResourceScopes(API api, Set<URITemplate> uriTemplates)
throws APIManagementException {
//TODO: Nothing to do here
}
/**
* This method will be used to update the local scopes and resource to scope attachments of an API in the
* authorization server.
*
* @param api API
* @param oldLocalScopeKeys Old local scopes of the API before update (excluding the versioned local scopes
* @param newLocalScopes New local scopes of the API after update
* @param oldURITemplates Old URI templates of the API before update
* @param newURITemplates New URI templates of the API after update
* @throws APIManagementException if fails to update resources scopes
*/
@Override
public void updateResourceScopes(API api, Set<String> oldLocalScopeKeys, Set<Scope> newLocalScopes,
Set<URITemplate> oldURITemplates, Set<URITemplate> newURITemplates)
throws APIManagementException {
detachResourceScopes(api, oldURITemplates);
// remove the old local scopes from the KM
for (String oldScope : oldLocalScopeKeys) {
deleteScope(oldScope);
}
//Register scopes
for (Scope scope : newLocalScopes) {
String scopeKey = scope.getKey();
// Check if key already registered in KM. Scope Key may be already registered for a different version.
if (!isScopeExists(scopeKey)) {
//register scope in KM
registerScope(scope);
} else {
if (log.isDebugEnabled()) {
log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope.");
}
}
}
attachResourceScopes(api, newURITemplates);
}
/**
* This method will be used to detach the resource scopes of an API and delete the local scopes of that API from
* the authorization server.
*
* @param api API API
* @param uriTemplates URITemplate Set with attach scopes to detach
* @throws APIManagementException if an error occurs while detaching resource scopes of the API.
*/
@Override
public void detachResourceScopes(API api, Set<URITemplate> uriTemplates)
throws APIManagementException {
//TODO: Nothing to do here
}
/**
* This method will be used to delete a Scope in the authorization server.
*
* @param scopeName Scope name
* @throws APIManagementException if an error occurs while deleting the scope
*/
@Override
public void deleteScope(String scopeName) throws APIManagementException {
try {
Response response = scopeClient.deleteScope(scopeName);
if (response.status() != HttpStatus.SC_OK) {
String responseString = readHttpResponseAsString(response.body());
String errorMessage =
"Error occurred while deleting scope: " + scopeName + ". Error Status: " + response.status() +
" . Error Response: " + responseString;
throw new APIManagementException(errorMessage);
}
} catch (KeyManagerClientException ex) {
handleException("Error occurred while deleting scope", ex);
}
}
/**
* This method will be used to update a Scope in the authorization server.
*
* @param scope Scope object
* @throws APIManagementException if an error occurs while updating the scope
*/
@Override
public void updateScope(Scope scope) throws APIManagementException {
String scopeKey = scope.getKey();
try {
ScopeDTO scopeDTO = new ScopeDTO();
scopeDTO.setDisplayName(scope.getName());
scopeDTO.setDescription(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) {
scopeDTO.setBindings(Arrays.asList(scope.getRoles().trim().split(",")));
}
scopeClient.updateScope(scopeDTO, scope.getKey());
} catch (KeyManagerClientException e) {
String errorMessage = "Error occurred while updating scope: " + scopeKey;
handleException(errorMessage, e);
}
}
/**
* This method will be used to check whether the a Scope exists for the given scope name in the authorization
* server.
*
* @param scopeName Scope Name
* @return whether scope exists or not
* @throws APIManagementException if an error occurs while checking the existence of the scope
*/
@Override
public boolean isScopeExists(String scopeName) throws APIManagementException {
try (Response response = scopeClient.isScopeExist(scopeName)) {
if (response.status() == HttpStatus.SC_OK) {
return true;
} else if (response.status() != HttpStatus.SC_NOT_FOUND) {
String responseString = readHttpResponseAsString(response.body());
String errorMessage = "Error occurred while checking existence of scope: " + scopeName + ". Error " +
"Status: " + response.status() + " . Error Response: " + responseString;
throw new APIManagementException(errorMessage);
}
} catch (KeyManagerClientException e) {
handleException("Error while check scope exist", e);
}
return false;
}
/**
* This method will be used to validate the scope set provided and populate the additional parameters
* (description and bindings) for each Scope object.
*
* @param scopes Scope set to validate
* @throws APIManagementException if an error occurs while validating and populating
*/
@Override
public void validateScopes(Set<Scope> scopes) throws APIManagementException {
for (Scope scope : scopes) {
Scope sharedScope = getScopeByName(scope.getKey());
scope.setName(sharedScope.getName());
scope.setDescription(sharedScope.getDescription());
scope.setRoles(sharedScope.getRoles());
}
}
@Override
public String getType() {
return APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE;
}
/**
* Return the value of the provided configuration parameter.
*
* @param parameter Parameter name
* @return Parameter value
*/
protected String getConfigurationParamValue(String parameter) {
return (String) configuration.getParameter(parameter);
}
/**
* Check whether Token partitioning is enabled.
*
* @return true/false
*/
protected boolean checkAccessTokenPartitioningEnabled() {
return APIUtil.checkAccessTokenPartitioningEnabled();
}
/**
* Check whether user name assertion is enabled.
*
* @return true/false
*/
protected boolean checkUserNameAssertionEnabled() {
return APIUtil.checkUserNameAssertionEnabled();
}
private String getTenantAwareContext() {
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
return "/t/".concat(tenantDomain);
}
return "";
}
private void addKeyManagerConfigsAsSystemProperties(String serviceUrl) {
URL keyManagerURL;
try {
keyManagerURL = new URL(serviceUrl);
String hostname = keyManagerURL.getHost();
int port = keyManagerURL.getPort();
if (port == -1) {
if (APIConstants.HTTPS_PROTOCOL.equals(keyManagerURL.getProtocol())) {
port = APIConstants.HTTPS_PROTOCOL_PORT;
} else {
port = APIConstants.HTTP_PROTOCOL_PORT;
}
}
System.setProperty(APIConstants.KEYMANAGER_PORT, String.valueOf(port));
if (hostname.equals(System.getProperty(APIConstants.CARBON_LOCALIP))) {
System.setProperty(APIConstants.KEYMANAGER_HOSTNAME, "localhost");
} else {
System.setProperty(APIConstants.KEYMANAGER_HOSTNAME, hostname);
}
//Since this is the server startup.Ignore the exceptions,invoked at the server startup
} catch (MalformedURLException e) {
log.error("Exception While resolving KeyManager Server URL or Port " + e.getMessage(), e);
}
}
@Override
public Map<String, String> getUserClaims(String username, Map<String, Object> properties)
throws APIManagementException {
Map<String, String> map = new HashMap<String, String>();
String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
UserInfoDTO userinfo = new UserInfoDTO();
userinfo.setUsername(tenantAwareUserName);
if (tenantAwareUserName.contains(CarbonConstants.DOMAIN_SEPARATOR)) {
userinfo.setDomain(tenantAwareUserName.split(CarbonConstants.DOMAIN_SEPARATOR)[0]);
}
if (properties.containsKey(APIConstants.KeyManager.ACCESS_TOKEN)) {
userinfo.setAccessToken(properties.get(APIConstants.KeyManager.ACCESS_TOKEN).toString());
}
if (properties.containsKey(APIConstants.KeyManager.CLAIM_DIALECT)) {
userinfo.setDialectURI(properties.get(APIConstants.KeyManager.CLAIM_DIALECT).toString());
}
try {
ClaimsList claims = userClient.generateClaims(userinfo);
if (claims != null && claims.getList() != null) {
for (Claim claim : claims.getList()) {
map.put(claim.getUri(), claim.getValue());
}
}
} catch (KeyManagerClientException e) {
handleException("Error while getting user info", e);
}
return map;
}
@Override
protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo)
throws APIManagementException {
super.validateOAuthAppCreationProperties(oAuthApplicationInfo);
String type = getType();
KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance()
.getKeyManagerConnectorConfiguration(type);
if (keyManagerConnectorConfiguration != null) {
Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
if (additionalProperties != null) {
JsonObject additionalPropertiesJson = (JsonObject) new JsonParser()
.parse((String) additionalProperties);
for (Map.Entry<String, JsonElement> entry : additionalPropertiesJson.entrySet()) {
String additionalProperty = entry.getValue().getAsString();
if (StringUtils.isNotBlank(additionalProperty) && !StringUtils
.equals(additionalProperty, APIConstants.KeyManager.NOT_APPLICABLE_VALUE)) {
try {
if (APIConstants.KeyManager.PKCE_MANDATORY.equals(entry.getKey()) ||
APIConstants.KeyManager.PKCE_SUPPORT_PLAIN.equals(entry.getKey()) ||
APIConstants.KeyManager.BYPASS_CLIENT_CREDENTIALS.equals(entry.getKey())) {
if (!(additionalProperty.equalsIgnoreCase(Boolean.TRUE.toString()) ||
additionalProperty.equalsIgnoreCase(Boolean.FALSE.toString()))) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
} else {
Long longValue = Long.parseLong(additionalProperty);
if (longValue < 0) {
String errMsg = "Application configuration values cannot have negative values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
} catch (NumberFormatException e) {
String errMsg = "Application configuration values cannot have string values.";
throw new APIManagementException(errMsg, ExceptionCodes
.from(ExceptionCodes.INVALID_APPLICATION_ADDITIONAL_PROPERTIES, errMsg));
}
}
}
}
}
}
}
|
Change to Base64 URL encoder
|
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/AMDefaultKeyManagerImpl.java
|
Change to Base64 URL encoder
|
|
Java
|
apache-2.0
|
87768fb89e2b17c421959a646f6d1f9195c9517f
| 0
|
jeorme/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,jerome79/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics
|
/**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.fixedincome;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import javax.time.calendar.DayOfWeek;
import javax.time.calendar.LocalDate;
import javax.time.calendar.ZonedDateTime;
import org.testng.annotations.Test;
import com.opengamma.core.holiday.Holiday;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.holiday.HolidayType;
import com.opengamma.core.region.RegionSource;
import com.opengamma.financial.analytics.bond.BondSecurityToBondDefinitionConverter;
import com.opengamma.financial.analytics.conversion.BondSecurityConverter;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.convention.DefaultConventionBundleSource;
import com.opengamma.financial.convention.InMemoryConventionBundleMaster;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.financial.convention.frequency.SimpleFrequency;
import com.opengamma.financial.convention.frequency.SimpleFrequencyFactory;
import com.opengamma.financial.convention.yield.YieldConventionFactory;
import com.opengamma.financial.instrument.bond.BondDefinition;
import com.opengamma.financial.security.bond.BondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.master.region.impl.MasterRegionSource;
import com.opengamma.master.region.impl.RegionFileReader;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.DateUtil;
import com.opengamma.util.time.Expiry;
/**
*
*/
public class BondSecurityToBondDefinitionConverterTest {
private static final HolidaySource HOLIDAY_SOURCE = new MyHolidaySource();
private static final ConventionBundleSource CONVENTION_SOURCE = new DefaultConventionBundleSource(
new InMemoryConventionBundleMaster());
private static final RegionSource REGION_SOURCE = new MasterRegionSource(RegionFileReader.createPopulated().getRegionMaster());
private static final BondSecurityToBondDefinitionConverter CONVERTER = new BondSecurityToBondDefinitionConverter(
HOLIDAY_SOURCE, CONVENTION_SOURCE);
private static final ZonedDateTime FIRST_ACCRUAL_DATE = DateUtil.getUTCDate(2007, 9, 30);
private static final ZonedDateTime SETTLEMENT_DATE = DateUtil.getUTCDate(2007, 10, 2);
private static final ZonedDateTime FIRST_COUPON_DATE = DateUtil.getUTCDate(2008, 3, 31);
private static final ZonedDateTime LAST_TRADE_DATE = DateUtil.getUTCDate(2008, 9, 30);
private static final double COUPON = 4.0;
private static final BondSecurityConverter NEW_CONVERTER = new BondSecurityConverter(HOLIDAY_SOURCE,
CONVENTION_SOURCE, REGION_SOURCE);
private static final GovernmentBondSecurity BOND = new GovernmentBondSecurity("US", "Government", "US", "Treasury", Currency.USD,
YieldConventionFactory.INSTANCE.getYieldConvention("US Treasury equivalent"), new Expiry(LAST_TRADE_DATE), "", COUPON,
SimpleFrequencyFactory.INSTANCE.getFrequency(SimpleFrequency.SEMI_ANNUAL_NAME), DayCountFactory.INSTANCE.getDayCount("Actual/Actual ICMA"), FIRST_ACCRUAL_DATE,
SETTLEMENT_DATE, FIRST_COUPON_DATE, 100, 100000000, 5000, 1000, 100, 100);
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullHolidaySource() {
new BondSecurityToBondDefinitionConverter(null, CONVENTION_SOURCE);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullConventionSource() {
new BondSecurityToBondDefinitionConverter(HOLIDAY_SOURCE, null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity1() {
CONVERTER.getBond((BondSecurity) null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity2() {
CONVERTER.getBond((BondSecurity) null, false);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity3() {
CONVERTER.getBond((BondSecurity) null, false, CONVENTION_SOURCE.getConventionBundle(Identifier.of(
InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, "USD_TREASURY_BOND_CONVENTION")));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullConvention() {
CONVERTER.getBond(BOND, false, null);
}
@Test
public void test() {
final BondDefinition definition = CONVERTER.getBond(BOND, true);
assertArrayEquals(definition.getNominalDates(), new LocalDate[] {FIRST_ACCRUAL_DATE.toLocalDate(),
FIRST_COUPON_DATE.toLocalDate(), LAST_TRADE_DATE.toLocalDate()});
assertEquals(definition.getSettlementDates()[0], SETTLEMENT_DATE.toLocalDate());
}
@Test
public void testNew() {
// final BondDefinition definition = NEW_CONVERTER.visitGovernmentBondSecurity(BOND);
// assertArrayEquals(definition.getNominalDates(), new LocalDate[] {FIRST_ACCRUAL_DATE.toLocalDate(),
// FIRST_COUPON_DATE.toLocalDate(), LAST_TRADE_DATE.toLocalDate()});
// assertEquals(definition.getSettlementDates()[0], SETTLEMENT_DATE.toLocalDate());
}
private static class MyHolidaySource implements HolidaySource {
@Override
public boolean isHoliday(final LocalDate dateToCheck, final Currency currency) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public boolean isHoliday(final LocalDate dateToCheck, final HolidayType holidayType,
final IdentifierBundle regionOrExchangeIds) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public boolean isHoliday(final LocalDate dateToCheck, final HolidayType holidayType,
final Identifier regionOrExchangeId) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public Holiday getHoliday(final UniqueIdentifier uid) {
return null;
}
}
}
|
projects/OG-Financial/tests/unit/com/opengamma/financial/analytics/fixedincome/BondSecurityToBondDefinitionConverterTest.java
|
/**
* Copyright (C) 2009 - 2010 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.fixedincome;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
import javax.time.calendar.DayOfWeek;
import javax.time.calendar.LocalDate;
import javax.time.calendar.ZonedDateTime;
import org.testng.annotations.Test;
import com.opengamma.core.holiday.Holiday;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.core.holiday.HolidayType;
import com.opengamma.core.region.RegionSource;
import com.opengamma.financial.analytics.bond.BondSecurityConverter;
import com.opengamma.financial.analytics.bond.BondSecurityToBondDefinitionConverter;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.convention.DefaultConventionBundleSource;
import com.opengamma.financial.convention.InMemoryConventionBundleMaster;
import com.opengamma.financial.convention.daycount.DayCountFactory;
import com.opengamma.financial.convention.frequency.SimpleFrequency;
import com.opengamma.financial.convention.frequency.SimpleFrequencyFactory;
import com.opengamma.financial.convention.yield.YieldConventionFactory;
import com.opengamma.financial.instrument.bond.BondDefinition;
import com.opengamma.financial.security.bond.BondSecurity;
import com.opengamma.financial.security.bond.GovernmentBondSecurity;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.master.region.impl.MasterRegionSource;
import com.opengamma.master.region.impl.RegionFileReader;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.DateUtil;
import com.opengamma.util.time.Expiry;
/**
*
*/
public class BondSecurityToBondDefinitionConverterTest {
private static final HolidaySource HOLIDAY_SOURCE = new MyHolidaySource();
private static final ConventionBundleSource CONVENTION_SOURCE = new DefaultConventionBundleSource(
new InMemoryConventionBundleMaster());
private static final RegionSource REGION_SOURCE = new MasterRegionSource(RegionFileReader.createPopulated().getRegionMaster());
private static final BondSecurityToBondDefinitionConverter CONVERTER = new BondSecurityToBondDefinitionConverter(
HOLIDAY_SOURCE, CONVENTION_SOURCE);
private static final ZonedDateTime FIRST_ACCRUAL_DATE = DateUtil.getUTCDate(2007, 9, 30);
private static final ZonedDateTime SETTLEMENT_DATE = DateUtil.getUTCDate(2007, 10, 2);
private static final ZonedDateTime FIRST_COUPON_DATE = DateUtil.getUTCDate(2008, 3, 31);
private static final ZonedDateTime LAST_TRADE_DATE = DateUtil.getUTCDate(2008, 9, 30);
private static final double COUPON = 4.0;
private static final BondSecurityConverter NEW_CONVERTER = new BondSecurityConverter(HOLIDAY_SOURCE,
CONVENTION_SOURCE, REGION_SOURCE);
private static final GovernmentBondSecurity BOND = new GovernmentBondSecurity("US", "Government", "US", "Treasury", Currency.USD,
YieldConventionFactory.INSTANCE.getYieldConvention("US Treasury equivalent"), new Expiry(LAST_TRADE_DATE), "", COUPON,
SimpleFrequencyFactory.INSTANCE.getFrequency(SimpleFrequency.SEMI_ANNUAL_NAME), DayCountFactory.INSTANCE.getDayCount("Actual/Actual ICMA"), FIRST_ACCRUAL_DATE,
SETTLEMENT_DATE, FIRST_COUPON_DATE, 100, 100000000, 5000, 1000, 100, 100);
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullHolidaySource() {
new BondSecurityToBondDefinitionConverter(null, CONVENTION_SOURCE);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullConventionSource() {
new BondSecurityToBondDefinitionConverter(HOLIDAY_SOURCE, null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity1() {
CONVERTER.getBond((BondSecurity) null);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity2() {
CONVERTER.getBond((BondSecurity) null, false);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullSecurity3() {
CONVERTER.getBond((BondSecurity) null, false, CONVENTION_SOURCE.getConventionBundle(Identifier.of(
InMemoryConventionBundleMaster.SIMPLE_NAME_SCHEME, "USD_TREASURY_BOND_CONVENTION")));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullConvention() {
CONVERTER.getBond(BOND, false, null);
}
@Test
public void test() {
final BondDefinition definition = CONVERTER.getBond(BOND, true);
assertArrayEquals(definition.getNominalDates(), new LocalDate[] {FIRST_ACCRUAL_DATE.toLocalDate(),
FIRST_COUPON_DATE.toLocalDate(), LAST_TRADE_DATE.toLocalDate()});
assertEquals(definition.getSettlementDates()[0], SETTLEMENT_DATE.toLocalDate());
}
@Test
public void testNew() {
// final BondDefinition definition = NEW_CONVERTER.visitGovernmentBondSecurity(BOND);
// assertArrayEquals(definition.getNominalDates(), new LocalDate[] {FIRST_ACCRUAL_DATE.toLocalDate(),
// FIRST_COUPON_DATE.toLocalDate(), LAST_TRADE_DATE.toLocalDate()});
// assertEquals(definition.getSettlementDates()[0], SETTLEMENT_DATE.toLocalDate());
}
private static class MyHolidaySource implements HolidaySource {
@Override
public boolean isHoliday(final LocalDate dateToCheck, final Currency currency) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public boolean isHoliday(final LocalDate dateToCheck, final HolidayType holidayType,
final IdentifierBundle regionOrExchangeIds) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public boolean isHoliday(final LocalDate dateToCheck, final HolidayType holidayType,
final Identifier regionOrExchangeId) {
return dateToCheck.getDayOfWeek() == DayOfWeek.SATURDAY || dateToCheck.getDayOfWeek() == DayOfWeek.SUNDAY;
}
@Override
public Holiday getHoliday(final UniqueIdentifier uid) {
return null;
}
}
}
|
Deleting an unneeded file
|
projects/OG-Financial/tests/unit/com/opengamma/financial/analytics/fixedincome/BondSecurityToBondDefinitionConverterTest.java
|
Deleting an unneeded file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.