repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
codeforkjeff/conciliator
src/main/java/com/codefork/refine/viaf/VIAFProxyModeMetaDataResponse.java
// Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java // public class NonVIAFSource extends Source { // // private static final Map<String, String> urls = new HashMap<>(); // // static { // urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}"); // // B2Q = no outgoing link // // BAV = no outgoing link // // BIBSYS = no outgoing link // // BNC = no outgoing link // // BNCHL = no outgoing link // // BNF = id in URL is different from id in "sid" field, so we disable this for now // // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}"); // // DBC = no outgoing link // urls.put("DNB", "http://d-nb.info/gnd/{{id}}"); // // EGAXA = no outgoing link // urls.put("ICCU", "http://id.sbn.it/af/{{id}}"); // urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}"); // // KRNLK = no outgoing link // // LAK = no outgoing link // urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}"); // // LNL = no outgoing link // // MRBNR = no outgoing link // urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}"); // // N6I = no outgoing link // // NKC = no outgoing link // // NLA = no outgoing link // // NLI = no outgoing link // // NLP = no outgoing link // // NLR = no outgoing link // // NSK = no outgoing link // // NTA = no outgoing link // // NUKAT = no outgoing link // // PTBNP = no outgoing link // // RERO = no outgoing link // urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}"); // urls.put("SUDOC", "http://www.idref.fr/{{id}}/id"); // // SWNL = no outgoing link // urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia"); // } // // private String code; // // public NonVIAFSource(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // // public String getServiceURLTemplate() { // String url = urls.get(code); // if(url == null) { // // TODO: This only works when IDs match IDs in source institution URLs, // // which is NOT the case for several sources that don't have URL templates: // // namely: BNC, BNF, DBC, NUKAT // // Can't think of a way to fix this right now. // url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code); // } // return url; // } // // @Override // public Result formatResult(SearchQuery query, VIAFResult viafResult) { // String source = query.getViafSource(); // // if no explicit source was specified, we should use any exact // // match if present, otherwise the most common one // String name = source != null ? // viafResult.getNameBySource(source) : // viafResult.getExactNameOrMostCommonName(query.getQuery()); // boolean exactMatch = name != null ? name.equals(query.getQuery()) : false; // // String sourceNameId = viafResult.getSourceNameId(source); // // // if we don't have a sourceNameId or VIAF gives it as a URL, // // use the name ID according to VIAF instead. // if(sourceNameId == null || sourceNameId.startsWith("http")) { // sourceNameId = viafResult.getNameId(source); // } // // // if there's STILL no source ID, we still have to return something, // // so we return 0. // if(sourceNameId == null) { // sourceNameId = "0"; // } // // Result r = new Result( // formatID(sourceNameId), // name, // viafResult.getNameType().asNameType(), // StringUtil.levenshteinDistanceRatio(name, query.getQuery()), // exactMatch); // return r; // } // // }
import com.codefork.refine.resources.View; import com.codefork.refine.viaf.sources.NonVIAFSource;
package com.codefork.refine.viaf; /** * Service metadata for "proxy mode": the important thing here is * "view" key contains URL template for the non-VIAF source (for example, * the LC website) rather than for VIAF. */ public class VIAFProxyModeMetaDataResponse extends VIAFMetaDataResponse { private String url;
// Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java // public class NonVIAFSource extends Source { // // private static final Map<String, String> urls = new HashMap<>(); // // static { // urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}"); // // B2Q = no outgoing link // // BAV = no outgoing link // // BIBSYS = no outgoing link // // BNC = no outgoing link // // BNCHL = no outgoing link // // BNF = id in URL is different from id in "sid" field, so we disable this for now // // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}"); // // DBC = no outgoing link // urls.put("DNB", "http://d-nb.info/gnd/{{id}}"); // // EGAXA = no outgoing link // urls.put("ICCU", "http://id.sbn.it/af/{{id}}"); // urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}"); // // KRNLK = no outgoing link // // LAK = no outgoing link // urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}"); // // LNL = no outgoing link // // MRBNR = no outgoing link // urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}"); // // N6I = no outgoing link // // NKC = no outgoing link // // NLA = no outgoing link // // NLI = no outgoing link // // NLP = no outgoing link // // NLR = no outgoing link // // NSK = no outgoing link // // NTA = no outgoing link // // NUKAT = no outgoing link // // PTBNP = no outgoing link // // RERO = no outgoing link // urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}"); // urls.put("SUDOC", "http://www.idref.fr/{{id}}/id"); // // SWNL = no outgoing link // urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia"); // } // // private String code; // // public NonVIAFSource(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // // public String getServiceURLTemplate() { // String url = urls.get(code); // if(url == null) { // // TODO: This only works when IDs match IDs in source institution URLs, // // which is NOT the case for several sources that don't have URL templates: // // namely: BNC, BNF, DBC, NUKAT // // Can't think of a way to fix this right now. // url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code); // } // return url; // } // // @Override // public Result formatResult(SearchQuery query, VIAFResult viafResult) { // String source = query.getViafSource(); // // if no explicit source was specified, we should use any exact // // match if present, otherwise the most common one // String name = source != null ? // viafResult.getNameBySource(source) : // viafResult.getExactNameOrMostCommonName(query.getQuery()); // boolean exactMatch = name != null ? name.equals(query.getQuery()) : false; // // String sourceNameId = viafResult.getSourceNameId(source); // // // if we don't have a sourceNameId or VIAF gives it as a URL, // // use the name ID according to VIAF instead. // if(sourceNameId == null || sourceNameId.startsWith("http")) { // sourceNameId = viafResult.getNameId(source); // } // // // if there's STILL no source ID, we still have to return something, // // so we return 0. // if(sourceNameId == null) { // sourceNameId = "0"; // } // // Result r = new Result( // formatID(sourceNameId), // name, // viafResult.getNameType().asNameType(), // StringUtil.levenshteinDistanceRatio(name, query.getQuery()), // exactMatch); // return r; // } // // } // Path: src/main/java/com/codefork/refine/viaf/VIAFProxyModeMetaDataResponse.java import com.codefork.refine.resources.View; import com.codefork.refine.viaf.sources.NonVIAFSource; package com.codefork.refine.viaf; /** * Service metadata for "proxy mode": the important thing here is * "view" key contains URL template for the non-VIAF source (for example, * the LC website) rather than for VIAF. */ public class VIAFProxyModeMetaDataResponse extends VIAFMetaDataResponse { private String url;
public VIAFProxyModeMetaDataResponse(NonVIAFSource nonVIAFSource, String baseUrl) {
codeforkjeff/conciliator
src/main/java/com/codefork/refine/viaf/VIAFProxyModeMetaDataResponse.java
// Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java // public class NonVIAFSource extends Source { // // private static final Map<String, String> urls = new HashMap<>(); // // static { // urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}"); // // B2Q = no outgoing link // // BAV = no outgoing link // // BIBSYS = no outgoing link // // BNC = no outgoing link // // BNCHL = no outgoing link // // BNF = id in URL is different from id in "sid" field, so we disable this for now // // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}"); // // DBC = no outgoing link // urls.put("DNB", "http://d-nb.info/gnd/{{id}}"); // // EGAXA = no outgoing link // urls.put("ICCU", "http://id.sbn.it/af/{{id}}"); // urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}"); // // KRNLK = no outgoing link // // LAK = no outgoing link // urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}"); // // LNL = no outgoing link // // MRBNR = no outgoing link // urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}"); // // N6I = no outgoing link // // NKC = no outgoing link // // NLA = no outgoing link // // NLI = no outgoing link // // NLP = no outgoing link // // NLR = no outgoing link // // NSK = no outgoing link // // NTA = no outgoing link // // NUKAT = no outgoing link // // PTBNP = no outgoing link // // RERO = no outgoing link // urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}"); // urls.put("SUDOC", "http://www.idref.fr/{{id}}/id"); // // SWNL = no outgoing link // urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia"); // } // // private String code; // // public NonVIAFSource(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // // public String getServiceURLTemplate() { // String url = urls.get(code); // if(url == null) { // // TODO: This only works when IDs match IDs in source institution URLs, // // which is NOT the case for several sources that don't have URL templates: // // namely: BNC, BNF, DBC, NUKAT // // Can't think of a way to fix this right now. // url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code); // } // return url; // } // // @Override // public Result formatResult(SearchQuery query, VIAFResult viafResult) { // String source = query.getViafSource(); // // if no explicit source was specified, we should use any exact // // match if present, otherwise the most common one // String name = source != null ? // viafResult.getNameBySource(source) : // viafResult.getExactNameOrMostCommonName(query.getQuery()); // boolean exactMatch = name != null ? name.equals(query.getQuery()) : false; // // String sourceNameId = viafResult.getSourceNameId(source); // // // if we don't have a sourceNameId or VIAF gives it as a URL, // // use the name ID according to VIAF instead. // if(sourceNameId == null || sourceNameId.startsWith("http")) { // sourceNameId = viafResult.getNameId(source); // } // // // if there's STILL no source ID, we still have to return something, // // so we return 0. // if(sourceNameId == null) { // sourceNameId = "0"; // } // // Result r = new Result( // formatID(sourceNameId), // name, // viafResult.getNameType().asNameType(), // StringUtil.levenshteinDistanceRatio(name, query.getQuery()), // exactMatch); // return r; // } // // }
import com.codefork.refine.resources.View; import com.codefork.refine.viaf.sources.NonVIAFSource;
package com.codefork.refine.viaf; /** * Service metadata for "proxy mode": the important thing here is * "view" key contains URL template for the non-VIAF source (for example, * the LC website) rather than for VIAF. */ public class VIAFProxyModeMetaDataResponse extends VIAFMetaDataResponse { private String url; public VIAFProxyModeMetaDataResponse(NonVIAFSource nonVIAFSource, String baseUrl) { super(nonVIAFSource.getCode() + " (by way of VIAF)", null, baseUrl); this.url = nonVIAFSource.getServiceURLTemplate(); } @Override
// Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/sources/NonVIAFSource.java // public class NonVIAFSource extends Source { // // private static final Map<String, String> urls = new HashMap<>(); // // static { // urls.put("BNE", "http://catalogo.bne.es/uhtbin/authoritybrowse.cgi?action=display&authority_id={{id}}"); // // B2Q = no outgoing link // // BAV = no outgoing link // // BIBSYS = no outgoing link // // BNC = no outgoing link // // BNCHL = no outgoing link // // BNF = id in URL is different from id in "sid" field, so we disable this for now // // urls.put("BNF", "http://catalogue.bnf.fr/ark:/12148/cb{{id}}"); // // DBC = no outgoing link // urls.put("DNB", "http://d-nb.info/gnd/{{id}}"); // // EGAXA = no outgoing link // urls.put("ICCU", "http://id.sbn.it/af/{{id}}"); // urls.put("JPG", "http://www.getty.edu/vow/ULANFullDisplay?find=&role=&nation=&subjectid={{id}}"); // // KRNLK = no outgoing link // // LAK = no outgoing link // urls.put("LC", "http://id.loc.gov/authorities/names/{{id}}"); // // LNL = no outgoing link // // MRBNR = no outgoing link // urls.put("NDL", "http://id.ndl.go.jp/auth/ndlna/{{id}}"); // // N6I = no outgoing link // // NKC = no outgoing link // // NLA = no outgoing link // // NLI = no outgoing link // // NLP = no outgoing link // // NLR = no outgoing link // // NSK = no outgoing link // // NTA = no outgoing link // // NUKAT = no outgoing link // // PTBNP = no outgoing link // // RERO = no outgoing link // urls.put("SELIBR", "http://libris.kb.se/resource/auth/{{id}}"); // urls.put("SUDOC", "http://www.idref.fr/{{id}}/id"); // // SWNL = no outgoing link // urls.put("WKP", "http://www.wikidata.org/entity/{{id}}#sitelinks-wikipedia"); // } // // private String code; // // public NonVIAFSource(String code) { // this.code = code; // } // // public String getCode() { // return code; // } // // public String getServiceURLTemplate() { // String url = urls.get(code); // if(url == null) { // // TODO: This only works when IDs match IDs in source institution URLs, // // which is NOT the case for several sources that don't have URL templates: // // namely: BNC, BNF, DBC, NUKAT // // Can't think of a way to fix this right now. // url = String.format("https://viaf.org/viaf/sourceID/%s|{{id}}", code); // } // return url; // } // // @Override // public Result formatResult(SearchQuery query, VIAFResult viafResult) { // String source = query.getViafSource(); // // if no explicit source was specified, we should use any exact // // match if present, otherwise the most common one // String name = source != null ? // viafResult.getNameBySource(source) : // viafResult.getExactNameOrMostCommonName(query.getQuery()); // boolean exactMatch = name != null ? name.equals(query.getQuery()) : false; // // String sourceNameId = viafResult.getSourceNameId(source); // // // if we don't have a sourceNameId or VIAF gives it as a URL, // // use the name ID according to VIAF instead. // if(sourceNameId == null || sourceNameId.startsWith("http")) { // sourceNameId = viafResult.getNameId(source); // } // // // if there's STILL no source ID, we still have to return something, // // so we return 0. // if(sourceNameId == null) { // sourceNameId = "0"; // } // // Result r = new Result( // formatID(sourceNameId), // name, // viafResult.getNameType().asNameType(), // StringUtil.levenshteinDistanceRatio(name, query.getQuery()), // exactMatch); // return r; // } // // } // Path: src/main/java/com/codefork/refine/viaf/VIAFProxyModeMetaDataResponse.java import com.codefork.refine.resources.View; import com.codefork.refine.viaf.sources.NonVIAFSource; package com.codefork.refine.viaf; /** * Service metadata for "proxy mode": the important thing here is * "view" key contains URL template for the non-VIAF source (for example, * the LC website) rather than for VIAF. */ public class VIAFProxyModeMetaDataResponse extends VIAFMetaDataResponse { private String url; public VIAFProxyModeMetaDataResponse(NonVIAFSource nonVIAFSource, String baseUrl) { super(nonVIAFSource.getCode() + " (by way of VIAF)", null, baseUrl); this.url = nonVIAFSource.getServiceURLTemplate(); } @Override
public View getView() {
codeforkjeff/conciliator
src/test/java/com/codefork/refine/solr/SolrParserTest.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // }
import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.Result; import org.junit.Test; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import java.util.List; import static org.junit.Assert.assertEquals;
package com.codefork.refine.solr; public class SolrParserTest { @Test public void testParse() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser();
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // } // Path: src/test/java/com/codefork/refine/solr/SolrParserTest.java import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.Result; import org.junit.Test; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import java.util.List; import static org.junit.Assert.assertEquals; package com.codefork.refine.solr; public class SolrParserTest { @Test public void testParse() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser();
SolrParser solrParser = new SolrParser("id", "title_display", null, null, new NameType("/book/book", "Book"));
codeforkjeff/conciliator
src/test/java/com/codefork/refine/solr/SolrParserTest.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // }
import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.Result; import org.junit.Test; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import java.util.List; import static org.junit.Assert.assertEquals;
package com.codefork.refine.solr; public class SolrParserTest { @Test public void testParse() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); SolrParser solrParser = new SolrParser("id", "title_display", null, null, new NameType("/book/book", "Book")); InputStream is = getClass().getResourceAsStream("/solr_results.xml"); parser.parse(is, solrParser);
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // } // Path: src/test/java/com/codefork/refine/solr/SolrParserTest.java import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.Result; import org.junit.Test; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import java.util.List; import static org.junit.Assert.assertEquals; package com.codefork.refine.solr; public class SolrParserTest { @Test public void testParse() throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); SolrParser solrParser = new SolrParser("id", "title_display", null, null, new NameType("/book/book", "Book")); InputStream is = getClass().getResourceAsStream("/solr_results.xml"); parser.parse(is, solrParser);
List<Result> results = solrParser.getResults();
codeforkjeff/conciliator
src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // }
import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List;
package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // } // Path: src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List; package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id";
private final static List<NameType> DEFAULT_TYPES = new ArrayList<>();
codeforkjeff/conciliator
src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // }
import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List;
package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id"; private final static List<NameType> DEFAULT_TYPES = new ArrayList<>();
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // } // Path: src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List; package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id"; private final static List<NameType> DEFAULT_TYPES = new ArrayList<>();
private View view;
codeforkjeff/conciliator
src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // }
import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List;
package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id"; private final static List<NameType> DEFAULT_TYPES = new ArrayList<>(); private View view; static { // TODO: it would be nice to make this list of default name types configurable // somehow; for now, just use the ones for VIAF
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // // Path: src/main/java/com/codefork/refine/resources/ServiceMetaDataResponse.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public abstract class ServiceMetaDataResponse { // // private String name; // private String identifierSpace; // private String schemaSpace; // private View view; // private List<NameType> defaultTypes; // private Preview preview; // private Extend extend; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getIdentifierSpace() { // return identifierSpace; // } // // public void setIdentifierSpace(String identifierSpace) { // this.identifierSpace = identifierSpace; // } // // public String getSchemaSpace() { // return schemaSpace; // } // // public void setSchemaSpace(String schemaSpace) { // this.schemaSpace = schemaSpace; // } // // public View getView() { // return view; // } // // public void setView(View view) { // this.view = view; // } // // public List<NameType> getDefaultTypes() { // return defaultTypes; // } // // public void setDefaultTypes(List<NameType> defaultTypes) { // this.defaultTypes = defaultTypes; // } // // public Preview getPreview() { // return preview; // } // // public void setPreview(Preview preview) { // this.preview = preview; // } // // public Extend getExtend() { // return extend; // } // // public void setExtend(Extend extend) { // this.extend = extend; // } // // } // // Path: src/main/java/com/codefork/refine/resources/View.java // public class View { // private String url; // // public View(String url) { // this.url = url; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // } // // Path: src/main/java/com/codefork/refine/viaf/VIAFNameType.java // public enum VIAFNameType { // Person("/people/person", "Person", "Personal", "local.personalNames all \"%s\""), // Organization("/organization/organization", "Corporate Name", "Corporate", "local.corporateNames all \"%s\""), // Location("/location/location", "Geographic Name", "Geographic", "local.geographicNames all \"%s\""), // // can't find better freebase ids for these two // Book("/book/book", "Work", "UniformTitleWork", "local.uniformTitleWorks all \"%s\""), // Edition("/book/book edition", "Expression", "UniformTitleExpression", "local.uniformTitleExpressions all \"%s\""); // // // ids are from freebase identifier ns // private final String id; // private final String displayName; // private final String viafCode; // private final String cqlString; // private NameType nameType; // // VIAFNameType(String id, String displayName, String viafCode, String cqlString) { // this.id = id; // this.displayName = displayName; // this.viafCode = viafCode; // this.cqlString = cqlString; // // this.nameType = new NameType(getId(), getDisplayName()); // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public String getViafCode() { // return viafCode; // } // // public String getCqlString() { // return cqlString; // } // // public NameType asNameType() { // return nameType; // } // // public static VIAFNameType getByViafCode(String viafCodeArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.viafCode.equals(viafCodeArg)) { // return nameType; // } // } // return null; // } // // public static VIAFNameType getById(String idArg) { // for(VIAFNameType nameType: VIAFNameType.values()) { // if(nameType.id.equals(idArg)) { // return nameType; // } // } // return null; // } // // } // Path: src/main/java/com/codefork/refine/solr/SolrMetaDataResponse.java import com.codefork.refine.resources.NameType; import com.codefork.refine.resources.ServiceMetaDataResponse; import com.codefork.refine.resources.View; import com.codefork.refine.viaf.VIAFNameType; import java.util.ArrayList; import java.util.List; package com.codefork.refine.solr; public class SolrMetaDataResponse extends ServiceMetaDataResponse { private final static String IDENTIFIER_SPACE = "http://rdf.freebase.com/ns/user/hangy/viaf"; private final static String SCHEMA_SPACE = "http://rdf.freebase.com/ns/type.object.id"; private final static List<NameType> DEFAULT_TYPES = new ArrayList<>(); private View view; static { // TODO: it would be nice to make this list of default name types configurable // somehow; for now, just use the ones for VIAF
for(VIAFNameType nameType : VIAFNameType.values()) {
codeforkjeff/conciliator
src/main/java/com/codefork/refine/SearchResult.java
// Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // }
import com.codefork.refine.resources.Result; import java.util.List;
package com.codefork.refine; /** */ public class SearchResult { public enum ErrorType { UNKNOWN, TOO_MANY_REQUESTS } private String key;
// Path: src/main/java/com/codefork/refine/resources/Result.java // public class Result { // // private String id; // private String name; // // /** // * It's weird that this is a list but that's what OpenRefine expects. // * A VIAF result only ever has one type, but maybe other reconciliation // * services return multiple types for a name? // */ // private List<NameType> type; // private double score; // private boolean match; // // public Result() { // } // // public Result(String id, String name, NameType nameType, double score, boolean match) { // this.id = id; // this.name = name; // this.type = new ArrayList<>(); // this.type.add(nameType); // this.score = score; // this.match = match; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<NameType> getType() { // return type; // } // // public void setType(List<NameType> resultType) { // this.type = resultType; // } // // public double getScore() { // return score; // } // // public void setScore(double score) { // this.score = score; // } // // public boolean isMatch() { // return match; // } // // public void setMatch(boolean match) { // this.match = match; // } // // } // Path: src/main/java/com/codefork/refine/SearchResult.java import com.codefork.refine.resources.Result; import java.util.List; package com.codefork.refine; /** */ public class SearchResult { public enum ErrorType { UNKNOWN, TOO_MANY_REQUESTS } private String key;
private List<Result> results;
codeforkjeff/conciliator
src/main/java/com/codefork/refine/SearchQuery.java
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // }
import com.codefork.refine.resources.NameType; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
package com.codefork.refine; /** * Represents a single query in a request sent by Open Refine. * For the JSON format of this query, see * https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-API * * There's not much documentation about the type_strict field: * when it's set, it's always "should" although the docs say there * are other possible values. */ public class SearchQuery { private String query; private int limit;
// Path: src/main/java/com/codefork/refine/resources/NameType.java // public class NameType { // // private String id; // private String name; // // public NameType(String id, String name) { // this.id = id; // this.name = name; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public boolean equals(Object obj) { // if(obj instanceof NameType) { // NameType obj2 = (NameType) obj; // return obj2.getId().equals(getId()) // && obj2.getName().equals(getName()); // } // return false; // } // } // Path: src/main/java/com/codefork/refine/SearchQuery.java import com.codefork.refine.resources.NameType; import com.fasterxml.jackson.databind.JsonNode; import java.util.HashMap; import java.util.Iterator; import java.util.Map; package com.codefork.refine; /** * Represents a single query in a request sent by Open Refine. * For the JSON format of this query, see * https://github.com/OpenRefine/OpenRefine/wiki/Reconciliation-Service-API * * There's not much documentation about the type_strict field: * when it's set, it's always "should" although the docs say there * are other possible values. */ public class SearchQuery { private String query; private int limit;
private NameType nameType;
Germanet-sfs/GermaNetApi
src/main/java/de/tuebingen/uni/sfs/germanet/api/StaxLoader.java
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int NUMBER_OF_GERMANET_FILES = 55;
import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.NUMBER_OF_GERMANET_FILES; import java.io.*; import java.util.List; import java.util.Map; import java.util.Set; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException;
Object2ObjectMap<String, ObjectSet<String>> lowerToUpperMap = new Object2ObjectOpenHashMap<>(); ObjectIterator<Synset> synsetIterator; ObjectIterator<LexUnit> lexUnitIterator; List<Synset> synsetsFromInputStream; Synset synset; LexUnit lexUnit; Set<Synset> synsetSet; Set<LexUnit> lexUnitSet; WordCategory cat; Map<String, Set<LexUnit>> mapAllOrthForms; String orthForm; // load all synset input streams first with a SynsetLoader for (int i = 0; i < inputStreams.size(); i++) { InputStream stream = inputStreams.get(i); String name = xmlNames.get(i); LOGGER.info("Loading {}...", name); synsetsFromInputStream = SynsetLoader.loadSynsets(stream); synsets.addAll(synsetsFromInputStream); synsetIterator = ObjectIterators.asObjectIterator(synsetsFromInputStream.iterator()); while (synsetIterator.hasNext()) { synset = synsetIterator.next(); cat = synset.getWordCategory(); synsetIdMap.put(synset.getId(), synset); // Don't add Root or its LexUnit to any of the // WordCategory or orthForm maps
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int NUMBER_OF_GERMANET_FILES = 55; // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/StaxLoader.java import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.NUMBER_OF_GERMANET_FILES; import java.io.*; import java.util.List; import java.util.Map; import java.util.Set; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; Object2ObjectMap<String, ObjectSet<String>> lowerToUpperMap = new Object2ObjectOpenHashMap<>(); ObjectIterator<Synset> synsetIterator; ObjectIterator<LexUnit> lexUnitIterator; List<Synset> synsetsFromInputStream; Synset synset; LexUnit lexUnit; Set<Synset> synsetSet; Set<LexUnit> lexUnitSet; WordCategory cat; Map<String, Set<LexUnit>> mapAllOrthForms; String orthForm; // load all synset input streams first with a SynsetLoader for (int i = 0; i < inputStreams.size(); i++) { InputStream stream = inputStreams.get(i); String name = xmlNames.get(i); LOGGER.info("Loading {}...", name); synsetsFromInputStream = SynsetLoader.loadSynsets(stream); synsets.addAll(synsetsFromInputStream); synsetIterator = ObjectIterators.asObjectIterator(synsetsFromInputStream.iterator()); while (synsetIterator.hasNext()) { synset = synsetIterator.next(); cat = synset.getWordCategory(); synsetIdMap.put(synset.getId(), synset); // Don't add Root or its LexUnit to any of the // WordCategory or orthForm maps
if (synset.getId() == GNROOT_ID) {
Germanet-sfs/GermaNetApi
src/main/java/de/tuebingen/uni/sfs/germanet/api/StaxLoader.java
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int NUMBER_OF_GERMANET_FILES = 55;
import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.NUMBER_OF_GERMANET_FILES; import java.io.*; import java.util.List; import java.util.Map; import java.util.Set; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException;
orthForm = lexUnit.getOrthForm(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get orthVar // add orthVar and lowercase orthVar to lowerToUpperMap orthForm = lexUnit.getOrthVar(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get oldOrthForm // add oldOrthForm and lowercase oldOrthForm to lowerToUpperMap orthForm = lexUnit.getOldOrthForm(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get oldOrthVar // add oldOrthVar and lowercase oldOrthVar to lowerToUpperMap orthForm = lexUnit.getOldOrthVar(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); } wordCategoryMapAllOrthForms.put(cat, mapAllOrthForms); } stream.close(); loadedFiles++; } // load relations with a RelationLoader LOGGER.info("Loading {}...", relsXmlName); RelationLoader.loadRelations(relsInputStream, synsetIdMap, lexUnitIdMap); loadedFiles++;
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int NUMBER_OF_GERMANET_FILES = 55; // Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/StaxLoader.java import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.NUMBER_OF_GERMANET_FILES; import java.io.*; import java.util.List; import java.util.Map; import java.util.Set; import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap; import it.unimi.dsi.fastutil.objects.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; orthForm = lexUnit.getOrthForm(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get orthVar // add orthVar and lowercase orthVar to lowerToUpperMap orthForm = lexUnit.getOrthVar(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get oldOrthForm // add oldOrthForm and lowercase oldOrthForm to lowerToUpperMap orthForm = lexUnit.getOldOrthForm(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); // get oldOrthVar // add oldOrthVar and lowercase oldOrthVar to lowerToUpperMap orthForm = lexUnit.getOldOrthVar(); StaxLoader.processOrthForm(orthForm, lexUnit, mapAllOrthForms, lowerToUpperMap); } wordCategoryMapAllOrthForms.put(cat, mapAllOrthForms); } stream.close(); loadedFiles++; } // load relations with a RelationLoader LOGGER.info("Loading {}...", relsXmlName); RelationLoader.loadRelations(relsInputStream, synsetIdMap, lexUnitIdMap); loadedFiles++;
if (loadedFiles >= NUMBER_OF_GERMANET_FILES) {
Germanet-sfs/GermaNetApi
src/test/java/de/tuebingen/uni/sfs/germanet/api/R14SemanticUtilsTest.java
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001;
import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // Path: src/test/java/de/tuebingen/uni/sfs/germanet/api/R14SemanticUtilsTest.java import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
new LeastCommonSubsumer(GNROOT_ID, Sets.newHashSet(regressivID, denunziatorischID), 18)
Germanet-sfs/GermaNetApi
src/test/java/de/tuebingen/uni/sfs/germanet/api/R16SemanticUtilsTest.java
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001;
import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // Path: src/test/java/de/tuebingen/uni/sfs/germanet/api/R16SemanticUtilsTest.java import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
new LeastCommonSubsumer(GNROOT_ID, Sets.newHashSet(regressivID, denunziatorischID), 18)
Germanet-sfs/GermaNetApi
src/test/java/de/tuebingen/uni/sfs/germanet/api/R15SemanticUtilsTest.java
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001;
import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
// Path: src/main/java/de/tuebingen/uni/sfs/germanet/api/GermaNet.java // public static final int GNROOT_ID = 51001; // Path: src/test/java/de/tuebingen/uni/sfs/germanet/api/R15SemanticUtilsTest.java import javax.xml.stream.XMLStreamException; import java.io.IOException; import java.util.*; import java.util.stream.Stream; import static de.tuebingen.uni.sfs.germanet.api.GermaNet.GNROOT_ID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.Sets; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; new LeastCommonSubsumer(krautID, Sets.newHashSet(krautID, heilpflanzeID), 1) ); return Stream.of( Arguments.of("Apfel - Birne -> Kernobst", apfelID, birneID, apfelBirneExpected), Arguments.of("Apfel - Baum -> Objekt", apfelID, baumID, apfelBaumExpected), Arguments.of("Pferd (animal) - Pferd (Chess) -> Objekt", pferdAnimalID, pferdChessID, pferdExpected), Arguments.of("Chinarindenbaum - Kompresse -> Medizinischer Artikel", chinarindenbaumID, kompresseID, chinarindenbaumKompresseExpected), Arguments.of("Kraut - Heilpflanze -> Kraut", krautID, heilpflanzeID, krautHeilpflanzeExpected) ); } private static Stream<Arguments> lcsVerbProvider() { // einkaufen - auftun -> geben Set<LeastCommonSubsumer> einkaufenAuftunExpected = Sets.newHashSet( new LeastCommonSubsumer(gebenID, Sets.newHashSet(einkaufenID, auftunID), 7) ); return Stream.of( Arguments.of("einkaufen - auftun -> geben", einkaufenID, auftunID, einkaufenAuftunExpected) ); } private static Stream<Arguments> lcsAdjProvider() { // regressiv - denunziatorisch -> GNROOT Set<LeastCommonSubsumer> regressivDenunziatorischExpected = Sets.newHashSet( new LeastCommonSubsumer(0, Sets.newHashSet(regressivID, denunziatorischID), 18),
new LeastCommonSubsumer(GNROOT_ID, Sets.newHashSet(regressivID, denunziatorischID), 18)
Yeamy/SqlBuilder
src/com/yeamy/sql/statement/AlterTable.java
// Path: src/com/yeamy/sql/statement/columninfo/ColumnInfo.java // public abstract class ColumnInfo<T extends ColumnInfo<T>> implements SQLString { // public static final Object NO_DEFAULT = "NO_DEFAULT"; // // private boolean primary; // private boolean notNull; // private Object _default = NO_DEFAULT; // protected int increment; // protected Object onUpdate; // // public boolean isPrimary() { // return primary; // } // // public T primaryKey() { // primary = true; // return notNull(); // } // // @SuppressWarnings("unchecked") // public T notNull() { // notNull = true; // return (T) this; // } // // @SuppressWarnings("unchecked") // public T defaultValue(Object _default) { // this._default = _default; // return (T) this; // } // // protected abstract void dataType(StringBuilder sql); // // @Override // public void toSQL(StringBuilder sql) { // dataType(sql); // if (notNull) { // sql.append(" NOT NULL"); // } // if (increment > 0) {// mysql // sql.append(" AUTO_INCREMENT"); // if (increment > 1) { // sql.append(" =").append(increment); // } // } // if (_default != NO_DEFAULT) {// mysql // sql.append(" DEFAULT "); // SQLString.appendValue(sql, _default); // } // if (onUpdate != null) { // sql.append(" ON UPDATE"); // SQLString.appendValue(sql, onUpdate); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // toSQL(sb); // return sb.toString(); // } // }
import java.util.ArrayList; import com.yeamy.sql.statement.columninfo.ColumnInfo;
package com.yeamy.sql.statement; public class AlterTable implements SQLString { private String table; private ArrayList<SQLString> columns = new ArrayList<>(); public AlterTable(String table) { this.table = table; } // column
// Path: src/com/yeamy/sql/statement/columninfo/ColumnInfo.java // public abstract class ColumnInfo<T extends ColumnInfo<T>> implements SQLString { // public static final Object NO_DEFAULT = "NO_DEFAULT"; // // private boolean primary; // private boolean notNull; // private Object _default = NO_DEFAULT; // protected int increment; // protected Object onUpdate; // // public boolean isPrimary() { // return primary; // } // // public T primaryKey() { // primary = true; // return notNull(); // } // // @SuppressWarnings("unchecked") // public T notNull() { // notNull = true; // return (T) this; // } // // @SuppressWarnings("unchecked") // public T defaultValue(Object _default) { // this._default = _default; // return (T) this; // } // // protected abstract void dataType(StringBuilder sql); // // @Override // public void toSQL(StringBuilder sql) { // dataType(sql); // if (notNull) { // sql.append(" NOT NULL"); // } // if (increment > 0) {// mysql // sql.append(" AUTO_INCREMENT"); // if (increment > 1) { // sql.append(" =").append(increment); // } // } // if (_default != NO_DEFAULT) {// mysql // sql.append(" DEFAULT "); // SQLString.appendValue(sql, _default); // } // if (onUpdate != null) { // sql.append(" ON UPDATE"); // SQLString.appendValue(sql, onUpdate); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // toSQL(sb); // return sb.toString(); // } // } // Path: src/com/yeamy/sql/statement/AlterTable.java import java.util.ArrayList; import com.yeamy.sql.statement.columninfo.ColumnInfo; package com.yeamy.sql.statement; public class AlterTable implements SQLString { private String table; private ArrayList<SQLString> columns = new ArrayList<>(); public AlterTable(String table) { this.table = table; } // column
public AlterTable add(String column, ColumnInfo dataType) {
Yeamy/SqlBuilder
src/com/yeamy/sql/statement/function/IfNull.java
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // }
import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString;
package com.yeamy.sql.statement.function; public class IfNull extends AbsColumn<IfNull> { private Object col, whenNull; public IfNull(Object col, Object whenNull) { this(col, whenNull, null); } public IfNull(Object col, Object whenNull, String nameAlias) { this.col = col; this.whenNull = whenNull; this.nameAlias = nameAlias; } @Override public void toSQL(StringBuilder sb) { sb.append("IFNULL(");
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // } // Path: src/com/yeamy/sql/statement/function/IfNull.java import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString; package com.yeamy.sql.statement.function; public class IfNull extends AbsColumn<IfNull> { private Object col, whenNull; public IfNull(Object col, Object whenNull) { this(col, whenNull, null); } public IfNull(Object col, Object whenNull, String nameAlias) { this.col = col; this.whenNull = whenNull; this.nameAlias = nameAlias; } @Override public void toSQL(StringBuilder sb) { sb.append("IFNULL(");
SQLString.appendValue(sb, col);
Yeamy/SqlBuilder
src/com/yeamy/sql/statement/function/Virtual.java
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // }
import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString;
package com.yeamy.sql.statement.function; public class Virtual extends AbsColumn<Virtual> { private Object value; public Virtual(Object value, String nameAlias) { this.value = value; this.nameAlias = nameAlias; } @Override public void toSQL(StringBuilder sb) {
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // } // Path: src/com/yeamy/sql/statement/function/Virtual.java import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString; package com.yeamy.sql.statement.function; public class Virtual extends AbsColumn<Virtual> { private Object value; public Virtual(Object value, String nameAlias) { this.value = value; this.nameAlias = nameAlias; } @Override public void toSQL(StringBuilder sb) {
SQLString.appendValue(sb, value);
Yeamy/SqlBuilder
src/com/yeamy/sql/statement/CreateTable.java
// Path: src/com/yeamy/sql/statement/columninfo/ColumnInfo.java // public abstract class ColumnInfo<T extends ColumnInfo<T>> implements SQLString { // public static final Object NO_DEFAULT = "NO_DEFAULT"; // // private boolean primary; // private boolean notNull; // private Object _default = NO_DEFAULT; // protected int increment; // protected Object onUpdate; // // public boolean isPrimary() { // return primary; // } // // public T primaryKey() { // primary = true; // return notNull(); // } // // @SuppressWarnings("unchecked") // public T notNull() { // notNull = true; // return (T) this; // } // // @SuppressWarnings("unchecked") // public T defaultValue(Object _default) { // this._default = _default; // return (T) this; // } // // protected abstract void dataType(StringBuilder sql); // // @Override // public void toSQL(StringBuilder sql) { // dataType(sql); // if (notNull) { // sql.append(" NOT NULL"); // } // if (increment > 0) {// mysql // sql.append(" AUTO_INCREMENT"); // if (increment > 1) { // sql.append(" =").append(increment); // } // } // if (_default != NO_DEFAULT) {// mysql // sql.append(" DEFAULT "); // SQLString.appendValue(sql, _default); // } // if (onUpdate != null) { // sql.append(" ON UPDATE"); // SQLString.appendValue(sql, onUpdate); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // toSQL(sb); // return sb.toString(); // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map.Entry; import com.yeamy.sql.statement.columninfo.ColumnInfo;
package com.yeamy.sql.statement; public class CreateTable implements SQLString { private String database; private String table;
// Path: src/com/yeamy/sql/statement/columninfo/ColumnInfo.java // public abstract class ColumnInfo<T extends ColumnInfo<T>> implements SQLString { // public static final Object NO_DEFAULT = "NO_DEFAULT"; // // private boolean primary; // private boolean notNull; // private Object _default = NO_DEFAULT; // protected int increment; // protected Object onUpdate; // // public boolean isPrimary() { // return primary; // } // // public T primaryKey() { // primary = true; // return notNull(); // } // // @SuppressWarnings("unchecked") // public T notNull() { // notNull = true; // return (T) this; // } // // @SuppressWarnings("unchecked") // public T defaultValue(Object _default) { // this._default = _default; // return (T) this; // } // // protected abstract void dataType(StringBuilder sql); // // @Override // public void toSQL(StringBuilder sql) { // dataType(sql); // if (notNull) { // sql.append(" NOT NULL"); // } // if (increment > 0) {// mysql // sql.append(" AUTO_INCREMENT"); // if (increment > 1) { // sql.append(" =").append(increment); // } // } // if (_default != NO_DEFAULT) {// mysql // sql.append(" DEFAULT "); // SQLString.appendValue(sql, _default); // } // if (onUpdate != null) { // sql.append(" ON UPDATE"); // SQLString.appendValue(sql, onUpdate); // } // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // toSQL(sb); // return sb.toString(); // } // } // Path: src/com/yeamy/sql/statement/CreateTable.java import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map.Entry; import com.yeamy.sql.statement.columninfo.ColumnInfo; package com.yeamy.sql.statement; public class CreateTable implements SQLString { private String database; private String table;
private LinkedHashMap<String, ColumnInfo> columns = new LinkedHashMap<>();
Yeamy/SqlBuilder
src/com/yeamy/sql/statement/function/Expression.java
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // }
import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString;
package com.yeamy.sql.statement.function; public class Expression extends AbsColumn<Expression> { private static final char[] symbol = { '+', '-', '*', '/', '%', '(', ')', '|', '>', '<', '=' }; private Object[] objs; /** * @param Object {@code AbsColumn}<br> * {@code Searchable}<br> * {@code String}(earch char is symbol) <br> * {@code String}(value) <br> * {@code SQLString}(value) <br> * {@code Number} */ public Expression(Object... objs) { this.objs = objs; } @Override public void toSQL(StringBuilder sb) { boolean f = true; for (Object obj : objs) { if (f) { f = false; } else { sb.append(' '); } if (obj instanceof AbsColumn) { ((AbsColumn) obj).toSQL(sb); } else if (obj instanceof String) { String str = (String) obj; if (allSymbol(str)) { sb.append(str); } else {
// Path: src/com/yeamy/sql/statement/AbsColumn.java // public abstract class AbsColumn<T extends AbsColumn<T>> implements SQLString { // protected String nameAlias; // // @SuppressWarnings("unchecked") // public T as(String nameAlias) { // this.nameAlias = nameAlias; // return (T) this; // } // // /** // * tableAlias.name AS alias -> table.name AS alias // */ // public void nameInColumn(StringBuilder sql) { // toSQL(sql); // if (nameAlias != null) { // sql.append(" AS "); // SQLString.appendColumn(sql, nameAlias); // } // } // // /** // * group by / order by // */ // public void shortName(StringBuilder sql) { // if (nameAlias != null) { // SQLString.appendColumn(sql, nameAlias); // } else { // toSQL(sql); // } // } // // } // // Path: src/com/yeamy/sql/statement/SQLString.java // public interface SQLString { // // void toSQL(StringBuilder sb); // // public static SQLString asValue(Object v) { // return (sb) -> { // sb.append(v); // }; // } // // public static String toString(Object value) { // StringBuilder sb = new StringBuilder(); // appendValue(sb, value); // return sb.toString(); // } // // public static void appendDatabase(StringBuilder sb, String database) { // sb.append('`').append(database).append('`'); // } // // public static void appendTable(StringBuilder sb, String table) { // sb.append('`').append(table).append('`'); // } // // public static void appendColumn(StringBuilder sb, String column) { // if (Column.ALL.equals(column)) { // sb.append("*"); // } else { // sb.append('`').append(column).append('`'); // } // } // // /** // * 检查数据安全,添加转义符 // */ // public static void appendValue(StringBuilder sb, Object value) { // if (value == null) { // sb.append("NULL"); // } else if (value instanceof Number) { // sb.append(value); // } else if (value instanceof Searchable) { // Searchable select = (Searchable) value; // sb.append('('); // select.toSQL(sb); // sb.append(')'); // } else if (value instanceof SQLString) { // ((SQLString) value).toSQL(sb); // } else if (value instanceof Date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // value = sdf.format((Date) value); // appendValue(sb, value); // } else { // // as String // sb.append('\''); // String out = value.toString().replace("\'", "\\\'"); // sb.append(out); // sb.append('\''); // } // } // } // Path: src/com/yeamy/sql/statement/function/Expression.java import com.yeamy.sql.statement.AbsColumn; import com.yeamy.sql.statement.SQLString; package com.yeamy.sql.statement.function; public class Expression extends AbsColumn<Expression> { private static final char[] symbol = { '+', '-', '*', '/', '%', '(', ')', '|', '>', '<', '=' }; private Object[] objs; /** * @param Object {@code AbsColumn}<br> * {@code Searchable}<br> * {@code String}(earch char is symbol) <br> * {@code String}(value) <br> * {@code SQLString}(value) <br> * {@code Number} */ public Expression(Object... objs) { this.objs = objs; } @Override public void toSQL(StringBuilder sb) { boolean f = true; for (Object obj : objs) { if (f) { f = false; } else { sb.append(' '); } if (obj instanceof AbsColumn) { ((AbsColumn) obj).toSQL(sb); } else if (obj instanceof String) { String str = (String) obj; if (allSymbol(str)) { sb.append(str); } else {
SQLString.appendValue(sb, str);
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/math_utils/MathUtilities.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
} else { return number.setScale(scale, roundingMode); } } else { return number.setScale(scale, roundingMode); } } public static BigDecimal computePopulationStandardDeviationOfBigDecimals(List<BigDecimal> numbers) { if ((numbers == null) || numbers.isEmpty()) { return null; } try { double[] doublesArray = new double[numbers.size()]; for (int i = 0; i < doublesArray.length; i++) { doublesArray[i] = numbers.get(i).doubleValue(); } StandardDeviation standardDeviation = new StandardDeviation(); standardDeviation.setBiasCorrected(false); BigDecimal standardDeviationResult = new BigDecimal(standardDeviation.evaluate(doublesArray)); return standardDeviationResult; } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/math_utils/MathUtilities.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; } else { return number.setScale(scale, roundingMode); } } else { return number.setScale(scale, roundingMode); } } public static BigDecimal computePopulationStandardDeviationOfBigDecimals(List<BigDecimal> numbers) { if ((numbers == null) || numbers.isEmpty()) { return null; } try { double[] doublesArray = new double[numbers.size()]; for (int i = 0; i < doublesArray.length; i++) { doublesArray[i] = numbers.get(i).doubleValue(); } StandardDeviation standardDeviation = new StandardDeviation(); standardDeviation.setBiasCorrected(false); BigDecimal standardDeviationResult = new BigDecimal(standardDeviation.evaluate(doublesArray)); return standardDeviationResult; } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/metric_formats/opentsdb/OpenTsdbHttpOutputModule.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.metric_formats.opentsdb; /** * @author Jeffrey Schmidt */ public class OpenTsdbHttpOutputModule { private static final Logger logger = LoggerFactory.getLogger(OpenTsdbHttpOutputModule.class.getName()); private final boolean isOutputEnabled_; private final String urlString_; private final int numSendRetryAttempts_; private final int maxMetricsPerMessage_; private final boolean sanitizeMetrics_; private final String uniqueId_; private URL url_; public OpenTsdbHttpOutputModule(boolean isOutputEnabled, String url, int numSendRetryAttempts, int maxMetricsPerMessage, boolean sanitizeMetrics, String uniqueId) { this.isOutputEnabled_ = isOutputEnabled; this.urlString_ = url; this.numSendRetryAttempts_ = numSendRetryAttempts; this.maxMetricsPerMessage_ = maxMetricsPerMessage; this.sanitizeMetrics_ = sanitizeMetrics; this.uniqueId_ = uniqueId; try { url_ = new URL(url); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/metric_formats/opentsdb/OpenTsdbHttpOutputModule.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.net.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.metric_formats.opentsdb; /** * @author Jeffrey Schmidt */ public class OpenTsdbHttpOutputModule { private static final Logger logger = LoggerFactory.getLogger(OpenTsdbHttpOutputModule.class.getName()); private final boolean isOutputEnabled_; private final String urlString_; private final int numSendRetryAttempts_; private final int maxMetricsPerMessage_; private final boolean sanitizeMetrics_; private final String uniqueId_; private URL url_; public OpenTsdbHttpOutputModule(boolean isOutputEnabled, String url, int numSendRetryAttempts, int maxMetricsPerMessage, boolean sanitizeMetrics, String uniqueId) { this.isOutputEnabled_ = isOutputEnabled; this.urlString_ = url; this.numSendRetryAttempts_ = numSendRetryAttempts; this.maxMetricsPerMessage_ = maxMetricsPerMessage; this.sanitizeMetrics_ = sanitizeMetrics; this.uniqueId_ = uniqueId; try { url_ = new URL(url); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/web_utils/HttpUtils.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
int colonIndex = credentialsString.indexOf(':'); if ((colonIndex > -1) && (colonIndex < (credentialsString.length() - 1))) { String username = credentialsString.substring(0, colonIndex); String password = credentialsString.substring(colonIndex + 1, credentialsString.length()); usernameAndPassword[0] = username; usernameAndPassword[1] = password; } } catch (Exception e) { logger.warn("Error decoding HTTP Basic Auth base64 credentials."); } } return usernameAndPassword; } public static String urlEncode(String urlSnippet, String characterEncoding) { if (urlSnippet == null) { return null; } String encodedUrlSnippet = ""; try { encodedUrlSnippet = URLEncoder.encode(urlSnippet, characterEncoding); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/web_utils/HttpUtils.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.net.URLEncoder; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; int colonIndex = credentialsString.indexOf(':'); if ((colonIndex > -1) && (colonIndex < (credentialsString.length() - 1))) { String username = credentialsString.substring(0, colonIndex); String password = credentialsString.substring(colonIndex + 1, credentialsString.length()); usernameAndPassword[0] = username; usernameAndPassword[1] = password; } } catch (Exception e) { logger.warn("Error decoding HTTP Basic Auth base64 credentials."); } } return usernameAndPassword; } public static String urlEncode(String urlSnippet, String characterEncoding) { if (urlSnippet == null) { return null; } String encodedUrlSnippet = ""; try { encodedUrlSnippet = URLEncoder.encode(urlSnippet, characterEncoding); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/db_utils/DatabaseUtils.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.math.BigDecimal; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.RowId; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
cleanup(null, preparedStatement, null, null, CLOSE); } public static void cleanup(PreparedStatement preparedStatement, ResultSet results) { cleanup(null, preparedStatement, null, results, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement) { cleanup(connection, preparedStatement, null, null, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, byte closeMode) { cleanup(connection, preparedStatement, null, null, closeMode); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, ResultSet results) { cleanup(connection, preparedStatement, null, results, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, ResultSet results, byte closeMode) { cleanup(connection, preparedStatement, null, results, closeMode); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, Statement statement, ResultSet results, byte closeMode) { if (results != null) { try { results.close(); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/db_utils/DatabaseUtils.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.math.BigDecimal; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.RowId; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; cleanup(null, preparedStatement, null, null, CLOSE); } public static void cleanup(PreparedStatement preparedStatement, ResultSet results) { cleanup(null, preparedStatement, null, results, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement) { cleanup(connection, preparedStatement, null, null, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, byte closeMode) { cleanup(connection, preparedStatement, null, null, closeMode); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, ResultSet results) { cleanup(connection, preparedStatement, null, results, CLOSE); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, ResultSet results, byte closeMode) { cleanup(connection, preparedStatement, null, results, closeMode); } public static void cleanup(Connection connection, PreparedStatement preparedStatement, Statement statement, ResultSet results, byte closeMode) { if (results != null) { try { results.close(); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/network_utils/TcpClient.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
private DataOutputStream dataOutputStream_ = null; public TcpClient(String host, int port, boolean connectImmediately, int socketConnectionTimeoutInMs) { this.host_ = host; this.port_ = port; this.socketConnectionTimeoutInMs_ = socketConnectionTimeoutInMs; if (connectImmediately) { connect(); } } public boolean reset() { close(); return connect(); } public boolean connect() { boolean isConnectSuccess; try { socket_ = new Socket(); socket_.connect(new InetSocketAddress(host_, port_), socketConnectionTimeoutInMs_); dataOutputStream_ = new DataOutputStream(socket_.getOutputStream()); bufferedWriter_ = new BufferedWriter(new OutputStreamWriter(dataOutputStream_)); isConnectSuccess = isConnected(); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/network_utils/TcpClient.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; private DataOutputStream dataOutputStream_ = null; public TcpClient(String host, int port, boolean connectImmediately, int socketConnectionTimeoutInMs) { this.host_ = host; this.port_ = port; this.socketConnectionTimeoutInMs_ = socketConnectionTimeoutInMs; if (connectImmediately) { connect(); } } public boolean reset() { close(); return connect(); } public boolean connect() { boolean isConnectSuccess; try { socket_ = new Socket(); socket_.connect(new InetSocketAddress(host_, port_), socketConnectionTimeoutInMs_); dataOutputStream_ = new DataOutputStream(socket_.getOutputStream()); bufferedWriter_ = new BufferedWriter(new OutputStreamWriter(dataOutputStream_)); isConnectSuccess = isConnected(); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/time_utils/DateAndTime.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.utilities.time_utils; /** * @author Jeffrey Schmidt */ public class DateAndTime { private static final Logger logger = LoggerFactory.getLogger(DateAndTime.class.getName()); public static final int COMPARE_ERROR_CODE = -44444444; public static String getFormattedCurrentDateAndTime(String simpleDateFormat) { if (simpleDateFormat == null) { return null; } try { DateFormat dateFormat = new SimpleDateFormat(simpleDateFormat); Date currentSystemDateAndTime = new Date(); return dateFormat.format(currentSystemDateAndTime); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/time_utils/DateAndTime.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.utilities.time_utils; /** * @author Jeffrey Schmidt */ public class DateAndTime { private static final Logger logger = LoggerFactory.getLogger(DateAndTime.class.getName()); public static final int COMPARE_ERROR_CODE = -44444444; public static String getFormattedCurrentDateAndTime(String simpleDateFormat) { if (simpleDateFormat == null) { return null; } try { DateFormat dateFormat = new SimpleDateFormat(simpleDateFormat); Date currentSystemDateAndTime = new Date(); return dateFormat.format(currentSystemDateAndTime); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/string_utils/StringUtilities.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.utilities.string_utils; /** * @author Jeffrey Schmidt */ public class StringUtilities { private static final Logger logger = LoggerFactory.getLogger(StringUtilities.class.getName()); private static final Map<String,Charset> charsetCache = new ConcurrentHashMap<>(); public static Charset getCharsetFromString(String charset) { if (charset == null) { return null; } Charset charsetToUse; try { charsetToUse = charsetCache.get(charset); if (charsetToUse == null) { charsetToUse = Charset.availableCharsets().get(charset); if (charsetToUse == null) { logger.warn("Couldn't find Charset \"" + removeNewlinesFromString(charset) + "\". Using default charset."); charsetToUse = Charset.defaultCharset(); } else charsetCache.put(charset, charsetToUse); } } catch (Exception e) { logger.error("Error using Charset \"" + removeNewlinesFromString(charset) + "\". Using default charset." +
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/string_utils/StringUtilities.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.utilities.string_utils; /** * @author Jeffrey Schmidt */ public class StringUtilities { private static final Logger logger = LoggerFactory.getLogger(StringUtilities.class.getName()); private static final Map<String,Charset> charsetCache = new ConcurrentHashMap<>(); public static Charset getCharsetFromString(String charset) { if (charset == null) { return null; } Charset charsetToUse; try { charsetToUse = charsetCache.get(charset); if (charsetToUse == null) { charsetToUse = Charset.availableCharsets().get(charset); if (charsetToUse == null) { logger.warn("Couldn't find Charset \"" + removeNewlinesFromString(charset) + "\". Using default charset."); charsetToUse = Charset.defaultCharset(); } else charsetCache.put(charset, charsetToUse); } } catch (Exception e) { logger.error("Error using Charset \"" + removeNewlinesFromString(charset) + "\". Using default charset." +
e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/json_utils/JsonUtils.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.pearson.statspoller.utilities.core_utils.StackTrace; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.utilities.json_utils; /** * @author Jeffrey Schmidt */ public class JsonUtils { private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class.getName()); public static Integer getIntegerFieldFromJsonObject(JsonObject jsonObject, String fieldName) { if (jsonObject == null) { return null; } Integer returnInteger = null; try { JsonElement jsonElement = jsonObject.get(fieldName); if (jsonElement != null) returnInteger = jsonElement.getAsInt(); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/json_utils/JsonUtils.java import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.pearson.statspoller.utilities.core_utils.StackTrace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.utilities.json_utils; /** * @author Jeffrey Schmidt */ public class JsonUtils { private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class.getName()); public static Integer getIntegerFieldFromJsonObject(JsonObject jsonObject, String fieldName) { if (jsonObject == null) { return null; } Integer returnInteger = null; try { JsonElement jsonElement = jsonObject.get(fieldName); if (jsonElement != null) returnInteger = jsonElement.getAsInt(); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/utilities/os_utils/ProcessUtils.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.BufferedReader; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.utilities.os_utils; /** * @author Jeffrey Schmidt */ public class ProcessUtils { private static final Logger logger = LoggerFactory.getLogger(ProcessUtils.class.getName()); public static String runProcessAndGetProcessOutput(String commands) { String output = null; try { String[] commandAndArgs = commands.split(" "); ProcessBuilder processBuilder = new ProcessBuilder().command(commandAndArgs); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder processOutput = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { processOutput.append(line); processOutput.append(System.getProperty("line.separator")); } output = processOutput.toString(); } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/utilities/os_utils/ProcessUtils.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.BufferedReader; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.utilities.os_utils; /** * @author Jeffrey Schmidt */ public class ProcessUtils { private static final Logger logger = LoggerFactory.getLogger(ProcessUtils.class.getName()); public static String runProcessAndGetProcessOutput(String commands) { String output = null; try { String[] commandAndArgs = commands.split(" "); ProcessBuilder processBuilder = new ProcessBuilder().command(commandAndArgs); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder processOutput = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { processOutput.append(line); processOutput.append(System.getProperty("line.separator")); } output = processOutput.toString(); } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
PearsonEducation/StatsPoller
src/main/java/com/pearson/statspoller/external_metric_collectors/ExternalMetricCollector.java
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // }
import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.pearson.statspoller.external_metric_collectors; /** * @author Jeffrey Schmidt */ public class ExternalMetricCollector { private static final Logger logger = LoggerFactory.getLogger(ExternalMetricCollector.class.getName()); private final String programPathAndFilename_; private final long collectionIntervalInMs_; private final String outputPathAndFilename_; private final String metricPrefix_; public ExternalMetricCollector(String programPathAndFilename, long collectionIntervalInMs, String outputPathAndFilename, String metricPrefix) { this.programPathAndFilename_ = programPathAndFilename; this.collectionIntervalInMs_ = collectionIntervalInMs; this.outputPathAndFilename_ = outputPathAndFilename; this.metricPrefix_ = metricPrefix; } public File getFileFromProgramPathAndFilename() { try { File file = new File(programPathAndFilename_); return file; } catch (Exception e) {
// Path: src/main/java/com/pearson/statspoller/utilities/core_utils/StackTrace.java // public class StackTrace { // // private static final Logger logger = LoggerFactory.getLogger(StackTrace.class.getName()); // // public static String getStringFromStackTrace(Exception exception) { // try { // StringWriter stringWriter = new StringWriter(); // PrintWriter printWriter = new PrintWriter(stringWriter); // // exception.printStackTrace(printWriter); // // return stringWriter.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // public static String getStringFromStackTrace(StackTraceElement[] stackTraceElements) { // try { // // StringBuilder stackTrace = new StringBuilder(); // // for (StackTraceElement stackTraceElement : stackTraceElements) { // stackTrace.append(stackTraceElement).append(System.lineSeparator()); // } // // return stackTrace.toString(); // } // catch (Exception e) { // logger.error(e.toString() + " - Failed to convert stack-trace to string"); // return null; // } // } // // } // Path: src/main/java/com/pearson/statspoller/external_metric_collectors/ExternalMetricCollector.java import com.pearson.statspoller.utilities.core_utils.StackTrace; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.pearson.statspoller.external_metric_collectors; /** * @author Jeffrey Schmidt */ public class ExternalMetricCollector { private static final Logger logger = LoggerFactory.getLogger(ExternalMetricCollector.class.getName()); private final String programPathAndFilename_; private final long collectionIntervalInMs_; private final String outputPathAndFilename_; private final String metricPrefix_; public ExternalMetricCollector(String programPathAndFilename, long collectionIntervalInMs, String outputPathAndFilename, String metricPrefix) { this.programPathAndFilename_ = programPathAndFilename; this.collectionIntervalInMs_ = collectionIntervalInMs; this.outputPathAndFilename_ = outputPathAndFilename; this.metricPrefix_ = metricPrefix; } public File getFileFromProgramPathAndFilename() { try { File file = new File(programPathAndFilename_); return file; } catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/BitBucketFileMetadata.java
// Path: src/main/java/org/springframework/social/bitbucket/api/impl/UTCDateDeserializer.java // public class UTCDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, // Locale.ENGLISH); // dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // return dateFormat.parse(jp.getText()); // } catch (ParseException e) { // throw new JsonParseException("Can't parse date : " + jp.getText(), // jp.getCurrentLocation()); // } // } // // /** // * JDK can't parse a TZ with a colon. Assume it will be +00:00. // */ // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // }
import java.util.Date; import org.springframework.social.bitbucket.api.impl.UTCDateDeserializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/** * Copyright 2012 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.social.bitbucket.api; /** * Metadata about a file in a repository. * * @author Eric Bottard */ @JsonIgnoreProperties(ignoreUnknown = true) public class BitBucketFileMetadata { @JsonProperty private String path; @JsonProperty private String revision; @JsonProperty("utctimestamp")
// Path: src/main/java/org/springframework/social/bitbucket/api/impl/UTCDateDeserializer.java // public class UTCDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, // Locale.ENGLISH); // dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // return dateFormat.parse(jp.getText()); // } catch (ParseException e) { // throw new JsonParseException("Can't parse date : " + jp.getText(), // jp.getCurrentLocation()); // } // } // // /** // * JDK can't parse a TZ with a colon. Assume it will be +00:00. // */ // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // } // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketFileMetadata.java import java.util.Date; import org.springframework.social.bitbucket.api.impl.UTCDateDeserializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Copyright 2012 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.social.bitbucket.api; /** * Metadata about a file in a repository. * * @author Eric Bottard */ @JsonIgnoreProperties(ignoreUnknown = true) public class BitBucketFileMetadata { @JsonProperty private String path; @JsonProperty private String revision; @JsonProperty("utctimestamp")
@JsonDeserialize(using = UTCDateDeserializer.class)
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // }
import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.security.provider.OAuth1AuthenticationService; import org.springframework.social.security.provider.SocialAuthenticationService;
/* * Copyright 2013 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.social.bitbucket.security; /** * {@link SocialAuthenticationService} implementation for BitBucket. * * @author Eric Bottard */ public class BitBucketAuthenticationService extends OAuth1AuthenticationService<BitBucket> { public BitBucketAuthenticationService(String apiKey, String appSecret) {
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.security.provider.OAuth1AuthenticationService; import org.springframework.social.security.provider.SocialAuthenticationService; /* * Copyright 2013 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.social.bitbucket.security; /** * {@link SocialAuthenticationService} implementation for BitBucket. * * @author Eric Bottard */ public class BitBucketAuthenticationService extends OAuth1AuthenticationService<BitBucket> { public BitBucketAuthenticationService(String apiKey, String appSecret) {
super(new BitBucketConnectionFactory(apiKey, appSecret));
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/UserTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // }
import java.util.List; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.bitbucket.api.UserWithRepositories; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty;
/** * Copyright 2012 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.social.bitbucket.api.impl; class UserTemplate extends AbstractBitBucketOperations implements UserOperations { public UserTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/UserTemplate.java import java.util.List; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.bitbucket.api.UserWithRepositories; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Copyright 2012 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.social.bitbucket.api.impl; class UserTemplate extends AbstractBitBucketOperations implements UserOperations { public UserTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override
public UserWithRepositories getUserWithRepositories() {
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/UserTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // }
import java.util.List; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.bitbucket.api.UserWithRepositories; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty;
/** * Copyright 2012 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.social.bitbucket.api.impl; class UserTemplate extends AbstractBitBucketOperations implements UserOperations { public UserTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override public UserWithRepositories getUserWithRepositories() { return restTemplate.getForObject(buildUrl("/user"), UserWithRepositories.class); } @Override
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/UserTemplate.java import java.util.List; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.bitbucket.api.UserWithRepositories; import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Copyright 2012 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.social.bitbucket.api.impl; class UserTemplate extends AbstractBitBucketOperations implements UserOperations { public UserTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override public UserWithRepositories getUserWithRepositories() { return restTemplate.getForObject(buildUrl("/user"), UserWithRepositories.class); } @Override
public List<BitBucketUser> getFollowers(String user) {
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/BitBucketRepository.java
// Path: src/main/java/org/springframework/social/bitbucket/api/impl/UTCDateDeserializer.java // public class UTCDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, // Locale.ENGLISH); // dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // return dateFormat.parse(jp.getText()); // } catch (ParseException e) { // throw new JsonParseException("Can't parse date : " + jp.getText(), // jp.getCurrentLocation()); // } // } // // /** // * JDK can't parse a TZ with a colon. Assume it will be +00:00. // */ // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // }
import java.io.Serializable; import java.util.Date; import org.springframework.social.bitbucket.api.impl.UTCDateDeserializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
/** * Copyright 2012 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.social.bitbucket.api; /** * A BitBucket repository, possibly with additional metadata. * * @author ericbottard * */ @JsonIgnoreProperties(ignoreUnknown = true) public class BitBucketRepository implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("is_private") private boolean _private; @JsonProperty("utc_created_on")
// Path: src/main/java/org/springframework/social/bitbucket/api/impl/UTCDateDeserializer.java // public class UTCDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jp, DeserializationContext ctxt) // throws IOException, JsonProcessingException { // try { // SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, // Locale.ENGLISH); // dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // return dateFormat.parse(jp.getText()); // } catch (ParseException e) { // throw new JsonParseException("Can't parse date : " + jp.getText(), // jp.getCurrentLocation()); // } // } // // /** // * JDK can't parse a TZ with a colon. Assume it will be +00:00. // */ // private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // // } // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketRepository.java import java.io.Serializable; import java.util.Date; import org.springframework.social.bitbucket.api.impl.UTCDateDeserializer; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * Copyright 2012 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.social.bitbucket.api; /** * A BitBucket repository, possibly with additional metadata. * * @author ericbottard * */ @JsonIgnoreProperties(ignoreUnknown = true) public class BitBucketRepository implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("is_private") private boolean _private; @JsonProperty("utc_created_on")
@JsonDeserialize(using = UTCDateDeserializer.class)
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/connect/BitBucketAdapter.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // }
import org.springframework.social.ApiException; import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.connect.ApiAdapter; import org.springframework.social.connect.ConnectionValues; import org.springframework.social.connect.UserProfile; import org.springframework.social.connect.UserProfileBuilder;
/** * Copyright 2012 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.social.bitbucket.connect; public class BitBucketAdapter implements ApiAdapter<BitBucket> { @Override public boolean test(BitBucket api) { try { if (null != api.userOperations().getUserWithRepositories()) { return true; } else { return false; } } catch (ApiException e) { return false; } } @Override public void setConnectionValues(BitBucket api, ConnectionValues values) {
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketAdapter.java import org.springframework.social.ApiException; import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.connect.ApiAdapter; import org.springframework.social.connect.ConnectionValues; import org.springframework.social.connect.UserProfile; import org.springframework.social.connect.UserProfileBuilder; /** * Copyright 2012 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.social.bitbucket.connect; public class BitBucketAdapter implements ApiAdapter<BitBucket> { @Override public boolean test(BitBucket api) { try { if (null != api.userOperations().getUserWithRepositories()) { return true; } else { return false; } } catch (ApiException e) { return false; } } @Override public void setConnectionValues(BitBucket api, ConnectionValues values) {
BitBucketUser user = api.userOperations().getUserWithRepositories()
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/connect/BitBucketServiceProvider.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java // public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements // BitBucket { // // private UserOperations userOperations; // // private RepoOperations repoOperations; // // private PrivilegeOperations privilegeOperations; // // public BitBucketTemplate(String consumerKey, String consumerSecret, // String accessToken, String accessTokenSecret) { // super(consumerKey, consumerSecret, accessToken, accessTokenSecret); // initSubApis(); // } // // public BitBucketTemplate() { // super(); // initSubApis(); // } // // private void initSubApis() { // userOperations = new UserTemplate(getRestTemplate(), isAuthorized()); // repoOperations = new RepoTemplate(getRestTemplate(), isAuthorized()); // privilegeOperations = new PrivilegeTemplate(getRestTemplate(), // isAuthorized()); // } // // @Override // public RepoOperations repoOperations() { // return repoOperations; // } // // @Override // public UserOperations userOperations() { // return userOperations; // } // // @Override // public PrivilegeOperations privelegesOperations() { // return privilegeOperations; // } // // }
import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.impl.BitBucketTemplate; import org.springframework.social.oauth1.AbstractOAuth1ServiceProvider; import org.springframework.social.oauth1.OAuth1Template;
/** * Copyright 2012 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.social.bitbucket.connect; public class BitBucketServiceProvider extends AbstractOAuth1ServiceProvider<BitBucket> { public BitBucketServiceProvider(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret, new OAuth1Template(consumerKey, consumerSecret, "https://bitbucket.org/!api/1.0/oauth/request_token", "https://bitbucket.org/!api/1.0/oauth/authenticate", "https://bitbucket.org/!api/1.0/oauth/access_token")); } @Override public BitBucket getApi(String accessToken, String secret) {
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java // public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements // BitBucket { // // private UserOperations userOperations; // // private RepoOperations repoOperations; // // private PrivilegeOperations privilegeOperations; // // public BitBucketTemplate(String consumerKey, String consumerSecret, // String accessToken, String accessTokenSecret) { // super(consumerKey, consumerSecret, accessToken, accessTokenSecret); // initSubApis(); // } // // public BitBucketTemplate() { // super(); // initSubApis(); // } // // private void initSubApis() { // userOperations = new UserTemplate(getRestTemplate(), isAuthorized()); // repoOperations = new RepoTemplate(getRestTemplate(), isAuthorized()); // privilegeOperations = new PrivilegeTemplate(getRestTemplate(), // isAuthorized()); // } // // @Override // public RepoOperations repoOperations() { // return repoOperations; // } // // @Override // public UserOperations userOperations() { // return userOperations; // } // // @Override // public PrivilegeOperations privelegesOperations() { // return privilegeOperations; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketServiceProvider.java import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.impl.BitBucketTemplate; import org.springframework.social.oauth1.AbstractOAuth1ServiceProvider; import org.springframework.social.oauth1.OAuth1Template; /** * Copyright 2012 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.social.bitbucket.connect; public class BitBucketServiceProvider extends AbstractOAuth1ServiceProvider<BitBucket> { public BitBucketServiceProvider(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret, new OAuth1Template(consumerKey, consumerSecret, "https://bitbucket.org/!api/1.0/oauth/request_token", "https://bitbucket.org/!api/1.0/oauth/authenticate", "https://bitbucket.org/!api/1.0/oauth/access_token")); } @Override public BitBucket getApi(String accessToken, String secret) {
return new BitBucketTemplate(getConsumerKey(), getConsumerSecret(),
ericbottard/spring-social-bitbucket
src/test/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplateTest.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // }
import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.util.List; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.RepoPrivilege;
package org.springframework.social.bitbucket.api.impl; public class PrivilegeTemplateTest extends BaseTemplateTest { @Test public void testGetRepoPrivileges() { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/privileges/evzijst/test")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-repo-privileges"), MediaType.APPLICATION_JSON));
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/test/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplateTest.java import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.util.List; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.RepoPrivilege; package org.springframework.social.bitbucket.api.impl; public class PrivilegeTemplateTest extends BaseTemplateTest { @Test public void testGetRepoPrivileges() { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/privileges/evzijst/test")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-repo-privileges"), MediaType.APPLICATION_JSON));
List<RepoPrivilege> privs = bitBucket.privelegesOperations()
ericbottard/spring-social-bitbucket
src/test/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplateTest.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // }
import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.util.List; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.RepoPrivilege;
package org.springframework.social.bitbucket.api.impl; public class PrivilegeTemplateTest extends BaseTemplateTest { @Test public void testGetRepoPrivileges() { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/privileges/evzijst/test")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-repo-privileges"), MediaType.APPLICATION_JSON)); List<RepoPrivilege> privs = bitBucket.privelegesOperations() .getRepoPrivileges("evzijst", "test"); assertEquals(4, privs.size()); assertEquals("evzijst/test", privs.get(0).getRepository()); assertEquals("jespern", privs.get(0).getUser().getUsername());
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/test/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplateTest.java import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.util.List; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.RepoPrivilege; package org.springframework.social.bitbucket.api.impl; public class PrivilegeTemplateTest extends BaseTemplateTest { @Test public void testGetRepoPrivileges() { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/privileges/evzijst/test")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-repo-privileges"), MediaType.APPLICATION_JSON)); List<RepoPrivilege> privs = bitBucket.privelegesOperations() .getRepoPrivileges("evzijst", "test"); assertEquals(4, privs.size()); assertEquals("evzijst/test", privs.get(0).getRepository()); assertEquals("jespern", privs.get(0).getUser().getUsername());
assertEquals(BitBucketPrivilege.read, privs.get(0).getPrivilege());
ericbottard/spring-social-bitbucket
src/test/java/org/springframework/social/bitbucket/api/impl/UserTemplateTest.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketRepository.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketRepository implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty("is_private") // private boolean _private; // // @JsonProperty("utc_created_on") // @JsonDeserialize(using = UTCDateDeserializer.class) // private Date createdAt; // // @JsonProperty // private String description; // // @JsonProperty("has_wiki") // private boolean hasWiki; // // @JsonProperty("utc_last_updated") // @JsonDeserialize(using = UTCDateDeserializer.class) // private Date lastUpdatedOn; // // @JsonProperty // private String name; // // @JsonProperty // private String owner; // // @JsonProperty("read_only") // private boolean readOnly; // // @JsonProperty // private BitBucketSCM scm; // // @JsonProperty // private long size; // // @JsonProperty // private String slug; // // /** // * The date when the repository was created. // */ // public Date getCreatedAt() { // return createdAt; // } // // /** // * A description of the repository, as entered by its creator. // */ // public String getDescription() { // return description; // } // // /** // * When this repository was last updated. // * // */ // public Date getLastUpdatedOn() { // return lastUpdatedOn; // } // // /** // * A user friendly name for this repository (may differ from its // * {@link #getSlug() slug}). // * // */ // public String getName() { // return name; // } // // /** // * The username of the repository owner. // */ // public String getOwner() { // return owner; // } // // /** // * The source control management system this repository uses. // */ // public BitBucketSCM getScm() { // return scm; // } // // /** // * The size of this repository, in bytes. // */ // public long getSize() { // return size; // } // // /** // * This repository's "slug", <i>ie.</i> its technical id in BitBucket terms. // */ // public String getSlug() { // return slug; // } // // /** // * Whether this repository has an attached wiki. // */ // public boolean isHasWiki() { // return hasWiki; // } // // /** // * Whether this repository is private (authenticated user needs access to // * it) or is for everyone to see. // */ // public boolean isPrivate() { // return _private; // } // // public boolean isReadOnly() { // return readOnly; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketSCM.java // public enum BitBucketSCM { // // /** // * Mercurial. // */ // hg, // // /** // * Git. // */ // git; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // }
import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketRepository; import org.springframework.social.bitbucket.api.BitBucketSCM; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserWithRepositories;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class UserTemplateTest extends BaseTemplateTest { @Test public void testGetUser() throws Exception { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/user")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-user"), MediaType.APPLICATION_JSON));
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketRepository.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketRepository implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty("is_private") // private boolean _private; // // @JsonProperty("utc_created_on") // @JsonDeserialize(using = UTCDateDeserializer.class) // private Date createdAt; // // @JsonProperty // private String description; // // @JsonProperty("has_wiki") // private boolean hasWiki; // // @JsonProperty("utc_last_updated") // @JsonDeserialize(using = UTCDateDeserializer.class) // private Date lastUpdatedOn; // // @JsonProperty // private String name; // // @JsonProperty // private String owner; // // @JsonProperty("read_only") // private boolean readOnly; // // @JsonProperty // private BitBucketSCM scm; // // @JsonProperty // private long size; // // @JsonProperty // private String slug; // // /** // * The date when the repository was created. // */ // public Date getCreatedAt() { // return createdAt; // } // // /** // * A description of the repository, as entered by its creator. // */ // public String getDescription() { // return description; // } // // /** // * When this repository was last updated. // * // */ // public Date getLastUpdatedOn() { // return lastUpdatedOn; // } // // /** // * A user friendly name for this repository (may differ from its // * {@link #getSlug() slug}). // * // */ // public String getName() { // return name; // } // // /** // * The username of the repository owner. // */ // public String getOwner() { // return owner; // } // // /** // * The source control management system this repository uses. // */ // public BitBucketSCM getScm() { // return scm; // } // // /** // * The size of this repository, in bytes. // */ // public long getSize() { // return size; // } // // /** // * This repository's "slug", <i>ie.</i> its technical id in BitBucket terms. // */ // public String getSlug() { // return slug; // } // // /** // * Whether this repository has an attached wiki. // */ // public boolean isHasWiki() { // return hasWiki; // } // // /** // * Whether this repository is private (authenticated user needs access to // * it) or is for everyone to see. // */ // public boolean isPrivate() { // return _private; // } // // public boolean isReadOnly() { // return readOnly; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketSCM.java // public enum BitBucketSCM { // // /** // * Mercurial. // */ // hg, // // /** // * Git. // */ // git; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketUser.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class BitBucketUser implements Serializable { // // private static final long serialVersionUID = 1L; // // @JsonProperty // private String username; // // @JsonProperty("first_name") // private String firstName; // // @JsonProperty("last_name") // private String lastName; // // @JsonProperty("avatar") // private String avatarImageUrl; // // public String getUsername() { // return username; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // public String getAvatarImageUrl() { // return avatarImageUrl; // } // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserWithRepositories.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class UserWithRepositories { // // @JsonProperty // private BitBucketUser user; // // @JsonProperty // private List<BitBucketRepository> repositories; // // public List<BitBucketRepository> getRepositories() { // return repositories; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/test/java/org/springframework/social/bitbucket/api/impl/UserTemplateTest.java import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.*; import static org.springframework.test.web.client.match.MockRestRequestMatchers.*; import static org.springframework.test.web.client.response.MockRestResponseCreators.*; import java.text.SimpleDateFormat; import java.util.List; import java.util.TimeZone; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.social.bitbucket.api.BitBucketRepository; import org.springframework.social.bitbucket.api.BitBucketSCM; import org.springframework.social.bitbucket.api.BitBucketUser; import org.springframework.social.bitbucket.api.UserWithRepositories; /** * Copyright 2012 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.social.bitbucket.api.impl; public class UserTemplateTest extends BaseTemplateTest { @Test public void testGetUser() throws Exception { mockServer .expect(requestTo("https://api.bitbucket.org/1.0/user")) .andExpect(method(GET)) .andRespond( withSuccess(jsonResource("get-user"), MediaType.APPLICATION_JSON));
UserWithRepositories profile = bitBucket.userOperations()
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService;
/* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() {
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService; /* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() {
super(BitBucketConnectionFactory.class, BitBucketApiHelper.class);
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService;
/* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() {
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService; /* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() {
super(BitBucketConnectionFactory.class, BitBucketApiHelper.class);
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService;
/* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() { super(BitBucketConnectionFactory.class, BitBucketApiHelper.class); } @Override protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/xml/BitBucketConfigBeanDefinitionParser.java import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.security.provider.SocialAuthenticationService; /* * Copyright 2013 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.social.bitbucket.config.xml; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that * creates a {@link BitBucketConnectionFactory}. * * @author Eric Bottard */ public class BitBucketConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public BitBucketConfigBeanDefinitionParser() { super(BitBucketConnectionFactory.class, BitBucketApiHelper.class); } @Override protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
return BitBucketAuthenticationService.class;
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // }
import static java.util.Arrays.*; import java.util.List; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoPrivilege; import org.springframework.web.client.RestTemplate;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class PrivilegeTemplate extends AbstractBitBucketOperations implements PrivilegeOperations { public PrivilegeTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplate.java import static java.util.Arrays.*; import java.util.List; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoPrivilege; import org.springframework.web.client.RestTemplate; /** * Copyright 2012 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.social.bitbucket.api.impl; public class PrivilegeTemplate extends AbstractBitBucketOperations implements PrivilegeOperations { public PrivilegeTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override
public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug) {
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // }
import static java.util.Arrays.*; import java.util.List; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoPrivilege; import org.springframework.web.client.RestTemplate;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class PrivilegeTemplate extends AbstractBitBucketOperations implements PrivilegeOperations { public PrivilegeTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug) { return asList(restTemplate.getForObject( buildUrl("/privileges/{user}/{repo_slug}"), RepoPrivilege[].class, user, repoSlug)); } @Override public RepoPrivilege setPrivilege(String owner, String repoSlug,
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucketPrivilege.java // public enum BitBucketPrivilege { // // read, write, admin; // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoPrivilege.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class RepoPrivilege { // // @JsonProperty("repo") // private String repository; // // @JsonProperty // private BitBucketPrivilege privilege; // // @JsonProperty // private BitBucketUser user; // // public String getRepository() { // return repository; // } // // public BitBucketPrivilege getPrivilege() { // return privilege; // } // // public BitBucketUser getUser() { // return user; // } // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/PrivilegeTemplate.java import static java.util.Arrays.*; import java.util.List; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.social.bitbucket.api.BitBucketPrivilege; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoPrivilege; import org.springframework.web.client.RestTemplate; /** * Copyright 2012 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.social.bitbucket.api.impl; public class PrivilegeTemplate extends AbstractBitBucketOperations implements PrivilegeOperations { public PrivilegeTemplate(RestTemplate restTemplate, boolean authorized) { super(restTemplate, authorized); } @Override public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug) { return asList(restTemplate.getForObject( buildUrl("/privileges/{user}/{repo_slug}"), RepoPrivilege[].class, user, repoSlug)); } @Override public RepoPrivilege setPrivilege(String owner, String repoSlug,
String recipient, BitBucketPrivilege privilege) {
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // }
import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket {
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding; /** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket {
private UserOperations userOperations;
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // }
import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket { private UserOperations userOperations;
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding; /** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket { private UserOperations userOperations;
private RepoOperations repoOperations;
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // }
import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding;
/** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket { private UserOperations userOperations; private RepoOperations repoOperations;
// Path: src/main/java/org/springframework/social/bitbucket/api/BitBucket.java // public interface BitBucket extends ApiBinding { // // /** // * Returns the portion of the BitBucket API that allow interaction with // * repositories. // */ // RepoOperations repoOperations(); // // /** // * Returns the portion of the BitBucket API that allow interaction with user // * accounts. // */ // UserOperations userOperations(); // // /** // * Returns the portion of the BitBucket API that allow messing with // * privileges. // */ // PrivilegeOperations privelegesOperations(); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/PrivilegeOperations.java // public interface PrivilegeOperations { // // /** // * Get the privileges on a given repository. // * // * @param user // * repository owner // * @param repoSlug // * name of the repository // */ // public List<RepoPrivilege> getRepoPrivileges(String user, String repoSlug); // // /** // * Set or change the privilege for the given recipient on some repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to set the privilege // * @param privilege // * new privilege value to set // */ // public RepoPrivilege setPrivilege(String owner, String repoSlug, // String recipient, BitBucketPrivilege privilege); // // /** // * Removes the current privilege of the given recipient from some // * repository. // * // * @param owner // * the repository owner // * @param repoSlug // * the repository name // * @param recipient // * user for which to remove the privilege // */ // public void removePrivilege(String owner, String repoSlug, String recipient); // // } // // Path: src/main/java/org/springframework/social/bitbucket/api/RepoOperations.java // public interface RepoOperations { // // /** // * Returns the public repository that belongs to {@code user} and that has // * {@code repoSlug} as its technical name. // */ // public BitBucketRepository getRepository(String user, String repoSlug); // // /** // * Returns the list of repositories for the current user. // */ // public List<BitBucketRepository> getUserRepositories(); // // /** // * Search for public repositories whose name contains the given String. // */ // public List<BitBucketRepository> search(String string); // // /** // * Returns a mapping between tags (keys) and changesets (values) on the // * given repository. // */ // public Map<String, BitBucketChangeset> getTags(String user, String repoSlug); // // /** // * Returns the list of users following the given repository. // */ // public List<BitBucketUser> getFollowers(String user, String repoSlug); // // /** // * Returns the last changesets on a repository, as well as information about // * how many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug); // // /** // * Returns some changesets on a repository, as well as information about how // * many are available totally. // */ // public BitBucketChangesets getChangesets(String user, String repoSlug, // String start, int limit); // // /** // * Returns information about a known directory, including children // * directories and files. // */ // public BitBucketDirectory getDirectory(String user, String repoSlug, // String revision, String path); // // /** // * Returns information and actual contents (as a String) about a known file // * path. // */ // public BitBucketFile getFile(String string, String string2, String string3, // String string4); // // /** // * Creates a new repository under the account of the currently authenticated // * user. The account automatically becomes the owner. // */ // public BitBucketRepository createRepository(RepoCreation options); // } // // Path: src/main/java/org/springframework/social/bitbucket/api/UserOperations.java // public interface UserOperations { // // /** // * Returns information about the current user, as well as the list of // * repositories he/she owns. // */ // UserWithRepositories getUserWithRepositories(); // // /** // * Returns the list of users that follow the given {@code user}. // */ // List<BitBucketUser> getFollowers(String user); // // } // Path: src/main/java/org/springframework/social/bitbucket/api/impl/BitBucketTemplate.java import org.springframework.social.bitbucket.api.BitBucket; import org.springframework.social.bitbucket.api.PrivilegeOperations; import org.springframework.social.bitbucket.api.RepoOperations; import org.springframework.social.bitbucket.api.UserOperations; import org.springframework.social.oauth1.AbstractOAuth1ApiBinding; /** * Copyright 2012 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.social.bitbucket.api.impl; public class BitBucketTemplate extends AbstractOAuth1ApiBinding implements BitBucket { private UserOperations userOperations; private RepoOperations repoOperations;
private PrivilegeOperations privilegeOperations;
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService;
package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() {
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService; package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() {
super(EnableBitBucket.class, BitBucketConnectionFactory.class,
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService;
package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() { super(EnableBitBucket.class, BitBucketConnectionFactory.class,
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService; package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() { super(EnableBitBucket.class, BitBucketConnectionFactory.class,
BitBucketApiHelper.class);
ericbottard/spring-social-bitbucket
src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // }
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService;
package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() { super(EnableBitBucket.class, BitBucketConnectionFactory.class, BitBucketApiHelper.class); } @Override protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
// Path: src/main/java/org/springframework/social/bitbucket/config/support/BitBucketApiHelper.java // public class BitBucketApiHelper implements ApiHelper<BitBucket> { // private final UsersConnectionRepository usersConnectionRepository; // // private final UserIdSource userIdSource; // // private BitBucketApiHelper( // UsersConnectionRepository usersConnectionRepository, // UserIdSource userIdSource) { // this.usersConnectionRepository = usersConnectionRepository; // this.userIdSource = userIdSource; // } // // @Override // public BitBucket getApi() { // if (logger.isDebugEnabled()) { // logger.debug("Getting API binding instance for BitBucket"); // } // // Connection<BitBucket> connection = usersConnectionRepository // .createConnectionRepository(userIdSource.getUserId()) // .findPrimaryConnection(BitBucket.class); // if (logger.isDebugEnabled() && connection == null) { // logger.debug("No current connection; Returning default BitBucketTemplate instance."); // } // return connection != null ? connection.getApi() : null; // } // // private final static Log logger = LogFactory // .getLog(BitBucketApiHelper.class); // } // // Path: src/main/java/org/springframework/social/bitbucket/connect/BitBucketConnectionFactory.java // public class BitBucketConnectionFactory extends // OAuth1ConnectionFactory<BitBucket> { // // public BitBucketConnectionFactory(String consumerKey, String consumerSecret) { // super("bitbucket", new BitBucketServiceProvider(consumerKey, // consumerSecret), new BitBucketAdapter()); // } // } // // Path: src/main/java/org/springframework/social/bitbucket/security/BitBucketAuthenticationService.java // public class BitBucketAuthenticationService extends // OAuth1AuthenticationService<BitBucket> { // // public BitBucketAuthenticationService(String apiKey, String appSecret) { // super(new BitBucketConnectionFactory(apiKey, appSecret)); // } // // } // Path: src/main/java/org/springframework/social/bitbucket/config/annotation/TwitterProviderConfigRegistrar.java import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.social.bitbucket.config.support.BitBucketApiHelper; import org.springframework.social.bitbucket.connect.BitBucketConnectionFactory; import org.springframework.social.bitbucket.security.BitBucketAuthenticationService; import org.springframework.social.config.annotation.AbstractProviderConfigRegistrarSupport; import org.springframework.social.security.provider.SocialAuthenticationService; package org.springframework.social.bitbucket.config.annotation; /** * {@link ImportBeanDefinitionRegistrar} for configuring a * {@link TwitterConnectionFactory} bean and a request-scoped {@link Twitter} * bean. * * @author Craig Walls */ public class TwitterProviderConfigRegistrar extends AbstractProviderConfigRegistrarSupport { public TwitterProviderConfigRegistrar() { super(EnableBitBucket.class, BitBucketConnectionFactory.class, BitBucketApiHelper.class); } @Override protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() {
return BitBucketAuthenticationService.class;
Graylog2/gelfclient
src/main/java/org/graylog2/gelfclient/transport/GelfSenderThread.java
// Path: src/main/java/org/graylog2/gelfclient/GelfMessage.java // public class GelfMessage { // private final GelfMessageVersion version; // private final String host; // private final String message; // private String fullMessage; // private double timestamp = System.currentTimeMillis() / 1000D; // private GelfMessageLevel level = GelfMessageLevel.ALERT; // private final Map<String, Object> additionalFields = new HashMap<>(); // // public GelfMessage(final String message) { // this(message, "localhost"); // } // // public GelfMessage(final String message, final String host) { // this(message, host, GelfMessageVersion.V1_1); // } // // public GelfMessage(final String message, final String host, final GelfMessageVersion version) { // this.message = message; // this.host = host; // this.version = version; // } // // public GelfMessageVersion getVersion() { // return version; // } // // public String getHost() { // return host; // } // // public String getMessage() { // return message; // } // // public String getFullMessage() { // return fullMessage; // } // // public void setFullMessage(final String fullMessage) { // this.fullMessage = fullMessage; // } // // public double getTimestamp() { // return timestamp; // } // // public void setTimestamp(final double timestamp) { // this.timestamp = timestamp; // } // // public GelfMessageLevel getLevel() { // return level; // } // // public void setLevel(final GelfMessageLevel level) { // this.level = level; // } // // public Map<String, Object> getAdditionalFields() { // return additionalFields; // } // // public void addAdditionalField(final String key, final Object value) { // if (key == null) { // return; // } // // additionalFields.put(key, value); // } // // public void addAdditionalFields(final Map<String, Object> additionalFields) { // this.additionalFields.putAll(additionalFields); // } // // @Override // public String toString() { // return String.format("GelfMessage{version=\"%s\" timestamp=\"%.3f\" short_message=\"%s\", level=\"%s\"}", // version, timestamp, message, level); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final GelfMessage that = (GelfMessage) o; // // if (version != that.version) return false; // if (!message.equals(that.message)) return false; // if (!host.equals(that.host)) return false; // if (level != that.level) return false; // if (Double.compare(that.timestamp, timestamp) != 0) return false; // if (fullMessage != null ? !fullMessage.equals(that.fullMessage) : that.fullMessage != null) return false; // // return true; // } // // @Override // public int hashCode() { // return Objects.hash(version, host, message, fullMessage, level, timestamp); // } // } // // Path: src/main/java/org/graylog2/gelfclient/util/Uninterruptibles.java // public class Uninterruptibles { // /** // * Copied from Guava for convenience. // * // * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} // * uninterruptibly. // * // * @param sleepFor the minimum time to sleep. If less than or equal to zero, // * do not sleep at all. // * @param unit the time unit of the {@code sleepFor} parameter. // */ // public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { // boolean interrupted = false; // try { // long remainingNanos = unit.toNanos(sleepFor); // long end = System.nanoTime() + remainingNanos; // while (true) { // try { // // TimeUnit.sleep() treats negative timeouts just like zero. // NANOSECONDS.sleep(remainingNanos); // return; // } catch (InterruptedException e) { // interrupted = true; // remainingNanos = end - System.nanoTime(); // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // } // }
import static java.util.concurrent.TimeUnit.MICROSECONDS; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import org.graylog2.gelfclient.GelfMessage; import org.graylog2.gelfclient.util.Uninterruptibles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
/* * Copyright 2014 TORCH GmbH * * 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.graylog2.gelfclient.transport; /** * The main event thread used by the {@link org.graylog2.gelfclient.transport.GelfTransport}s. */ public class GelfSenderThread { private static final Logger LOG = LoggerFactory.getLogger(GelfSenderThread.class); private final ReentrantLock lock; private final Condition connectedCond; private final AtomicBoolean keepRunning = new AtomicBoolean(true); private final Thread senderThread; private Channel channel; private final int maxInflightSends;
// Path: src/main/java/org/graylog2/gelfclient/GelfMessage.java // public class GelfMessage { // private final GelfMessageVersion version; // private final String host; // private final String message; // private String fullMessage; // private double timestamp = System.currentTimeMillis() / 1000D; // private GelfMessageLevel level = GelfMessageLevel.ALERT; // private final Map<String, Object> additionalFields = new HashMap<>(); // // public GelfMessage(final String message) { // this(message, "localhost"); // } // // public GelfMessage(final String message, final String host) { // this(message, host, GelfMessageVersion.V1_1); // } // // public GelfMessage(final String message, final String host, final GelfMessageVersion version) { // this.message = message; // this.host = host; // this.version = version; // } // // public GelfMessageVersion getVersion() { // return version; // } // // public String getHost() { // return host; // } // // public String getMessage() { // return message; // } // // public String getFullMessage() { // return fullMessage; // } // // public void setFullMessage(final String fullMessage) { // this.fullMessage = fullMessage; // } // // public double getTimestamp() { // return timestamp; // } // // public void setTimestamp(final double timestamp) { // this.timestamp = timestamp; // } // // public GelfMessageLevel getLevel() { // return level; // } // // public void setLevel(final GelfMessageLevel level) { // this.level = level; // } // // public Map<String, Object> getAdditionalFields() { // return additionalFields; // } // // public void addAdditionalField(final String key, final Object value) { // if (key == null) { // return; // } // // additionalFields.put(key, value); // } // // public void addAdditionalFields(final Map<String, Object> additionalFields) { // this.additionalFields.putAll(additionalFields); // } // // @Override // public String toString() { // return String.format("GelfMessage{version=\"%s\" timestamp=\"%.3f\" short_message=\"%s\", level=\"%s\"}", // version, timestamp, message, level); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final GelfMessage that = (GelfMessage) o; // // if (version != that.version) return false; // if (!message.equals(that.message)) return false; // if (!host.equals(that.host)) return false; // if (level != that.level) return false; // if (Double.compare(that.timestamp, timestamp) != 0) return false; // if (fullMessage != null ? !fullMessage.equals(that.fullMessage) : that.fullMessage != null) return false; // // return true; // } // // @Override // public int hashCode() { // return Objects.hash(version, host, message, fullMessage, level, timestamp); // } // } // // Path: src/main/java/org/graylog2/gelfclient/util/Uninterruptibles.java // public class Uninterruptibles { // /** // * Copied from Guava for convenience. // * // * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} // * uninterruptibly. // * // * @param sleepFor the minimum time to sleep. If less than or equal to zero, // * do not sleep at all. // * @param unit the time unit of the {@code sleepFor} parameter. // */ // public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { // boolean interrupted = false; // try { // long remainingNanos = unit.toNanos(sleepFor); // long end = System.nanoTime() + remainingNanos; // while (true) { // try { // // TimeUnit.sleep() treats negative timeouts just like zero. // NANOSECONDS.sleep(remainingNanos); // return; // } catch (InterruptedException e) { // interrupted = true; // remainingNanos = end - System.nanoTime(); // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // } // } // Path: src/main/java/org/graylog2/gelfclient/transport/GelfSenderThread.java import static java.util.concurrent.TimeUnit.MICROSECONDS; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import org.graylog2.gelfclient.GelfMessage; import org.graylog2.gelfclient.util.Uninterruptibles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /* * Copyright 2014 TORCH GmbH * * 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.graylog2.gelfclient.transport; /** * The main event thread used by the {@link org.graylog2.gelfclient.transport.GelfTransport}s. */ public class GelfSenderThread { private static final Logger LOG = LoggerFactory.getLogger(GelfSenderThread.class); private final ReentrantLock lock; private final Condition connectedCond; private final AtomicBoolean keepRunning = new AtomicBoolean(true); private final Thread senderThread; private Channel channel; private final int maxInflightSends;
private final BlockingQueue<GelfMessage> queue;
Graylog2/gelfclient
src/main/java/org/graylog2/gelfclient/transport/GelfSenderThread.java
// Path: src/main/java/org/graylog2/gelfclient/GelfMessage.java // public class GelfMessage { // private final GelfMessageVersion version; // private final String host; // private final String message; // private String fullMessage; // private double timestamp = System.currentTimeMillis() / 1000D; // private GelfMessageLevel level = GelfMessageLevel.ALERT; // private final Map<String, Object> additionalFields = new HashMap<>(); // // public GelfMessage(final String message) { // this(message, "localhost"); // } // // public GelfMessage(final String message, final String host) { // this(message, host, GelfMessageVersion.V1_1); // } // // public GelfMessage(final String message, final String host, final GelfMessageVersion version) { // this.message = message; // this.host = host; // this.version = version; // } // // public GelfMessageVersion getVersion() { // return version; // } // // public String getHost() { // return host; // } // // public String getMessage() { // return message; // } // // public String getFullMessage() { // return fullMessage; // } // // public void setFullMessage(final String fullMessage) { // this.fullMessage = fullMessage; // } // // public double getTimestamp() { // return timestamp; // } // // public void setTimestamp(final double timestamp) { // this.timestamp = timestamp; // } // // public GelfMessageLevel getLevel() { // return level; // } // // public void setLevel(final GelfMessageLevel level) { // this.level = level; // } // // public Map<String, Object> getAdditionalFields() { // return additionalFields; // } // // public void addAdditionalField(final String key, final Object value) { // if (key == null) { // return; // } // // additionalFields.put(key, value); // } // // public void addAdditionalFields(final Map<String, Object> additionalFields) { // this.additionalFields.putAll(additionalFields); // } // // @Override // public String toString() { // return String.format("GelfMessage{version=\"%s\" timestamp=\"%.3f\" short_message=\"%s\", level=\"%s\"}", // version, timestamp, message, level); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final GelfMessage that = (GelfMessage) o; // // if (version != that.version) return false; // if (!message.equals(that.message)) return false; // if (!host.equals(that.host)) return false; // if (level != that.level) return false; // if (Double.compare(that.timestamp, timestamp) != 0) return false; // if (fullMessage != null ? !fullMessage.equals(that.fullMessage) : that.fullMessage != null) return false; // // return true; // } // // @Override // public int hashCode() { // return Objects.hash(version, host, message, fullMessage, level, timestamp); // } // } // // Path: src/main/java/org/graylog2/gelfclient/util/Uninterruptibles.java // public class Uninterruptibles { // /** // * Copied from Guava for convenience. // * // * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} // * uninterruptibly. // * // * @param sleepFor the minimum time to sleep. If less than or equal to zero, // * do not sleep at all. // * @param unit the time unit of the {@code sleepFor} parameter. // */ // public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { // boolean interrupted = false; // try { // long remainingNanos = unit.toNanos(sleepFor); // long end = System.nanoTime() + remainingNanos; // while (true) { // try { // // TimeUnit.sleep() treats negative timeouts just like zero. // NANOSECONDS.sleep(remainingNanos); // return; // } catch (InterruptedException e) { // interrupted = true; // remainingNanos = end - System.nanoTime(); // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // } // }
import static java.util.concurrent.TimeUnit.MICROSECONDS; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import org.graylog2.gelfclient.GelfMessage; import org.graylog2.gelfclient.util.Uninterruptibles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
} }; while (keepRunning.get()) { // wait until we are connected to the graylog2 server before polling log events from the queue lock.lock(); try { while (channel == null || !channel.isActive()) { try { connectedCond.await(); } catch (InterruptedException e) { if (!keepRunning.get()) { // bail out if we are awoken because the application is stopping break; } } } // we are connected, let's start sending logs try { // if we have a lingering event already, try to send that instead of polling a new one. if (gelfMessage == null) { gelfMessage = queue.poll(100, TimeUnit.MILLISECONDS); } // if we are still connected, convert LoggingEvent to GELF and send it // but if we aren't connected anymore, we'll have already pulled an event from the queue, // which we keep hanging around in this thread and in the next loop iteration will block until we are connected again. if (gelfMessage != null && channel != null && channel.isActive()) { // Do not allow more than "maxInflightSends" concurrent writes in netty, to avoid having netty buffer // excessively when faced with slower consumers while (inflightSends.get() > GelfSenderThread.this.maxInflightSends) {
// Path: src/main/java/org/graylog2/gelfclient/GelfMessage.java // public class GelfMessage { // private final GelfMessageVersion version; // private final String host; // private final String message; // private String fullMessage; // private double timestamp = System.currentTimeMillis() / 1000D; // private GelfMessageLevel level = GelfMessageLevel.ALERT; // private final Map<String, Object> additionalFields = new HashMap<>(); // // public GelfMessage(final String message) { // this(message, "localhost"); // } // // public GelfMessage(final String message, final String host) { // this(message, host, GelfMessageVersion.V1_1); // } // // public GelfMessage(final String message, final String host, final GelfMessageVersion version) { // this.message = message; // this.host = host; // this.version = version; // } // // public GelfMessageVersion getVersion() { // return version; // } // // public String getHost() { // return host; // } // // public String getMessage() { // return message; // } // // public String getFullMessage() { // return fullMessage; // } // // public void setFullMessage(final String fullMessage) { // this.fullMessage = fullMessage; // } // // public double getTimestamp() { // return timestamp; // } // // public void setTimestamp(final double timestamp) { // this.timestamp = timestamp; // } // // public GelfMessageLevel getLevel() { // return level; // } // // public void setLevel(final GelfMessageLevel level) { // this.level = level; // } // // public Map<String, Object> getAdditionalFields() { // return additionalFields; // } // // public void addAdditionalField(final String key, final Object value) { // if (key == null) { // return; // } // // additionalFields.put(key, value); // } // // public void addAdditionalFields(final Map<String, Object> additionalFields) { // this.additionalFields.putAll(additionalFields); // } // // @Override // public String toString() { // return String.format("GelfMessage{version=\"%s\" timestamp=\"%.3f\" short_message=\"%s\", level=\"%s\"}", // version, timestamp, message, level); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final GelfMessage that = (GelfMessage) o; // // if (version != that.version) return false; // if (!message.equals(that.message)) return false; // if (!host.equals(that.host)) return false; // if (level != that.level) return false; // if (Double.compare(that.timestamp, timestamp) != 0) return false; // if (fullMessage != null ? !fullMessage.equals(that.fullMessage) : that.fullMessage != null) return false; // // return true; // } // // @Override // public int hashCode() { // return Objects.hash(version, host, message, fullMessage, level, timestamp); // } // } // // Path: src/main/java/org/graylog2/gelfclient/util/Uninterruptibles.java // public class Uninterruptibles { // /** // * Copied from Guava for convenience. // * // * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} // * uninterruptibly. // * // * @param sleepFor the minimum time to sleep. If less than or equal to zero, // * do not sleep at all. // * @param unit the time unit of the {@code sleepFor} parameter. // */ // public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { // boolean interrupted = false; // try { // long remainingNanos = unit.toNanos(sleepFor); // long end = System.nanoTime() + remainingNanos; // while (true) { // try { // // TimeUnit.sleep() treats negative timeouts just like zero. // NANOSECONDS.sleep(remainingNanos); // return; // } catch (InterruptedException e) { // interrupted = true; // remainingNanos = end - System.nanoTime(); // } // } // } finally { // if (interrupted) { // Thread.currentThread().interrupt(); // } // } // } // } // Path: src/main/java/org/graylog2/gelfclient/transport/GelfSenderThread.java import static java.util.concurrent.TimeUnit.MICROSECONDS; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import org.graylog2.gelfclient.GelfMessage; import org.graylog2.gelfclient.util.Uninterruptibles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; } }; while (keepRunning.get()) { // wait until we are connected to the graylog2 server before polling log events from the queue lock.lock(); try { while (channel == null || !channel.isActive()) { try { connectedCond.await(); } catch (InterruptedException e) { if (!keepRunning.get()) { // bail out if we are awoken because the application is stopping break; } } } // we are connected, let's start sending logs try { // if we have a lingering event already, try to send that instead of polling a new one. if (gelfMessage == null) { gelfMessage = queue.poll(100, TimeUnit.MILLISECONDS); } // if we are still connected, convert LoggingEvent to GELF and send it // but if we aren't connected anymore, we'll have already pulled an event from the queue, // which we keep hanging around in this thread and in the next loop iteration will block until we are connected again. if (gelfMessage != null && channel != null && channel.isActive()) { // Do not allow more than "maxInflightSends" concurrent writes in netty, to avoid having netty buffer // excessively when faced with slower consumers while (inflightSends.get() > GelfSenderThread.this.maxInflightSends) {
Uninterruptibles.sleepUninterruptibly(1, MICROSECONDS);
Graylog2/gelfclient
src/test/java/org/graylog2/gelfclient/Issue22.java
// Path: src/main/java/org/graylog2/gelfclient/transport/GelfTransport.java // public interface GelfTransport { // /** // * Sends the given message to the remote host. This <strong>blocks</strong> until there is sufficient capacity to // * process the message. It is not guaranteed that the message has been sent once the method call returns because // * a queue might be used to dispatch the message. // * // * @param message message to send to the remote host // */ // void send(GelfMessage message) throws InterruptedException; // // /** // * Tries to send the given message to the remote host. It does <strong>not block</strong> if there is not enough // * capacity to process the message. It is not guaranteed that the message has been sent once the method call // * returns because a queue might be used to dispatch the message. // * // * @param message message to send to the remote host // * @return true if the message could be dispatched, false otherwise // */ // boolean trySend(GelfMessage message); // // /** // * Stops the transport. Can be used to gracefully shutdown the backend. // */ // void stop(); // // /** // * Blocks and stops the transport after flushing/sending all enqueued messages. // * Blocking occurs until either all messages are flushed, or the indicated {@code waitDuration}, {@code timeUnit} // * and {@code retries} have elapsed. // * // * Each retry waits for the indicated {@code waitDuration} and {@code timeUnit} again. // * // * This can be used to gracefully shutdown the backend. // * // * @param waitDuration the wait duration. // * @param timeUnit the time unit for the {@code waitDuration}. // * @param retries the number of times to retry and wait for messages to flush. Zero retries indicates that // * one initial attempt will be made. // */ // void flushAndStopSynchronously(int waitDuration, TimeUnit timeUnit, int retries); // }
import org.graylog2.gelfclient.transport.GelfTransport; import org.testng.annotations.Test; import java.net.InetSocketAddress; import java.util.Date;
/* * Copyright 2016 TORCH GmbH * * 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.graylog2.gelfclient; public class Issue22 { @Test(enabled = false) public void shouldNotOOM() throws InterruptedException { final GelfMessageBuilder builder = new GelfMessageBuilder("", "GELF-CLIENT-TEST").level(GelfMessageLevel.INFO); final GelfConfiguration config = new GelfConfiguration(new InetSocketAddress("localhost", 12202)) .transport(GelfTransports.TCP) .tcpKeepAlive(true) .queueSize(512) .connectTimeout(5000) .reconnectDelay(5000) .tcpNoDelay(true) .sendBufferSize(1024);
// Path: src/main/java/org/graylog2/gelfclient/transport/GelfTransport.java // public interface GelfTransport { // /** // * Sends the given message to the remote host. This <strong>blocks</strong> until there is sufficient capacity to // * process the message. It is not guaranteed that the message has been sent once the method call returns because // * a queue might be used to dispatch the message. // * // * @param message message to send to the remote host // */ // void send(GelfMessage message) throws InterruptedException; // // /** // * Tries to send the given message to the remote host. It does <strong>not block</strong> if there is not enough // * capacity to process the message. It is not guaranteed that the message has been sent once the method call // * returns because a queue might be used to dispatch the message. // * // * @param message message to send to the remote host // * @return true if the message could be dispatched, false otherwise // */ // boolean trySend(GelfMessage message); // // /** // * Stops the transport. Can be used to gracefully shutdown the backend. // */ // void stop(); // // /** // * Blocks and stops the transport after flushing/sending all enqueued messages. // * Blocking occurs until either all messages are flushed, or the indicated {@code waitDuration}, {@code timeUnit} // * and {@code retries} have elapsed. // * // * Each retry waits for the indicated {@code waitDuration} and {@code timeUnit} again. // * // * This can be used to gracefully shutdown the backend. // * // * @param waitDuration the wait duration. // * @param timeUnit the time unit for the {@code waitDuration}. // * @param retries the number of times to retry and wait for messages to flush. Zero retries indicates that // * one initial attempt will be made. // */ // void flushAndStopSynchronously(int waitDuration, TimeUnit timeUnit, int retries); // } // Path: src/test/java/org/graylog2/gelfclient/Issue22.java import org.graylog2.gelfclient.transport.GelfTransport; import org.testng.annotations.Test; import java.net.InetSocketAddress; import java.util.Date; /* * Copyright 2016 TORCH GmbH * * 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.graylog2.gelfclient; public class Issue22 { @Test(enabled = false) public void shouldNotOOM() throws InterruptedException { final GelfMessageBuilder builder = new GelfMessageBuilder("", "GELF-CLIENT-TEST").level(GelfMessageLevel.INFO); final GelfConfiguration config = new GelfConfiguration(new InetSocketAddress("localhost", 12202)) .transport(GelfTransports.TCP) .tcpKeepAlive(true) .queueSize(512) .connectTimeout(5000) .reconnectDelay(5000) .tcpNoDelay(true) .sendBufferSize(1024);
final GelfTransport transport = GelfTransports.create(config);
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/economy/Economy.java
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // }
import edu.self.startux.craftBay.CraftBayPlugin; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer;
package edu.self.startux.craftBay.economy; public interface Economy { Economy setup(); boolean has(OfflinePlayer off, double money); double get(OfflinePlayer off); boolean give(OfflinePlayer off, double money, String message); boolean take(OfflinePlayer off, double money, String message); String format(double amount);
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // } // Path: src/main/java/edu/self/startux/craftBay/economy/Economy.java import edu.self.startux.craftBay.CraftBayPlugin; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; package edu.self.startux.craftBay.economy; public interface Economy { Economy setup(); boolean has(OfflinePlayer off, double money); double get(OfflinePlayer off); boolean give(OfflinePlayer off, double money, String message); boolean take(OfflinePlayer off, double money, String message); String format(double amount);
static Economy get(CraftBayPlugin plugin) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionStartEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionStartEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
public AuctionStartEvent(Auction auction) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/TimedAuction.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class TimedAuction extends AbstractAuction { private int timeLeft; private double minbid; private double minIncrement = 5.0; private double minRaise = 0.05; private LinkedList<Bid> bids = new LinkedList<Bid>(); private UUID lastBidder = null; public TimedAuction(CraftBayPlugin plugin, Merchant owner, Item item) { super(plugin, owner, item); minbid = plugin.getConfig().getDouble("startingbid"); timeLeft = plugin.getConfig().getInt("auctiontime"); minIncrement = plugin.getConfig().getDouble("minincrement", minIncrement); minRaise = plugin.getConfig().getDouble("minraise", minRaise); } @Override public void start() { scheduleTick(true); setState(AuctionState.RUNNING);
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // Path: src/main/java/edu/self/startux/craftBay/TimedAuction.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class TimedAuction extends AbstractAuction { private int timeLeft; private double minbid; private double minIncrement = 5.0; private double minRaise = 0.05; private LinkedList<Bid> bids = new LinkedList<Bid>(); private UUID lastBidder = null; public TimedAuction(CraftBayPlugin plugin, Merchant owner, Item item) { super(plugin, owner, item); minbid = plugin.getConfig().getDouble("startingbid"); timeLeft = plugin.getConfig().getInt("auctiontime"); minIncrement = plugin.getConfig().getDouble("minincrement", minIncrement); minRaise = plugin.getConfig().getDouble("minraise", minRaise); } @Override public void start() { scheduleTick(true); setState(AuctionState.RUNNING);
AuctionStartEvent event = new AuctionStartEvent(this);
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/TimedAuction.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID;
AuctionStartEvent event = new AuctionStartEvent(this); getPlugin().getServer().getPluginManager().callEvent(event); } @Override public int getTimeLeft() { return timeLeft; } @Override public void setTimeLeft(int time) { timeLeft = time; } @Override public MoneyAmount getStartingBid() { return new MoneyAmount(minbid); } @Override public void setStartingBid(MoneyAmount amount) { minbid = amount.getDouble(); } @Override public void tick() { if (timeLeft <= 0) { end(); return; }
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // Path: src/main/java/edu/self/startux/craftBay/TimedAuction.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID; AuctionStartEvent event = new AuctionStartEvent(this); getPlugin().getServer().getPluginManager().callEvent(event); } @Override public int getTimeLeft() { return timeLeft; } @Override public void setTimeLeft(int time) { timeLeft = time; } @Override public MoneyAmount getStartingBid() { return new MoneyAmount(minbid); } @Override public void setStartingBid(MoneyAmount amount) { minbid = amount.getDouble(); } @Override public void tick() { if (timeLeft <= 0) { end(); return; }
getPlugin().getServer().getPluginManager().callEvent(new AuctionTickEvent(this));
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/TimedAuction.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID;
bids.addLast(bid); } @Override public boolean bid(Merchant bidder, MoneyAmount bid) { if (getState() != AuctionState.RUNNING) return false; if (bidder.equals(getOwner()) && !bidder.equals(BankMerchant.getInstance())) { bidder.warn(getPlugin().getMessage("auction.bid.IsOwner").set(this, bidder)); return false; } if (plugin.getDenyDoubleBid() && bidder.getUuid().equals(lastBidder)) { bidder.warn(getPlugin().getMessage("auction.bid.DoubleBid").set(this, bidder)); return false; } if (bidder.equals(getWinner()) && bid.getDouble() <= getMaxBid().getDouble() && bidder != BankMerchant.getInstance()) { bidder.warn(getPlugin().getMessage("auction.bid.UnderbidSelf").set(this, bidder)); return false; } if (bid.getDouble() < getMinimalBid().getDouble()) { bidder.warn(getPlugin().getMessage("auction.bid.BidTooSmall").set(this, bidder)); return false; } if (!bidder.hasAmount(bid)) { bidder.warn(getPlugin().getMessage("auction.bid.TooPoor").set(this, bidder)); return false; } MoneyAmount oldPrice = getWinningBid(); Merchant oldWinner = getWinner(); addBid(new Bid(bidder, bid)); if (timeLeft < 10 && !bidder.equals(oldWinner)) { timeLeft = 10; }
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java // public class AuctionTickEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionTickEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // Path: src/main/java/edu/self/startux/craftBay/TimedAuction.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTickEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.UUID; bids.addLast(bid); } @Override public boolean bid(Merchant bidder, MoneyAmount bid) { if (getState() != AuctionState.RUNNING) return false; if (bidder.equals(getOwner()) && !bidder.equals(BankMerchant.getInstance())) { bidder.warn(getPlugin().getMessage("auction.bid.IsOwner").set(this, bidder)); return false; } if (plugin.getDenyDoubleBid() && bidder.getUuid().equals(lastBidder)) { bidder.warn(getPlugin().getMessage("auction.bid.DoubleBid").set(this, bidder)); return false; } if (bidder.equals(getWinner()) && bid.getDouble() <= getMaxBid().getDouble() && bidder != BankMerchant.getInstance()) { bidder.warn(getPlugin().getMessage("auction.bid.UnderbidSelf").set(this, bidder)); return false; } if (bid.getDouble() < getMinimalBid().getDouble()) { bidder.warn(getPlugin().getMessage("auction.bid.BidTooSmall").set(this, bidder)); return false; } if (!bidder.hasAmount(bid)) { bidder.warn(getPlugin().getMessage("auction.bid.TooPoor").set(this, bidder)); return false; } MoneyAmount oldPrice = getWinningBid(); Merchant oldWinner = getWinner(); addBid(new Bid(bidder, bid)); if (timeLeft < 10 && !bidder.equals(oldWinner)) { timeLeft = 10; }
AuctionBidEvent event = new AuctionBidEvent(this, bidder, bid, oldWinner, oldPrice);
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionCreateEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionCreateEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
public AuctionCreateEvent(Auction auction) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionTimeChangeEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private CommandSender sender; private int delay;
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionTimeChangeEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private CommandSender sender; private int delay;
public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionHouse.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // }
import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import java.util.Date; import java.util.HashMap; import java.util.Map;
} if (!plugin.getAuctionScheduler().canQueue()) { owner.warn(plugin.getMessage("auction.create.QueueFull").set(owner)); return null; } double fee = 0.0; double tax = 0.0; if (!owner.hasPermission("auction.nofee")) fee = plugin.getConfig().getDouble("auctionfee"); if (!owner.hasPermission("auction.notax") && startingBid.getDouble() > plugin.getConfig().getDouble("startingbid")) { tax = (plugin.getConfig().getDouble("auctiontax") * (startingBid.getDouble() - plugin.getConfig().getDouble("startingbid"))) / 100.0; } MoneyAmount feetax = new MoneyAmount(fee + tax); if (feetax.getDouble() > 0.0) { if (!owner.hasAmount(feetax)) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } if (!owner.takeAmount(feetax, "Auction Tax")) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } owner.msg(plugin.getMessage("auction.create.FeeDebited").set(owner).set("fee", feetax)); } touchCooldown(owner); // create Auction auction = new TimedAuction(plugin, owner, item); auction.setState(AuctionState.QUEUED); if (startingBid.getDouble() > 0) auction.setStartingBid(startingBid); auction.setFee(feetax); plugin.getAuctionScheduler().queueAuction(auction);
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionHouse.java import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import java.util.Date; import java.util.HashMap; import java.util.Map; } if (!plugin.getAuctionScheduler().canQueue()) { owner.warn(plugin.getMessage("auction.create.QueueFull").set(owner)); return null; } double fee = 0.0; double tax = 0.0; if (!owner.hasPermission("auction.nofee")) fee = plugin.getConfig().getDouble("auctionfee"); if (!owner.hasPermission("auction.notax") && startingBid.getDouble() > plugin.getConfig().getDouble("startingbid")) { tax = (plugin.getConfig().getDouble("auctiontax") * (startingBid.getDouble() - plugin.getConfig().getDouble("startingbid"))) / 100.0; } MoneyAmount feetax = new MoneyAmount(fee + tax); if (feetax.getDouble() > 0.0) { if (!owner.hasAmount(feetax)) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } if (!owner.takeAmount(feetax, "Auction Tax")) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } owner.msg(plugin.getMessage("auction.create.FeeDebited").set(owner).set("fee", feetax)); } touchCooldown(owner); // create Auction auction = new TimedAuction(plugin, owner, item); auction.setState(AuctionState.QUEUED); if (startingBid.getDouble() > 0) auction.setStartingBid(startingBid); auction.setFee(feetax); plugin.getAuctionScheduler().queueAuction(auction);
plugin.getServer().getPluginManager().callEvent(new AuctionCreateEvent(auction));
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionHouse.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // }
import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import java.util.Date; import java.util.HashMap; import java.util.Map;
double fee = 0.0; double tax = 0.0; if (!owner.hasPermission("auction.nofee")) fee = plugin.getConfig().getDouble("auctionfee"); if (!owner.hasPermission("auction.notax") && startingBid.getDouble() > plugin.getConfig().getDouble("startingbid")) { tax = (plugin.getConfig().getDouble("auctiontax") * (startingBid.getDouble() - plugin.getConfig().getDouble("startingbid"))) / 100.0; } MoneyAmount feetax = new MoneyAmount(fee + tax); if (feetax.getDouble() > 0.0) { if (!owner.hasAmount(feetax)) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } if (!owner.takeAmount(feetax, "Auction Tax")) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } owner.msg(plugin.getMessage("auction.create.FeeDebited").set(owner).set("fee", feetax)); } touchCooldown(owner); // create Auction auction = new TimedAuction(plugin, owner, item); auction.setState(AuctionState.QUEUED); if (startingBid.getDouble() > 0) auction.setStartingBid(startingBid); auction.setFee(feetax); plugin.getAuctionScheduler().queueAuction(auction); plugin.getServer().getPluginManager().callEvent(new AuctionCreateEvent(auction)); return auction; } public void endAuction(Auction auction) {
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionHouse.java import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import java.util.Date; import java.util.HashMap; import java.util.Map; double fee = 0.0; double tax = 0.0; if (!owner.hasPermission("auction.nofee")) fee = plugin.getConfig().getDouble("auctionfee"); if (!owner.hasPermission("auction.notax") && startingBid.getDouble() > plugin.getConfig().getDouble("startingbid")) { tax = (plugin.getConfig().getDouble("auctiontax") * (startingBid.getDouble() - plugin.getConfig().getDouble("startingbid"))) / 100.0; } MoneyAmount feetax = new MoneyAmount(fee + tax); if (feetax.getDouble() > 0.0) { if (!owner.hasAmount(feetax)) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } if (!owner.takeAmount(feetax, "Auction Tax")) { owner.warn(plugin.getMessage("auction.create.FeeTooHigh").set(owner).set("fee", feetax)); return null; } owner.msg(plugin.getMessage("auction.create.FeeDebited").set(owner).set("fee", feetax)); } touchCooldown(owner); // create Auction auction = new TimedAuction(plugin, owner, item); auction.setState(AuctionState.QUEUED); if (startingBid.getDouble() > 0) auction.setStartingBid(startingBid); auction.setFee(feetax); plugin.getAuctionScheduler().queueAuction(auction); plugin.getServer().getPluginManager().callEvent(new AuctionCreateEvent(auction)); return auction; } public void endAuction(Auction auction) {
AuctionEndEvent event = new AuctionEndEvent(auction);
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/economy/VaultEconomy.java
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // }
import edu.self.startux.craftBay.CraftBayPlugin; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider;
package edu.self.startux.craftBay.economy; @RequiredArgsConstructor public final class VaultEconomy implements Economy {
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // } // Path: src/main/java/edu/self/startux/craftBay/economy/VaultEconomy.java import edu.self.startux.craftBay.CraftBayPlugin; import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.plugin.RegisteredServiceProvider; package edu.self.startux.craftBay.economy; @RequiredArgsConstructor public final class VaultEconomy implements Economy {
private final CraftBayPlugin plugin;
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionLogger.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class AuctionLogger implements Listener { private CraftBayPlugin plugin; public AuctionLogger(CraftBayPlugin plugin) { this.plugin = plugin; } public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST)
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionLogger.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class AuctionLogger implements Listener { private CraftBayPlugin plugin; public AuctionLogger(CraftBayPlugin plugin) { this.plugin = plugin; } public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST)
public void onAuctionCreate(AuctionCreateEvent event) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionLogger.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class AuctionLogger implements Listener { private CraftBayPlugin plugin; public AuctionLogger(CraftBayPlugin plugin) { this.plugin = plugin; } public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionCreate(AuctionCreateEvent event) { if (!plugin.getDebugMode()) return; Auction auction = event.getAuction(); auction.log(String.format("CREATE owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST)
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionLogger.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay; public class AuctionLogger implements Listener { private CraftBayPlugin plugin; public AuctionLogger(CraftBayPlugin plugin) { this.plugin = plugin; } public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionCreate(AuctionCreateEvent event) { if (!plugin.getDebugMode()) return; Auction auction = event.getAuction(); auction.log(String.format("CREATE owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST)
public void onAuctionStart(AuctionStartEvent event) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionLogger.java
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // }
import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener;
public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionCreate(AuctionCreateEvent event) { if (!plugin.getDebugMode()) return; Auction auction = event.getAuction(); auction.log(String.format("CREATE owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionStart(AuctionStartEvent event) { Auction auction = event.getAuction(); auction.log(String.format("START owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionBid(AuctionBidEvent event) { Auction auction = event.getAuction(); auction.log(String.format("BID bidder='%s' amount='%s'", event.getBidder().getName(), event.getAmount())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionEnd(AuctionEndEvent event) { Auction auction = event.getAuction(); auction.log(String.format("END winner='%s' price='%s' paymentError='%b'", (auction.getWinner() != null ? auction.getWinner().getName() : "none"), auction.getWinningBid(), event.hasPaymentError())); } @EventHandler(priority = EventPriority.LOWEST)
// Path: src/main/java/edu/self/startux/craftBay/event/AuctionBidEvent.java // public class AuctionBidEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private Merchant bidder, oldWinner; // private MoneyAmount amount, oldPrice; // // public AuctionBidEvent(Auction auction, Merchant bidder, MoneyAmount amount, Merchant oldWinner, MoneyAmount oldPrice) { // super(auction); // this.bidder = bidder; // this.amount = amount; // this.oldWinner = oldWinner; // this.oldPrice = oldPrice; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public Merchant getBidder() { // return bidder; // } // // public MoneyAmount getAmount() { // return amount; // } // // public Merchant getOldWinner() { // return oldWinner; // } // // public MoneyAmount getOldPrice() { // return oldPrice; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java // public class AuctionCancelEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // // public AuctionCancelEvent(Auction auction, CommandSender sender) { // super(auction); // this.sender = sender; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCreateEvent.java // public class AuctionCreateEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionCreateEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java // public class AuctionEndEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private boolean paymentError = false; // // public AuctionEndEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public void setPaymentError(boolean paymentError) { // this.paymentError = paymentError; // } // // public boolean hasPaymentError() { // return paymentError; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionStartEvent.java // public class AuctionStartEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // // public AuctionStartEvent(Auction auction) { // super(auction); // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // } // // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTimeChangeEvent.java // public class AuctionTimeChangeEvent extends AuctionEvent { // private static HandlerList handlers = new HandlerList(); // private CommandSender sender; // private int delay; // // public AuctionTimeChangeEvent(Auction auction, CommandSender sender, int delay) { // super(auction); // this.sender = sender; // this.delay = delay; // } // // public static HandlerList getHandlerList() { // return handlers; // } // // @Override // public HandlerList getHandlers() { // return handlers; // } // // public CommandSender getSender() { // return sender; // } // // public int getDelay() { // return delay; // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionLogger.java import edu.self.startux.craftBay.event.AuctionBidEvent; import edu.self.startux.craftBay.event.AuctionCancelEvent; import edu.self.startux.craftBay.event.AuctionCreateEvent; import edu.self.startux.craftBay.event.AuctionEndEvent; import edu.self.startux.craftBay.event.AuctionStartEvent; import edu.self.startux.craftBay.event.AuctionTimeChangeEvent; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; public void enable() { plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionCreate(AuctionCreateEvent event) { if (!plugin.getDebugMode()) return; Auction auction = event.getAuction(); auction.log(String.format("CREATE owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionStart(AuctionStartEvent event) { Auction auction = event.getAuction(); auction.log(String.format("START owner='%s' item='%s' minbid='%s' fee='%s'", auction.getOwner().getName(), auction.getItem().toString(), auction.getMinimalBid(), auction.getFee())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionBid(AuctionBidEvent event) { Auction auction = event.getAuction(); auction.log(String.format("BID bidder='%s' amount='%s'", event.getBidder().getName(), event.getAmount())); } @EventHandler(priority = EventPriority.LOWEST) public void onAuctionEnd(AuctionEndEvent event) { Auction auction = event.getAuction(); auction.log(String.format("END winner='%s' price='%s' paymentError='%b'", (auction.getWinner() != null ? auction.getWinner().getName() : "none"), auction.getWinningBid(), event.hasPaymentError())); } @EventHandler(priority = EventPriority.LOWEST)
public void onAuctionCancel(AuctionCancelEvent event) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/RealItem.java
// Path: src/main/java/edu/self/startux/craftBay/item/ItemManager.java // public interface ItemManager { // /** // * Does this manager manage this item exclusively? // */ // boolean isManaged(ItemStack itemStack); // // /** // * Produce the item display name. // */ // Component getDisplayName(ItemStack itemStack); // // /** // * Detailed item info. // */ // Component getItemInfo(ItemStack itemStack); // // static List<ItemManager> getList(CraftBayPlugin plugin) { // List<ItemManager> result = new ArrayList<>(); // try { // if (Bukkit.getPluginManager().isPluginEnabled("Mytems")) { // if (Bukkit.getPluginManager().getPlugin("Mytems").getClass().getName().equals("com.cavetale.mytems.MytemsPlugin")) { // result.add(new MytemsItemManager()); // plugin.getLogger().info("Mytems plugin found!"); // } // } // } catch (Throwable t) { // t.printStackTrace(); // } // return result; // } // }
import edu.self.startux.craftBay.item.ItemManager; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.FireworkEffectMeta; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionType;
PotionData data = potions.getBasePotionData(); if (data != null && data.getType() != PotionType.UNCRAFTABLE) { sb.append(" "); sb.append(niceEnumName(data.getType().name())); if (data.isExtended()) sb.append(" Ext"); if (data.isUpgraded()) sb.append(" II"); } } catch (IllegalArgumentException iae) { } if (potions.hasCustomEffects()) { for (PotionEffect effect: potions.getCustomEffects()) { sb.append(" "); sb.append(niceEnumName(effect.getType().getName())); int amp = effect.getAmplifier(); if (amp > 0) { sb.append(" ").append((amp + 1)); } } } result.append(Component.text(sb.toString())); } return result.build(); } @Override public ItemAmount getAmount() { return new ItemAmount(amount, stack.getMaxStackSize()); } @Override public Component getItemInfo() {
// Path: src/main/java/edu/self/startux/craftBay/item/ItemManager.java // public interface ItemManager { // /** // * Does this manager manage this item exclusively? // */ // boolean isManaged(ItemStack itemStack); // // /** // * Produce the item display name. // */ // Component getDisplayName(ItemStack itemStack); // // /** // * Detailed item info. // */ // Component getItemInfo(ItemStack itemStack); // // static List<ItemManager> getList(CraftBayPlugin plugin) { // List<ItemManager> result = new ArrayList<>(); // try { // if (Bukkit.getPluginManager().isPluginEnabled("Mytems")) { // if (Bukkit.getPluginManager().getPlugin("Mytems").getClass().getName().equals("com.cavetale.mytems.MytemsPlugin")) { // result.add(new MytemsItemManager()); // plugin.getLogger().info("Mytems plugin found!"); // } // } // } catch (Throwable t) { // t.printStackTrace(); // } // return result; // } // } // Path: src/main/java/edu/self/startux/craftBay/RealItem.java import edu.self.startux.craftBay.item.ItemManager; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.FireworkEffectMeta; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionType; PotionData data = potions.getBasePotionData(); if (data != null && data.getType() != PotionType.UNCRAFTABLE) { sb.append(" "); sb.append(niceEnumName(data.getType().name())); if (data.isExtended()) sb.append(" Ext"); if (data.isUpgraded()) sb.append(" II"); } } catch (IllegalArgumentException iae) { } if (potions.hasCustomEffects()) { for (PotionEffect effect: potions.getCustomEffects()) { sb.append(" "); sb.append(niceEnumName(effect.getType().getName())); int amp = effect.getAmplifier(); if (amp > 0) { sb.append(" ").append((amp + 1)); } } } result.append(Component.text(sb.toString())); } return result.build(); } @Override public ItemAmount getAmount() { return new ItemAmount(amount, stack.getMaxStackSize()); } @Override public Component getItemInfo() {
for (ItemManager itemManager : CraftBayPlugin.getInstance().getItemManagers()) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/AuctionInventory.java
// Path: src/main/java/edu/self/startux/craftBay/locale/Color.java // public final class Color { // public static final Color DEFAULT = new Color(new String[]{"DEFAULT", "DFL"}, NamedTextColor.BLUE); // public static final Color HEADER = new Color(new String[]{"HEADER", "HEAD", "HD", "H"}, NamedTextColor.YELLOW); // public static final Color HIGHLIGHT = new Color(new String[]{"HIGHLIGHT", "HL", "HI"}, NamedTextColor.AQUA); // public static final Color SHADOW = new Color(new String[]{"SHADOW", "DARK", "SHADE", "SHD"}, NamedTextColor.DARK_GRAY); // public static final Color SHORTCUT = new Color(new String[]{"SHORTCUT", "SC", "S"}, NamedTextColor.WHITE); // public static final Color ADMIN = new Color(new String[]{"ADMIN", "ADM"}, NamedTextColor.DARK_RED); // public static final Color ADMINHIGHLIGHT = new Color(new String[]{"ADMINHIGHLIGHT", "ADMINHIGH", "ADMINHI", "ADMHL", "ADMHI"}, NamedTextColor.RED); // public static final Color ERROR = new Color(new String[]{"ERROR", "ERR"}, NamedTextColor.DARK_RED); // public static final Color WARN = new Color(new String[]{"WARNING", "WARN", "WRN"}, NamedTextColor.RED); // public static final Color WARNHIGHLIGHT = new Color(new String[]{"WARNINGHIGHLIGHT", "WARNINGHIGH", "WARNHIGH", "WARNHI", "WRNHI"}, NamedTextColor.DARK_RED); // // private static Map<String, Color> nameMap; // private TextColor textColor; // // private Color(final String[] aliases, final TextColor dfl) { // if (nameMap == null) nameMap = new HashMap<String, Color>(); // for (String alias : aliases) nameMap.put(alias.toLowerCase(), this); // this.textColor = dfl; // } // // public static Color getByName(String name) { // if (name == null) return null; // return nameMap.get(name.toLowerCase()); // } // // public void setColor(TextColor color) { // this.textColor = color; // } // // @Override // public String toString() { // return textColor.toString(); // } // // public TextColor getTextColor() { // return textColor; // } // // public static void configure(ConfigurationSection section) { // if (section == null) return; // for (String key : section.getKeys(false)) { // Color color = getByName(key); // if (color == null) { // CraftBayPlugin.getInstance().getLogger().warning("Unknown color key: " + key); // continue; // } // String value = section.getString(key); // TextColor textColor; // try { // if (value.startsWith("#")) { // textColor = TextColor.fromHexString(value.substring(1)); // } else { // textColor = NamedTextColor.NAMES.value(value); // } // } catch (Exception e) { // CraftBayPlugin.getInstance().getLogger().warning("Unknown color value: " + value); // continue; // } // color.setColor(textColor); // } // } // }
import edu.self.startux.craftBay.locale.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.Tag; import org.bukkit.block.ShulkerBox; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta;
data.minbid = minbid; data.inventory = inventory; data.type = type; } } public void initPlayer(Player player, MoneyAmount minbid) { String title = plugin.getMessage("auction.gui.ChestTitle").toString(); if (title.length() > 32) title = title.substring(0, 32); Inventory inventory = Bukkit.createInventory(null, 54, Component.text(title)); player.openInventory(inventory); setPlayer(player, minbid, inventory, Type.CREATE); } public boolean initPreview(Player player, Auction auction) { if (!(auction.getItem() instanceof RealItem)) return false; if (playerData.get(player.getUniqueId()) != null) return false; RealItem real = (RealItem) auction.getItem(); ItemStack item = real.getItemStack(); List<ItemStack> items = new ArrayList<>(); int amount = real.getAmount().getInt(); while (amount > 0) { int stackSize = Math.min(amount, item.getType().getMaxStackSize()); amount -= stackSize; ItemStack clone = item.clone(); clone.setAmount(stackSize); items.add(clone); } if (items.isEmpty()) return false; int invSize = ((items.size() - 1) / 9 + 1) * 9;
// Path: src/main/java/edu/self/startux/craftBay/locale/Color.java // public final class Color { // public static final Color DEFAULT = new Color(new String[]{"DEFAULT", "DFL"}, NamedTextColor.BLUE); // public static final Color HEADER = new Color(new String[]{"HEADER", "HEAD", "HD", "H"}, NamedTextColor.YELLOW); // public static final Color HIGHLIGHT = new Color(new String[]{"HIGHLIGHT", "HL", "HI"}, NamedTextColor.AQUA); // public static final Color SHADOW = new Color(new String[]{"SHADOW", "DARK", "SHADE", "SHD"}, NamedTextColor.DARK_GRAY); // public static final Color SHORTCUT = new Color(new String[]{"SHORTCUT", "SC", "S"}, NamedTextColor.WHITE); // public static final Color ADMIN = new Color(new String[]{"ADMIN", "ADM"}, NamedTextColor.DARK_RED); // public static final Color ADMINHIGHLIGHT = new Color(new String[]{"ADMINHIGHLIGHT", "ADMINHIGH", "ADMINHI", "ADMHL", "ADMHI"}, NamedTextColor.RED); // public static final Color ERROR = new Color(new String[]{"ERROR", "ERR"}, NamedTextColor.DARK_RED); // public static final Color WARN = new Color(new String[]{"WARNING", "WARN", "WRN"}, NamedTextColor.RED); // public static final Color WARNHIGHLIGHT = new Color(new String[]{"WARNINGHIGHLIGHT", "WARNINGHIGH", "WARNHIGH", "WARNHI", "WRNHI"}, NamedTextColor.DARK_RED); // // private static Map<String, Color> nameMap; // private TextColor textColor; // // private Color(final String[] aliases, final TextColor dfl) { // if (nameMap == null) nameMap = new HashMap<String, Color>(); // for (String alias : aliases) nameMap.put(alias.toLowerCase(), this); // this.textColor = dfl; // } // // public static Color getByName(String name) { // if (name == null) return null; // return nameMap.get(name.toLowerCase()); // } // // public void setColor(TextColor color) { // this.textColor = color; // } // // @Override // public String toString() { // return textColor.toString(); // } // // public TextColor getTextColor() { // return textColor; // } // // public static void configure(ConfigurationSection section) { // if (section == null) return; // for (String key : section.getKeys(false)) { // Color color = getByName(key); // if (color == null) { // CraftBayPlugin.getInstance().getLogger().warning("Unknown color key: " + key); // continue; // } // String value = section.getString(key); // TextColor textColor; // try { // if (value.startsWith("#")) { // textColor = TextColor.fromHexString(value.substring(1)); // } else { // textColor = NamedTextColor.NAMES.value(value); // } // } catch (Exception e) { // CraftBayPlugin.getInstance().getLogger().warning("Unknown color value: " + value); // continue; // } // color.setColor(textColor); // } // } // } // Path: src/main/java/edu/self/startux/craftBay/AuctionInventory.java import edu.self.startux.craftBay.locale.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.Tag; import org.bukkit.block.ShulkerBox; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BlockStateMeta; data.minbid = minbid; data.inventory = inventory; data.type = type; } } public void initPlayer(Player player, MoneyAmount minbid) { String title = plugin.getMessage("auction.gui.ChestTitle").toString(); if (title.length() > 32) title = title.substring(0, 32); Inventory inventory = Bukkit.createInventory(null, 54, Component.text(title)); player.openInventory(inventory); setPlayer(player, minbid, inventory, Type.CREATE); } public boolean initPreview(Player player, Auction auction) { if (!(auction.getItem() instanceof RealItem)) return false; if (playerData.get(player.getUniqueId()) != null) return false; RealItem real = (RealItem) auction.getItem(); ItemStack item = real.getItemStack(); List<ItemStack> items = new ArrayList<>(); int amount = real.getAmount().getInt(); while (amount > 0) { int stackSize = Math.min(amount, item.getType().getMaxStackSize()); amount -= stackSize; ItemStack clone = item.clone(); clone.setAmount(stackSize); items.add(clone); } if (items.isEmpty()) return false; int invSize = ((items.size() - 1) / 9 + 1) * 9;
Component name = Component.text("Auction Preview", Color.DEFAULT.getTextColor());
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/economy/MoneyEconomy.java
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // }
import com.cavetale.money.Money; import edu.self.startux.craftBay.CraftBayPlugin; import lombok.RequiredArgsConstructor; import org.bukkit.OfflinePlayer;
package edu.self.startux.craftBay.economy; @RequiredArgsConstructor public final class MoneyEconomy implements Economy {
// Path: src/main/java/edu/self/startux/craftBay/CraftBayPlugin.java // public final class CraftBayPlugin extends JavaPlugin { // private String tag = "[CraftBay]"; // private ChatPlugin chatPlugin; // private AuctionAnnouncer announcer; // private AuctionHouse house; // @Getter private AuctionScheduler scheduler; // private AuctionCommand executor; // private Language language; // private AuctionLogger auctionLogger; // private AuctionInventory inventory; // private List<String> blacklistWorlds = new ArrayList<String>(); // private static CraftBayPlugin instance; // private boolean denyDoubleBid = false; // private boolean debugMode = false; // @Getter private boolean showCustomItemNames = false; // private Economy economy; // @Getter private final List<ItemManager> itemManagers = new ArrayList<>(); // // public static CraftBayPlugin getInstance() { // return instance; // } // // public void onEnable() { // instance = this; // Language.writeLanguageFiles(); // setupSerializations(); // executor = new AuctionCommand(this); // getCommand("auction").setExecutor(executor); // getCommand("bid").setExecutor(executor); // this.economy = Economy.get(this); // itemManagers.addAll(ItemManager.getList(this)); // announcer = new AuctionAnnouncer(this); // house = new AuctionHouse(this); // scheduler = new AuctionScheduler(this); // auctionLogger = new AuctionLogger(this); // inventory = new AuctionInventory(this); // saveDefaultConfig(); // reloadAuctionConfig(); // auctionLogger.enable(); // house.enable(); // announcer.enable(); // scheduler.enable(); // } // // public void onDisable() { // inventory.onDisable(); // if (scheduler != null) scheduler.disable(); // economy = null; // if (chatPlugin != null) chatPlugin.disable(); // chatPlugin = null; // announcer = null; // house = null; // scheduler = null; // auctionLogger = null; // instance = null; // } // // public void setupSerializations() { // ConfigurationSerialization.registerClass(TimedAuction.class); // ConfigurationSerialization.registerClass(RealItem.class); // ConfigurationSerialization.registerClass(FakeItem.class); // ConfigurationSerialization.registerClass(Bid.class); // ConfigurationSerialization.registerClass(PlayerMerchant.class); // ConfigurationSerialization.registerClass(BankMerchant.class); // ConfigurationSerialization.registerClass(ItemDelivery.class); // } // // public void reloadAuctionConfig() { // reloadConfig(); // blacklistWorlds = getConfig().getStringList("blacklistworlds"); // language = new Language(this, getConfig().getString("lang")); // tag = language.getMessage("Tag").toString(); // Color.configure(getConfig().getConfigurationSection("colors")); // denyDoubleBid = getConfig().getBoolean("denydoublebid"); // debugMode = getConfig().getBoolean("debug"); // showCustomItemNames = getConfig().getBoolean("show-custom-item-names"); // announcer.reloadConfig(); // setupChat(); // } // // private void setupChat() { // if (chatPlugin != null) chatPlugin.disable(); // do { // // if all fails, fall back to bukkit chat // chatPlugin = new BukkitChat(this); // chatPlugin.enable(getConfig().getConfigurationSection("defaultchat")); // getLogger().info("Falling back to default chat"); // } while (false); // } // // public Economy getEco() { // return economy; // } // // public Auction getAuction() { // return scheduler.getCurrentAuction(); // } // // public AuctionHouse getAuctionHouse() { // return house; // } // // public AuctionScheduler getAuctionScheduler() { // return scheduler; // } // // public AuctionInventory getAuctionInventory() { // return inventory; // } // // public List<String> getBlacklistWorlds() { // return blacklistWorlds; // } // // public void warn(CommandSender sender, Message msg) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.ERROR.getTextColor()), // Component.space(), // msg.compile(), // }).color(Color.WARN.getTextColor())); // } // // public void msg(CommandSender sender, Component component) { // sender.sendMessage(Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // component, // }).color(Color.DEFAULT.getTextColor())); // } // // public void msg(CommandSender sender, Message msg) { // msg(sender, msg.compile()); // } // // public String getTag() { // return tag; // } // // public boolean getDenyDoubleBid() { // return denyDoubleBid; // } // // public boolean getDebugMode() { // return debugMode; // } // // public void broadcast(Message msg) { // Component txt = msg.compile(); // if (Component.empty().equals(txt)) return; // Component c = Component.join(JoinConfiguration.noSeparators(), new Component[] { // Component.text(tag, Color.HIGHLIGHT.getTextColor()), // Component.space(), // txt, // }).color(Color.DEFAULT.getTextColor()); // chatPlugin.broadcast(c); // } // // public ChatPlugin getChatPlugin() { // return chatPlugin; // } // // public Language getLanguage() { // return language; // } // // public Message getMessage(String key) { // return language.getMessage(key); // } // // public Message getMessages(String... keys) { // return language.getMessages(keys); // } // } // Path: src/main/java/edu/self/startux/craftBay/economy/MoneyEconomy.java import com.cavetale.money.Money; import edu.self.startux.craftBay.CraftBayPlugin; import lombok.RequiredArgsConstructor; import org.bukkit.OfflinePlayer; package edu.self.startux.craftBay.economy; @RequiredArgsConstructor public final class MoneyEconomy implements Economy {
private final CraftBayPlugin plugin;
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; /** * Called whenever an auction ends and an item and maybe money * will go to merchants. */ public class AuctionEndEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private boolean paymentError = false;
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEndEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; /** * Called whenever an auction ends and an item and maybe money * will go to merchants. */ public class AuctionEndEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private boolean paymentError = false;
public AuctionEndEvent(Auction auction) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionCancelEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private CommandSender sender;
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionCancelEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.command.CommandSender; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public class AuctionCancelEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList(); private CommandSender sender;
public AuctionCancelEvent(Auction auction, CommandSender sender) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; /** * */ public class AuctionTickEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionTickEvent.java import edu.self.startux.craftBay.Auction; import org.bukkit.event.HandlerList; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; /** * */ public class AuctionTickEvent extends AuctionEvent { private static HandlerList handlers = new HandlerList();
public AuctionTickEvent(Auction auction) {
StarTux/CraftBay
src/main/java/edu/self/startux/craftBay/event/AuctionEvent.java
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // }
import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import edu.self.startux.craftBay.Auction;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public abstract class AuctionEvent extends Event { private static HandlerList handlers = new HandlerList();
// Path: src/main/java/edu/self/startux/craftBay/Auction.java // public interface Auction extends ConfigurationSerializable { // /** // * Get this auction's id // * @return the id // */ // public int getId(); // // /** // * The AuctionScheduler should set the id with this method. // * @param id the id // */ // public void setId(int id); // // /** // * Get the state of this auction // * @return the state // */ // public AuctionState getState(); // public void setState(AuctionState state); // // /** // * Get the item that is being auctioned // * @return the item // */ // public Item getItem(); // // /** // * Get the owner of this auction // * @return the owner // */ // public Merchant getOwner(); // // /** // * Get the winner of this auction // * @return the winner or null if there isn't one // */ // public Merchant getWinner(); // // /** // * Start this auction. // */ // public void start(); // // /** // * Attempt to place a bid. // * @param bidder the Merchant attempting to bid // * @param bid the bid amount // */ // public boolean bid(Merchant bidder, MoneyAmount bid); // // /** // * Stop this auction. // */ // public void stop(); // // /** // * End this auction legitmately. // */ // public void end(); // // /** // * Cancel this auction. // */ // public void cancel(); // // /** // * Get the minimum amount that a new bidder has to make to // * be accepted. // */ // public MoneyAmount getMinimalBid(); // /** // * Get the highest bid that was placed // */ // public MoneyAmount getMaxBid(); // /** // * Get the winning bid // */ // public MoneyAmount getWinningBid(); // // public int getTimeLeft(); // public void setTimeLeft(int time); // // public MoneyAmount getStartingBid(); // public void setStartingBid(MoneyAmount amount); // // public MoneyAmount getFee(); // public void setFee(MoneyAmount fee); // // public void log(String msg); // public List<String> getLog(); // } // Path: src/main/java/edu/self/startux/craftBay/event/AuctionEvent.java import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import edu.self.startux.craftBay.Auction; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright 2012 StarTux * * This file is part of CraftBay. * * CraftBay 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. * * CraftBay is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CraftBay. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package edu.self.startux.craftBay.event; public abstract class AuctionEvent extends Event { private static HandlerList handlers = new HandlerList();
private Auction auction;
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/fanout/CompletableFuturesTest.java
// Path: blog-code/src/main/java/pl/ciruk/blog/fanout/CompletableFutures.java // static <F, T> Function<F, CompletableFuture<Stream<T>>> fanOut(Collection<Function<F, T>> mappings) { // return fanOut(mappings, ForkJoinPool.commonPool()); // }
import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static pl.ciruk.blog.fanout.CompletableFutures.fanOut;
package pl.ciruk.blog.fanout; public class CompletableFuturesTest { @Test public void shouldExecuteAllFunctionsFromMappings() throws Exception { // Given CompletableFuture<String> future = CompletableFuture.completedFuture("SampleText"); // When CompletableFuture<Stream<Integer>> actualFuture = future.thenCompose(
// Path: blog-code/src/main/java/pl/ciruk/blog/fanout/CompletableFutures.java // static <F, T> Function<F, CompletableFuture<Stream<T>>> fanOut(Collection<Function<F, T>> mappings) { // return fanOut(mappings, ForkJoinPool.commonPool()); // } // Path: blog-code/src/test/java/pl/ciruk/blog/fanout/CompletableFuturesTest.java import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static pl.ciruk.blog.fanout.CompletableFutures.fanOut; package pl.ciruk.blog.fanout; public class CompletableFuturesTest { @Test public void shouldExecuteAllFunctionsFromMappings() throws Exception { // Given CompletableFuture<String> future = CompletableFuture.completedFuture("SampleText"); // When CompletableFuture<Stream<Integer>> actualFuture = future.thenCompose(
fanOut(ImmutableList.of(
cpiotr/blog
blog-code/src/main/java/pl/ciruk/blog/producerconsumer/web/PagesProcessor.java
// Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Consumer.java // public class Consumer<T extends Queueable> implements Runnable { // private BlockingQueue<T> queue; // // private Processable<T> processor; // // public Consumer(BlockingQueue<T> queue) { // this(queue, Processable.EMPTY); // } // // public Consumer(BlockingQueue<T> queue, Processable<T> processor) { // this.queue = queue; // this.processor = processor; // } // // @Override // public void run() { // // try { // consumeMessages(); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // private void consumeMessages() throws InterruptedException { // while (true) { // T message = queue.poll(1, TimeUnit.SECONDS); // if (Queueables.isLastMessage(message)) { // return; // } // // processor.process(message); // } // } // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Processable.java // public interface Processable<T> { // Processable EMPTY = new Processable<Object>() { // @Override // public void process(Object element) { // // Nothing to do, just visiting // } // // }; // // void process(T element); // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Producer.java // public class Producer<T extends Queueable> { // private BlockingQueue<T> queue; // // public Producer(BlockingQueue<T> queue) { // this.queue = queue; // } // // public void send(T message) { // try { // queue.put(message); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import pl.ciruk.blog.producerconsumer.concurrent.Consumer; import pl.ciruk.blog.producerconsumer.concurrent.Processable; import pl.ciruk.blog.producerconsumer.concurrent.Producer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists;
package pl.ciruk.blog.producerconsumer.web; public class PagesProcessor { Map<String, Producer<Page>> producers = new HashMap<>(); ExecutorService executor = Executors.newFixedThreadPool(4); public void createProducer(final String producerId) { BlockingQueue<Page> queue = new LinkedBlockingQueue<Page>(); Producer<Page> producer = new Producer<>(queue); producers.put(producerId, producer);
// Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Consumer.java // public class Consumer<T extends Queueable> implements Runnable { // private BlockingQueue<T> queue; // // private Processable<T> processor; // // public Consumer(BlockingQueue<T> queue) { // this(queue, Processable.EMPTY); // } // // public Consumer(BlockingQueue<T> queue, Processable<T> processor) { // this.queue = queue; // this.processor = processor; // } // // @Override // public void run() { // // try { // consumeMessages(); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // private void consumeMessages() throws InterruptedException { // while (true) { // T message = queue.poll(1, TimeUnit.SECONDS); // if (Queueables.isLastMessage(message)) { // return; // } // // processor.process(message); // } // } // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Processable.java // public interface Processable<T> { // Processable EMPTY = new Processable<Object>() { // @Override // public void process(Object element) { // // Nothing to do, just visiting // } // // }; // // void process(T element); // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Producer.java // public class Producer<T extends Queueable> { // private BlockingQueue<T> queue; // // public Producer(BlockingQueue<T> queue) { // this.queue = queue; // } // // public void send(T message) { // try { // queue.put(message); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // } // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/web/PagesProcessor.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import pl.ciruk.blog.producerconsumer.concurrent.Consumer; import pl.ciruk.blog.producerconsumer.concurrent.Processable; import pl.ciruk.blog.producerconsumer.concurrent.Producer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; package pl.ciruk.blog.producerconsumer.web; public class PagesProcessor { Map<String, Producer<Page>> producers = new HashMap<>(); ExecutorService executor = Executors.newFixedThreadPool(4); public void createProducer(final String producerId) { BlockingQueue<Page> queue = new LinkedBlockingQueue<Page>(); Producer<Page> producer = new Producer<>(queue); producers.put(producerId, producer);
Consumer<Page> consumer = new Consumer<>(queue, new Processable<Page>() {
cpiotr/blog
blog-code/src/main/java/pl/ciruk/blog/producerconsumer/web/PagesProcessor.java
// Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Consumer.java // public class Consumer<T extends Queueable> implements Runnable { // private BlockingQueue<T> queue; // // private Processable<T> processor; // // public Consumer(BlockingQueue<T> queue) { // this(queue, Processable.EMPTY); // } // // public Consumer(BlockingQueue<T> queue, Processable<T> processor) { // this.queue = queue; // this.processor = processor; // } // // @Override // public void run() { // // try { // consumeMessages(); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // private void consumeMessages() throws InterruptedException { // while (true) { // T message = queue.poll(1, TimeUnit.SECONDS); // if (Queueables.isLastMessage(message)) { // return; // } // // processor.process(message); // } // } // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Processable.java // public interface Processable<T> { // Processable EMPTY = new Processable<Object>() { // @Override // public void process(Object element) { // // Nothing to do, just visiting // } // // }; // // void process(T element); // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Producer.java // public class Producer<T extends Queueable> { // private BlockingQueue<T> queue; // // public Producer(BlockingQueue<T> queue) { // this.queue = queue; // } // // public void send(T message) { // try { // queue.put(message); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import pl.ciruk.blog.producerconsumer.concurrent.Consumer; import pl.ciruk.blog.producerconsumer.concurrent.Processable; import pl.ciruk.blog.producerconsumer.concurrent.Producer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists;
package pl.ciruk.blog.producerconsumer.web; public class PagesProcessor { Map<String, Producer<Page>> producers = new HashMap<>(); ExecutorService executor = Executors.newFixedThreadPool(4); public void createProducer(final String producerId) { BlockingQueue<Page> queue = new LinkedBlockingQueue<Page>(); Producer<Page> producer = new Producer<>(queue); producers.put(producerId, producer);
// Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Consumer.java // public class Consumer<T extends Queueable> implements Runnable { // private BlockingQueue<T> queue; // // private Processable<T> processor; // // public Consumer(BlockingQueue<T> queue) { // this(queue, Processable.EMPTY); // } // // public Consumer(BlockingQueue<T> queue, Processable<T> processor) { // this.queue = queue; // this.processor = processor; // } // // @Override // public void run() { // // try { // consumeMessages(); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // // private void consumeMessages() throws InterruptedException { // while (true) { // T message = queue.poll(1, TimeUnit.SECONDS); // if (Queueables.isLastMessage(message)) { // return; // } // // processor.process(message); // } // } // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Processable.java // public interface Processable<T> { // Processable EMPTY = new Processable<Object>() { // @Override // public void process(Object element) { // // Nothing to do, just visiting // } // // }; // // void process(T element); // } // // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/concurrent/Producer.java // public class Producer<T extends Queueable> { // private BlockingQueue<T> queue; // // public Producer(BlockingQueue<T> queue) { // this.queue = queue; // } // // public void send(T message) { // try { // queue.put(message); // } catch (InterruptedException e) { // throw new RuntimeException(e); // } // } // } // Path: blog-code/src/main/java/pl/ciruk/blog/producerconsumer/web/PagesProcessor.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import pl.ciruk.blog.producerconsumer.concurrent.Consumer; import pl.ciruk.blog.producerconsumer.concurrent.Processable; import pl.ciruk.blog.producerconsumer.concurrent.Producer; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; package pl.ciruk.blog.producerconsumer.web; public class PagesProcessor { Map<String, Producer<Page>> producers = new HashMap<>(); ExecutorService executor = Executors.newFixedThreadPool(4); public void createProducer(final String producerId) { BlockingQueue<Page> queue = new LinkedBlockingQueue<Page>(); Producer<Page> producer = new Producer<>(queue); producers.put(producerId, producer);
Consumer<Page> consumer = new Consumer<>(queue, new Processable<Page>() {
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/jms/MockDestinationIntegrationTest.java
// Path: blog-code/src/main/java/pl/ciruk/blog/mq/MQConfiguration.java // @Configuration // @EnableJms // public class MQConfiguration { // @Bean // public PlatformTransactionManager platformTransactionManager(ConnectionFactory connectionFactory) { // return new JmsTransactionManager(connectionFactory); // } // // @Bean // public DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory(PlatformTransactionManager transactionManager, ConnectionFactory connectionFactory) { // DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); // factory.setConnectionFactory(connectionFactory); // factory.setTransactionManager(transactionManager); // factory.setConcurrency("5-10"); // factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); // factory.setSessionTransacted(true); // return factory; // } // // @Bean // public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) { // JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory); // return jmsTemplate; // } // // @Bean // public Consumer<String> messageConsumer() { // return System.out::println; // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.core.JmsTemplate; import org.springframework.test.context.junit4.SpringRunner; import pl.ciruk.blog.mq.MQConfiguration; import javax.inject.Inject; import java.util.concurrent.TimeUnit; import java.util.function.Function;
@Test public void shouldPrintTwoReceivedMessagesAndRespondToOne() throws Exception { mockDestination .whenReceived(message -> message.equals(FIRST_MESSAGE)) .thenSend(RESPONSE_QUEUE, message -> message + " acknowledged"); mockDestination .whenReceived(message -> message.startsWith("A")) .thenConsume(message -> System.out.println("Received: " + message)); send(FIRST_MESSAGE); send(SECOND_MESSAGE); System.out.println(jmsTemplate.receiveAndConvert(RESPONSE_QUEUE)); } private void send(String firstMessage) { waitAMoment(); jmsTemplate.convertAndSend("RequestQueue", firstMessage); } private void waitAMoment() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { Thread.interrupted(); } } @Configuration
// Path: blog-code/src/main/java/pl/ciruk/blog/mq/MQConfiguration.java // @Configuration // @EnableJms // public class MQConfiguration { // @Bean // public PlatformTransactionManager platformTransactionManager(ConnectionFactory connectionFactory) { // return new JmsTransactionManager(connectionFactory); // } // // @Bean // public DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory(PlatformTransactionManager transactionManager, ConnectionFactory connectionFactory) { // DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); // factory.setConnectionFactory(connectionFactory); // factory.setTransactionManager(transactionManager); // factory.setConcurrency("5-10"); // factory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); // factory.setSessionTransacted(true); // return factory; // } // // @Bean // public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) { // JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory); // return jmsTemplate; // } // // @Bean // public Consumer<String> messageConsumer() { // return System.out::println; // } // } // Path: blog-code/src/test/java/pl/ciruk/blog/jms/MockDestinationIntegrationTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.core.JmsTemplate; import org.springframework.test.context.junit4.SpringRunner; import pl.ciruk.blog.mq.MQConfiguration; import javax.inject.Inject; import java.util.concurrent.TimeUnit; import java.util.function.Function; @Test public void shouldPrintTwoReceivedMessagesAndRespondToOne() throws Exception { mockDestination .whenReceived(message -> message.equals(FIRST_MESSAGE)) .thenSend(RESPONSE_QUEUE, message -> message + " acknowledged"); mockDestination .whenReceived(message -> message.startsWith("A")) .thenConsume(message -> System.out.println("Received: " + message)); send(FIRST_MESSAGE); send(SECOND_MESSAGE); System.out.println(jmsTemplate.receiveAndConvert(RESPONSE_QUEUE)); } private void send(String firstMessage) { waitAMoment(); jmsTemplate.convertAndSend("RequestQueue", firstMessage); } private void waitAMoment() { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { Thread.interrupted(); } } @Configuration
static class TestConfiguration extends MQConfiguration {
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // }
import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice;
package pl.ciruk.blog.jpa_unit_tests; public class SampleEntityTest { @Inject private EntityManager entityManager; @Inject
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // } // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice; package pl.ciruk.blog.jpa_unit_tests; public class SampleEntityTest { @Inject private EntityManager entityManager; @Inject
private MyJpaInitializer jpaInitializer;
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // }
import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice;
package pl.ciruk.blog.jpa_unit_tests; public class SampleEntityTest { @Inject private EntityManager entityManager; @Inject private MyJpaInitializer jpaInitializer; @Before public void setUp() {
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // } // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice; package pl.ciruk.blog.jpa_unit_tests; public class SampleEntityTest { @Inject private EntityManager entityManager; @Inject private MyJpaInitializer jpaInitializer; @Before public void setUp() {
Guice.createInjector(new MyGuiceModule()).injectMembers(this);
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // }
import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice;
@After public void cleanUp() { entityManager.getTransaction().rollback(); jpaInitializer.stopService(); } @Test public void shouldRetrieveEntitiesWithAmountBelowThreshold() { int numberOfMockEntities = 100; List<SampleEntity> mockEntities = Entities.mockListOf(SampleEntity.class, numberOfMockEntities); double amountThreshold = 0.75; long numberOfEntitesWithAmountBelowThreshold = mockEntities.stream() .filter(entity -> entity.getAmount() < amountThreshold) .count(); mockEntities.stream() .forEach(entityManager::persist); @SuppressWarnings("unchecked") List<SampleEntity> actualEntities = entityManager .createNamedQuery(SampleEntity.Query.WITH_AMOUNT_BELOW) .setParameter("amountThreshold", amountThreshold) .getResultList(); assertThat(actualEntities.stream().count(), is(equalTo(numberOfEntitesWithAmountBelowThreshold))); assertThat(actualEntities, allOf(
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // } // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice; @After public void cleanUp() { entityManager.getTransaction().rollback(); jpaInitializer.stopService(); } @Test public void shouldRetrieveEntitiesWithAmountBelowThreshold() { int numberOfMockEntities = 100; List<SampleEntity> mockEntities = Entities.mockListOf(SampleEntity.class, numberOfMockEntities); double amountThreshold = 0.75; long numberOfEntitesWithAmountBelowThreshold = mockEntities.stream() .filter(entity -> entity.getAmount() < amountThreshold) .count(); mockEntities.stream() .forEach(entityManager::persist); @SuppressWarnings("unchecked") List<SampleEntity> actualEntities = entityManager .createNamedQuery(SampleEntity.Query.WITH_AMOUNT_BELOW) .setParameter("amountThreshold", amountThreshold) .getResultList(); assertThat(actualEntities.stream().count(), is(equalTo(numberOfEntitesWithAmountBelowThreshold))); assertThat(actualEntities, allOf(
everyItem(isInCollection(mockEntities)),
cpiotr/blog
blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // }
import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice;
public void cleanUp() { entityManager.getTransaction().rollback(); jpaInitializer.stopService(); } @Test public void shouldRetrieveEntitiesWithAmountBelowThreshold() { int numberOfMockEntities = 100; List<SampleEntity> mockEntities = Entities.mockListOf(SampleEntity.class, numberOfMockEntities); double amountThreshold = 0.75; long numberOfEntitesWithAmountBelowThreshold = mockEntities.stream() .filter(entity -> entity.getAmount() < amountThreshold) .count(); mockEntities.stream() .forEach(entityManager::persist); @SuppressWarnings("unchecked") List<SampleEntity> actualEntities = entityManager .createNamedQuery(SampleEntity.Query.WITH_AMOUNT_BELOW) .setParameter("amountThreshold", amountThreshold) .getResultList(); assertThat(actualEntities.stream().count(), is(equalTo(numberOfEntitesWithAmountBelowThreshold))); assertThat(actualEntities, allOf( everyItem(isInCollection(mockEntities)),
// Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/CollectionMatchers.java // public static <T> Matcher<T> isInCollection(Collection<T> collection) { // return new TypeSafeMatcher<T>() { // // @Override // public void describeTo(Description description) { // description.appendText("in collection: ") // .appendValueList("[", ",", "]", collection); // } // // @Override // protected boolean matchesSafely(T item) { // return collection.contains(item); // } // // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityMatchers.java // public static Matcher<SampleEntity> hasAmountLowerThan(double threshold) { // return new TypeSafeMatcher<SampleEntity>() { // @Override // public void describeTo(Description description) { // description.appendText("having amount lower than") // .appendValue(threshold); // } // // @Override // protected boolean matchesSafely(SampleEntity item) { // return item.getAmount() < threshold; // } // }; // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyGuiceModule.java // public class MyGuiceModule extends AbstractModule { // // @Override // protected void configure() { // install(new JpaPersistModule("my-persistence-unit")); // // bind(MyJpaInitializer.class).asEagerSingleton(); // } // } // // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/conf/MyJpaInitializer.java // public class MyJpaInitializer { // private PersistService persistService; // // @Inject // MyJpaInitializer(PersistService service) { // persistService = service; // persistService.start(); // } // // public void stopService() { // persistService.stop(); // } // } // Path: blog-code/src/test/java/pl/ciruk/blog/jpa_unit_tests/SampleEntityTest.java import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.everyItem; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static pl.ciruk.blog.jpa_unit_tests.CollectionMatchers.isInCollection; import static pl.ciruk.blog.jpa_unit_tests.SampleEntityMatchers.hasAmountLowerThan; import java.util.List; import javax.inject.Inject; import javax.persistence.EntityManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import pl.ciruk.blog.jpa_unit_tests.conf.MyGuiceModule; import pl.ciruk.blog.jpa_unit_tests.conf.MyJpaInitializer; import com.google.inject.Guice; public void cleanUp() { entityManager.getTransaction().rollback(); jpaInitializer.stopService(); } @Test public void shouldRetrieveEntitiesWithAmountBelowThreshold() { int numberOfMockEntities = 100; List<SampleEntity> mockEntities = Entities.mockListOf(SampleEntity.class, numberOfMockEntities); double amountThreshold = 0.75; long numberOfEntitesWithAmountBelowThreshold = mockEntities.stream() .filter(entity -> entity.getAmount() < amountThreshold) .count(); mockEntities.stream() .forEach(entityManager::persist); @SuppressWarnings("unchecked") List<SampleEntity> actualEntities = entityManager .createNamedQuery(SampleEntity.Query.WITH_AMOUNT_BELOW) .setParameter("amountThreshold", amountThreshold) .getResultList(); assertThat(actualEntities.stream().count(), is(equalTo(numberOfEntitesWithAmountBelowThreshold))); assertThat(actualEntities, allOf( everyItem(isInCollection(mockEntities)),
everyItem(hasAmountLowerThan(amountThreshold))
liying2008/neu-ipgw
app/src/main/java/lxy/liying/ipgw/post/ConnectPC.java
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // }
import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl;
package lxy.liying.ipgw.post; /** * 连接网络 * * @author 李颖 */ class ConnectPC { private static Request<String> mRequest; /** * 静态方法,连接网络 * * @param uid 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String connectPC(String uid, String password) throws UnknownHostException { // 创建请求
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // } // Path: app/src/main/java/lxy/liying/ipgw/post/ConnectPC.java import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl; package lxy.liying.ipgw.post; /** * 连接网络 * * @author 李颖 */ class ConnectPC { private static Request<String> mRequest; /** * 静态方法,连接网络 * * @param uid 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String connectPC(String uid, String password) throws UnknownHostException { // 创建请求
mRequest = NoHttp.createStringRequest(IPGWUrl.PC_POST_CONNECT_URL, RequestMethod.POST);
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/widget/IpgwWidgetProvider.java
// Path: app/src/main/java/com/liying/ipgw/utils/Constants.java // public interface Constants { // String INSIDE_CHINA = "2"; // /** Activity传递的Intent数据的key */ // String PROGRAM = "program"; // /** Sharedpreferences的名字 */ // String PREFS_NAME = "spc"; // /** 存储彩蛋信息的Sharedpreferences的名字 */ // String EGG_PREFS_NAME = "egg"; // /** Sharedpreferences储存的版本号 */ // String VERSION = "VERSION_CODE"; // /** Sharedpreferences储存的默认帐号 */ // String DEFAULT_ACCOUNT = "DEFAULT_ACCOUNT"; // /** Sharedpreferences储存的临时语言 */ // String TEMP_LANGUAGE = "TEMP_LANGUAGE"; // /** Sharedpreferences储存的默认语言 */ // String DEFAULT_LANGUAGE = "DEFAULT_LANGUAGE"; // /** Sharedpreferences储存的连接IP地址 */ // String IP_ADDRESS = "IP_ADDRESS"; // /** Sharedpreferences储存的色彩主题 */ // String COLOR_THEME = "COLOR_THEME"; // /** Sharedpreferences储存的已接收到的推送的id */ // String PUSH_ID = "PUSH_ID"; // /** Sharedpreferences储存的彩蛋集合 */ // String EGG_SET = "eggset"; // /** Sharedpreferences储存的彩蛋收纳盒是否显示 */ // String EGG_BOX = "eggbox"; // // String IPGW_DIR = "neuipgw"; // /** // * 工作目录 // */ // String WORK_DIR = Environment.getExternalStorageDirectory() + File.separator + IPGW_DIR; // /** // * ResultCode:选择快递 // */ // int SHIPPER_RESULT = 1; // /** // * 友盟统计相关常量 // */ // interface UmengStatistics { // /** 连接网络 */ // String CONNECT_CLICK = "connect_click"; // /** 断开网络 */ // String DISCONNECT_CLICK = "disconnect_click"; // /** 查询流量信息 */ // String QUERY_FLOW = "query_flow"; // /** 从浏览器登录 */ // String IPGW_BROSWER = "ipgw_broswer"; // /** 关于IPGW */ // String ABOUT_IPGW = "about_ipgw"; // /** 分享IPGW */ // String SHARE_IPGW = "share_ipgw"; // /** 桌面小工具 */ // String IPGW_TOOL = "ipgw_tool"; // /** 网址导航 */ // String NEU_NAVIGATOR = "neu_navigator"; // /** 用户反馈 */ // String USER_FEEDBACK = "user_feedback"; // /** 看电视 */ // String WATCH_TV = "watch_tv"; // /** 查看校历 */ // String SCHOOL_CALENDER = "school_calender"; // /** 关于作者 */ // String ABOUT_AUTHOR = "about_author"; // /** 色彩主题 */ // String COLOR_THEME = "color_theme"; // /** 检查更新 */ // String CHECK_UPDATE = "check_update"; // /** 彩蛋收纳盒 */ // String EGG_BOX = "egg_box"; // /** 最新网络中心黑板报 */ // String RECENT_POSTS = "recent_posts"; // /** 应用通知 */ // String APP_FAQ = "app_faq"; // /** 快递查询 */ // String EXPRESS_QUERY = "express_query"; // /** 彩蛋 */ // String EGG = "egg"; // } // // }
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import com.liying.ipgw.utils.Constants; import com.umeng.analytics.MobclickAgent;
package com.liying.ipgw.widget; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/6 15:56 * 版本:1.0 * 描述: * 备注: * ======================================================= */ public class IpgwWidgetProvider extends AppWidgetProvider { /** * 更新由这个提供程序创建的小部件时,这个方法会被调用 * 通常情况下,以下情况会调用该方法: * 1、开始创建小部件 * 2、达到AppWidgetProviderInfo中定义的updatePeriodMillis时间间隔 * 3、AppWidgetManager中的updateAppWidget()方法被手动调用 * * @param context * @param appWidgetManager * @param appWidgetIds */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); // 友盟统计:桌面小工具
// Path: app/src/main/java/com/liying/ipgw/utils/Constants.java // public interface Constants { // String INSIDE_CHINA = "2"; // /** Activity传递的Intent数据的key */ // String PROGRAM = "program"; // /** Sharedpreferences的名字 */ // String PREFS_NAME = "spc"; // /** 存储彩蛋信息的Sharedpreferences的名字 */ // String EGG_PREFS_NAME = "egg"; // /** Sharedpreferences储存的版本号 */ // String VERSION = "VERSION_CODE"; // /** Sharedpreferences储存的默认帐号 */ // String DEFAULT_ACCOUNT = "DEFAULT_ACCOUNT"; // /** Sharedpreferences储存的临时语言 */ // String TEMP_LANGUAGE = "TEMP_LANGUAGE"; // /** Sharedpreferences储存的默认语言 */ // String DEFAULT_LANGUAGE = "DEFAULT_LANGUAGE"; // /** Sharedpreferences储存的连接IP地址 */ // String IP_ADDRESS = "IP_ADDRESS"; // /** Sharedpreferences储存的色彩主题 */ // String COLOR_THEME = "COLOR_THEME"; // /** Sharedpreferences储存的已接收到的推送的id */ // String PUSH_ID = "PUSH_ID"; // /** Sharedpreferences储存的彩蛋集合 */ // String EGG_SET = "eggset"; // /** Sharedpreferences储存的彩蛋收纳盒是否显示 */ // String EGG_BOX = "eggbox"; // // String IPGW_DIR = "neuipgw"; // /** // * 工作目录 // */ // String WORK_DIR = Environment.getExternalStorageDirectory() + File.separator + IPGW_DIR; // /** // * ResultCode:选择快递 // */ // int SHIPPER_RESULT = 1; // /** // * 友盟统计相关常量 // */ // interface UmengStatistics { // /** 连接网络 */ // String CONNECT_CLICK = "connect_click"; // /** 断开网络 */ // String DISCONNECT_CLICK = "disconnect_click"; // /** 查询流量信息 */ // String QUERY_FLOW = "query_flow"; // /** 从浏览器登录 */ // String IPGW_BROSWER = "ipgw_broswer"; // /** 关于IPGW */ // String ABOUT_IPGW = "about_ipgw"; // /** 分享IPGW */ // String SHARE_IPGW = "share_ipgw"; // /** 桌面小工具 */ // String IPGW_TOOL = "ipgw_tool"; // /** 网址导航 */ // String NEU_NAVIGATOR = "neu_navigator"; // /** 用户反馈 */ // String USER_FEEDBACK = "user_feedback"; // /** 看电视 */ // String WATCH_TV = "watch_tv"; // /** 查看校历 */ // String SCHOOL_CALENDER = "school_calender"; // /** 关于作者 */ // String ABOUT_AUTHOR = "about_author"; // /** 色彩主题 */ // String COLOR_THEME = "color_theme"; // /** 检查更新 */ // String CHECK_UPDATE = "check_update"; // /** 彩蛋收纳盒 */ // String EGG_BOX = "egg_box"; // /** 最新网络中心黑板报 */ // String RECENT_POSTS = "recent_posts"; // /** 应用通知 */ // String APP_FAQ = "app_faq"; // /** 快递查询 */ // String EXPRESS_QUERY = "express_query"; // /** 彩蛋 */ // String EGG = "egg"; // } // // } // Path: app/src/main/java/com/liying/ipgw/widget/IpgwWidgetProvider.java import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import com.liying.ipgw.utils.Constants; import com.umeng.analytics.MobclickAgent; package com.liying.ipgw.widget; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/6 15:56 * 版本:1.0 * 描述: * 备注: * ======================================================= */ public class IpgwWidgetProvider extends AppWidgetProvider { /** * 更新由这个提供程序创建的小部件时,这个方法会被调用 * 通常情况下,以下情况会调用该方法: * 1、开始创建小部件 * 2、达到AppWidgetProviderInfo中定义的updatePeriodMillis时间间隔 * 3、AppWidgetManager中的updateAppWidget()方法被手动调用 * * @param context * @param appWidgetManager * @param appWidgetIds */ @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); // 友盟统计:桌面小工具
MobclickAgent.onEvent(context, Constants.UmengStatistics.IPGW_TOOL);
liying2008/neu-ipgw
app/src/main/java/lxy/liying/ipgw/post/Connect.java
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // }
import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl;
package lxy.liying.ipgw.post; /** * 连接网络 * * @author 李颖 */ class Connect { private static Request<String> mRequest; /** * 静态方法,连接网络 * * @param uid 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String connect(String uid, String password) throws UnknownHostException { // 创建请求
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // } // Path: app/src/main/java/lxy/liying/ipgw/post/Connect.java import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl; package lxy.liying.ipgw.post; /** * 连接网络 * * @author 李颖 */ class Connect { private static Request<String> mRequest; /** * 静态方法,连接网络 * * @param uid 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String connect(String uid, String password) throws UnknownHostException { // 创建请求
mRequest = NoHttp.createStringRequest(IPGWUrl.POST_CONNECT_URL, RequestMethod.POST);
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/db/DBInfo.java
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // } // // Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // }
import com.liying.ipgw.model.AccountInfo; import com.liying.ipgw.model.Express;
package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:29 * 版本:1.0 * 描述:数据库常量信息 * 备注: * ======================================================= */ class DBInfo { /** * 数据库名称 */ public static final String DB_NAME = "AutoConnect.db"; /** * 数据库版本 * version 1: 初始版本 * version 2: 加入range字段 * version 3: 新增Express表 * */ public static final int DB_VERSION = 3; /** * 数据表 * * @author 李颖 */ public static class Table { public static final String ACCOUNT_TB_NAME = "UserAccount";
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // } // // Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // } // Path: app/src/main/java/com/liying/ipgw/db/DBInfo.java import com.liying.ipgw.model.AccountInfo; import com.liying.ipgw.model.Express; package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:29 * 版本:1.0 * 描述:数据库常量信息 * 备注: * ======================================================= */ class DBInfo { /** * 数据库名称 */ public static final String DB_NAME = "AutoConnect.db"; /** * 数据库版本 * version 1: 初始版本 * version 2: 加入range字段 * version 3: 新增Express表 * */ public static final int DB_VERSION = 3; /** * 数据表 * * @author 李颖 */ public static class Table { public static final String ACCOUNT_TB_NAME = "UserAccount";
public static final String EXPRESS_TB_NAME = "Express";
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/db/DBInfo.java
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // } // // Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // }
import com.liying.ipgw.model.AccountInfo; import com.liying.ipgw.model.Express;
package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:29 * 版本:1.0 * 描述:数据库常量信息 * 备注: * ======================================================= */ class DBInfo { /** * 数据库名称 */ public static final String DB_NAME = "AutoConnect.db"; /** * 数据库版本 * version 1: 初始版本 * version 2: 加入range字段 * version 3: 新增Express表 * */ public static final int DB_VERSION = 3; /** * 数据表 * * @author 李颖 */ public static class Table { public static final String ACCOUNT_TB_NAME = "UserAccount"; public static final String EXPRESS_TB_NAME = "Express"; public static final String ACCOUNT_TB_CREATE = "create table if not exists " + ACCOUNT_TB_NAME + " (" +
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // } // // Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // } // Path: app/src/main/java/com/liying/ipgw/db/DBInfo.java import com.liying.ipgw.model.AccountInfo; import com.liying.ipgw.model.Express; package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:29 * 版本:1.0 * 描述:数据库常量信息 * 备注: * ======================================================= */ class DBInfo { /** * 数据库名称 */ public static final String DB_NAME = "AutoConnect.db"; /** * 数据库版本 * version 1: 初始版本 * version 2: 加入range字段 * version 3: 新增Express表 * */ public static final int DB_VERSION = 3; /** * 数据表 * * @author 李颖 */ public static class Table { public static final String ACCOUNT_TB_NAME = "UserAccount"; public static final String EXPRESS_TB_NAME = "Express"; public static final String ACCOUNT_TB_CREATE = "create table if not exists " + ACCOUNT_TB_NAME + " (" +
AccountInfo.USERNAME + " varchar(20), " +
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/adapter/ColorThemeListAdapter.java
// Path: app/src/main/java/com/liying/ipgw/model/ColorTheme.java // public class ColorTheme { // /** 主题位置 */ // private int position; // /** 主题名称 */ // private String themeName; // /** 预览图片的Drawable id */ // private int themePreId; // /** 是否选中 */ // private boolean isSelected; // /** 主题style id */ // private int styleId; // // public ColorTheme() { // } // // public ColorTheme(int position, String themeName, int themePreId, boolean isSelected, int styleId) { // this.position = position; // this.themeName = themeName; // this.themePreId = themePreId; // this.isSelected = isSelected; // this.styleId = styleId; // } // // public int getPosition() { // return position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getThemeName() { // return themeName; // } // // public void setThemeName(String themeName) { // this.themeName = themeName; // } // // public int getThemePreId() { // return themePreId; // } // // public void setThemePreId(int themePreId) { // this.themePreId = themePreId; // } // // public boolean isSelected() { // return isSelected; // } // // public void setSelected(boolean selected) { // isSelected = selected; // } // // public int getStyleId() { // return styleId; // } // // public void setStyleId(int styleId) { // this.styleId = styleId; // } // } // // Path: app/src/main/java/com/liying/ipgw/utils/DensityUtil.java // public class DensityUtil { // private static int[] deviceWidthHeight = new int[2]; // public static int[] getDeviceInfo(Context context) { // if ((deviceWidthHeight[0] == 0) && (deviceWidthHeight[1] == 0)) { // DisplayMetrics metrics = new DisplayMetrics(); // ((Activity) context).getWindowManager().getDefaultDisplay() // .getMetrics(metrics); // // deviceWidthHeight[0] = metrics.widthPixels; // deviceWidthHeight[1] = metrics.heightPixels; // } // return deviceWidthHeight; // } // /** // * // * @param context 上下文 // * @param dpValue dp数值 // * @return dp to px // */ // public static int dip2px(Context context, float dpValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dpValue * scale + 0.5f); // // } // /** // * 获取屏幕尺寸 // */ // @SuppressWarnings("deprecation") // @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) // public static Point getScreenSize(Context context){ // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2){ // return new Point(display.getWidth(), display.getHeight()); // }else{ // Point point = new Point(); // display.getSize(point); // return point; // } // } // /** // * // * @param context 上下文 // * @param pxValue px的数值 // * @return px to dp // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.model.ColorTheme; import com.liying.ipgw.utils.DensityUtil;
package com.liying.ipgw.adapter; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/4 19:58 * 版本:1.0 * 描述:色彩主题列表适配器 * 备注: * ======================================================= */ public class ColorThemeListAdapter extends RecyclerView.Adapter<ColorThemeListAdapter.ViewHolder> { private Context context;
// Path: app/src/main/java/com/liying/ipgw/model/ColorTheme.java // public class ColorTheme { // /** 主题位置 */ // private int position; // /** 主题名称 */ // private String themeName; // /** 预览图片的Drawable id */ // private int themePreId; // /** 是否选中 */ // private boolean isSelected; // /** 主题style id */ // private int styleId; // // public ColorTheme() { // } // // public ColorTheme(int position, String themeName, int themePreId, boolean isSelected, int styleId) { // this.position = position; // this.themeName = themeName; // this.themePreId = themePreId; // this.isSelected = isSelected; // this.styleId = styleId; // } // // public int getPosition() { // return position; // } // // public void setPosition(int position) { // this.position = position; // } // // public String getThemeName() { // return themeName; // } // // public void setThemeName(String themeName) { // this.themeName = themeName; // } // // public int getThemePreId() { // return themePreId; // } // // public void setThemePreId(int themePreId) { // this.themePreId = themePreId; // } // // public boolean isSelected() { // return isSelected; // } // // public void setSelected(boolean selected) { // isSelected = selected; // } // // public int getStyleId() { // return styleId; // } // // public void setStyleId(int styleId) { // this.styleId = styleId; // } // } // // Path: app/src/main/java/com/liying/ipgw/utils/DensityUtil.java // public class DensityUtil { // private static int[] deviceWidthHeight = new int[2]; // public static int[] getDeviceInfo(Context context) { // if ((deviceWidthHeight[0] == 0) && (deviceWidthHeight[1] == 0)) { // DisplayMetrics metrics = new DisplayMetrics(); // ((Activity) context).getWindowManager().getDefaultDisplay() // .getMetrics(metrics); // // deviceWidthHeight[0] = metrics.widthPixels; // deviceWidthHeight[1] = metrics.heightPixels; // } // return deviceWidthHeight; // } // /** // * // * @param context 上下文 // * @param dpValue dp数值 // * @return dp to px // */ // public static int dip2px(Context context, float dpValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (dpValue * scale + 0.5f); // // } // /** // * 获取屏幕尺寸 // */ // @SuppressWarnings("deprecation") // @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) // public static Point getScreenSize(Context context){ // WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // Display display = windowManager.getDefaultDisplay(); // if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2){ // return new Point(display.getWidth(), display.getHeight()); // }else{ // Point point = new Point(); // display.getSize(point); // return point; // } // } // /** // * // * @param context 上下文 // * @param pxValue px的数值 // * @return px to dp // */ // public static int px2dip(Context context, float pxValue) { // final float scale = context.getResources().getDisplayMetrics().density; // return (int) (pxValue / scale + 0.5f); // // } // } // Path: app/src/main/java/com/liying/ipgw/adapter/ColorThemeListAdapter.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.model.ColorTheme; import com.liying.ipgw.utils.DensityUtil; package com.liying.ipgw.adapter; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/4 19:58 * 版本:1.0 * 描述:色彩主题列表适配器 * 备注: * ======================================================= */ public class ColorThemeListAdapter extends RecyclerView.Adapter<ColorThemeListAdapter.ViewHolder> { private Context context;
private ColorTheme[] colorThemes;
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/adapter/RecommendListAdapter.java
// Path: app/src/main/java/com/liying/ipgw/activity/RecommendActivity.java // public class RecommendActivity extends BaseActivity { // private static WeakReference<RecommendActivity> recommendActivity; // // // 图标数组 // private static int[] icons = {R.mipmap.xdp_512x512, R.mipmap.sec_512x512, R.mipmap.circle_512x512}; // // 软件名称数组 // private static int[] name = {R.string.recommend_name_xdp, R.string.recommend_name_sec, R.string.recommend_name_circle}; // // 软件描述数组 // private static int[] desc = {R.string.recommend_desc_xdp, R.string.recommend_desc_sec, R.string.recommend_desc_circle}; // // 软件包名 // public static String[] packageName = {"lxy.liying.hdtvneu", "lxy.liying.secbook", "lxy.liying.circletodo"}; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_recommend); // AccountApp.activityList.add(this); // TextView tvBack = (TextView) findViewById(R.id.tvBack); // tvBack.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // finish(); // } // }); // ListView lvRecommend = (ListView) findViewById(R.id.lvRecommend); // RecommendListAdapter adapter = new RecommendListAdapter(this, icons, name, desc); // lvRecommend.setAdapter(adapter); // // recommendActivity = new WeakReference<RecommendActivity>(this); // } // // /** // * 获取本Activity的实例 // * @return // */ // public static RecommendActivity getInstance() { // return recommendActivity.get(); // } // // /** // * 跳到应用商店的下载页面 // * @param packageName 应用的包名 // */ // public void goToDownload(String packageName) { // Uri uri = Uri.parse("market://details?id=" + packageName); // Intent intent = new Intent(Intent.ACTION_VIEW, uri); // ComponentName componentName = intent.resolveActivity(getPackageManager()); // if (componentName != null) { // startActivity(intent); // } else { // AppToast.showToast("您没有安装应用市场类软件,无法打开应用详情页面。"); // } // } // // @Override // protected void onDestroy() { // super.onDestroy(); // AccountApp.activityList.remove(this); // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.activity.RecommendActivity;
@Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ListItemView listItemView = null; if (convertView == null){ listItemView = new ListItemView(); //获取list_item布局文件的视图 convertView = listContainer.inflate(R.layout.item_recommend, null); listItemView.ivRecommendIcon = (ImageView) convertView.findViewById(R.id.ivRecommendIcon); listItemView.tvRecommendName = (TextView) convertView.findViewById(R.id.tvRecommendName); listItemView.tvRecommendDesc = (TextView) convertView.findViewById(R.id.tvRecommendDesc); listItemView.btnDownload = (Button) convertView.findViewById(R.id.btnDownload); //设置控件集到convertView convertView.setTag(listItemView); } else { listItemView = (ListItemView)convertView.getTag(); } listItemView.ivRecommendIcon.setImageResource(icons[position]); listItemView.tvRecommendName.setText(name[position]); listItemView.tvRecommendDesc.setText(desc[position]); listItemView.btnDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
// Path: app/src/main/java/com/liying/ipgw/activity/RecommendActivity.java // public class RecommendActivity extends BaseActivity { // private static WeakReference<RecommendActivity> recommendActivity; // // // 图标数组 // private static int[] icons = {R.mipmap.xdp_512x512, R.mipmap.sec_512x512, R.mipmap.circle_512x512}; // // 软件名称数组 // private static int[] name = {R.string.recommend_name_xdp, R.string.recommend_name_sec, R.string.recommend_name_circle}; // // 软件描述数组 // private static int[] desc = {R.string.recommend_desc_xdp, R.string.recommend_desc_sec, R.string.recommend_desc_circle}; // // 软件包名 // public static String[] packageName = {"lxy.liying.hdtvneu", "lxy.liying.secbook", "lxy.liying.circletodo"}; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_recommend); // AccountApp.activityList.add(this); // TextView tvBack = (TextView) findViewById(R.id.tvBack); // tvBack.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // finish(); // } // }); // ListView lvRecommend = (ListView) findViewById(R.id.lvRecommend); // RecommendListAdapter adapter = new RecommendListAdapter(this, icons, name, desc); // lvRecommend.setAdapter(adapter); // // recommendActivity = new WeakReference<RecommendActivity>(this); // } // // /** // * 获取本Activity的实例 // * @return // */ // public static RecommendActivity getInstance() { // return recommendActivity.get(); // } // // /** // * 跳到应用商店的下载页面 // * @param packageName 应用的包名 // */ // public void goToDownload(String packageName) { // Uri uri = Uri.parse("market://details?id=" + packageName); // Intent intent = new Intent(Intent.ACTION_VIEW, uri); // ComponentName componentName = intent.resolveActivity(getPackageManager()); // if (componentName != null) { // startActivity(intent); // } else { // AppToast.showToast("您没有安装应用市场类软件,无法打开应用详情页面。"); // } // } // // @Override // protected void onDestroy() { // super.onDestroy(); // AccountApp.activityList.remove(this); // } // } // Path: app/src/main/java/com/liying/ipgw/adapter/RecommendListAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.activity.RecommendActivity; @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ListItemView listItemView = null; if (convertView == null){ listItemView = new ListItemView(); //获取list_item布局文件的视图 convertView = listContainer.inflate(R.layout.item_recommend, null); listItemView.ivRecommendIcon = (ImageView) convertView.findViewById(R.id.ivRecommendIcon); listItemView.tvRecommendName = (TextView) convertView.findViewById(R.id.tvRecommendName); listItemView.tvRecommendDesc = (TextView) convertView.findViewById(R.id.tvRecommendDesc); listItemView.btnDownload = (Button) convertView.findViewById(R.id.btnDownload); //设置控件集到convertView convertView.setTag(listItemView); } else { listItemView = (ListItemView)convertView.getTag(); } listItemView.ivRecommendIcon.setImageResource(icons[position]); listItemView.tvRecommendName.setText(name[position]); listItemView.tvRecommendDesc.setText(desc[position]); listItemView.btnDownload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
RecommendActivity activity = RecommendActivity.getInstance();
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/adapter/TraceListAdapter.java
// Path: app/src/main/java/com/liying/ipgw/model/Trace.java // public class Trace { // /** 时间 */ // private String acceptTime; // /** 描述 */ // private String acceptStation; // /** 备注 */ // private String remark; // // public Trace() { // } // // public Trace(String acceptTime, String acceptStation, String remark) { // this.acceptTime = acceptTime; // this.acceptStation = acceptStation; // this.remark = remark; // } // // public String getAcceptTime() { // return acceptTime; // } // // public void setAcceptTime(String acceptTime) { // this.acceptTime = acceptTime; // } // // public String getAcceptStation() { // return acceptStation; // } // // public void setAcceptStation(String acceptStation) { // this.acceptStation = acceptStation; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.model.Trace; import java.util.ArrayList; import java.util.List;
package com.liying.ipgw.adapter; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/22 20:53 * 版本:1.0 * 描述:物流信息列表适配器 * 备注: * ======================================================= */ public class TraceListAdapter extends BaseAdapter { private LayoutInflater inflater;
// Path: app/src/main/java/com/liying/ipgw/model/Trace.java // public class Trace { // /** 时间 */ // private String acceptTime; // /** 描述 */ // private String acceptStation; // /** 备注 */ // private String remark; // // public Trace() { // } // // public Trace(String acceptTime, String acceptStation, String remark) { // this.acceptTime = acceptTime; // this.acceptStation = acceptStation; // this.remark = remark; // } // // public String getAcceptTime() { // return acceptTime; // } // // public void setAcceptTime(String acceptTime) { // this.acceptTime = acceptTime; // } // // public String getAcceptStation() { // return acceptStation; // } // // public void setAcceptStation(String acceptStation) { // this.acceptStation = acceptStation; // } // // public String getRemark() { // return remark; // } // // public void setRemark(String remark) { // this.remark = remark; // } // } // Path: app/src/main/java/com/liying/ipgw/adapter/TraceListAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.liying.ipgw.R; import com.liying.ipgw.model.Trace; import java.util.ArrayList; import java.util.List; package com.liying.ipgw.adapter; /** * ======================================================= * 作者:liying - [email protected] * 日期:2016/11/22 20:53 * 版本:1.0 * 描述:物流信息列表适配器 * 备注: * ======================================================= */ public class TraceListAdapter extends BaseAdapter { private LayoutInflater inflater;
private List<Trace> traceList = new ArrayList<>(1);
liying2008/neu-ipgw
app/src/main/java/lxy/liying/ipgw/info/GetConnInfo.java
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // }
import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.util.Locale; import lxy.liying.ipgw.url.IPGWUrl;
package lxy.liying.ipgw.info; /** * 得到在线信息类 */ public class GetConnInfo { /** * 得到连接用户的信息 例如: <br /> * 45223109,12623,45.00,,0,58.154.209.141 <br /> * 45278986,13189,45.00,,0,58.154.209.141 <br /> * 流量,时长,余额,,0,IP地址 * * @return */ private static String getConnInfoHtml() { // 创建请求
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // } // Path: app/src/main/java/lxy/liying/ipgw/info/GetConnInfo.java import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.util.Locale; import lxy.liying.ipgw.url.IPGWUrl; package lxy.liying.ipgw.info; /** * 得到在线信息类 */ public class GetConnInfo { /** * 得到连接用户的信息 例如: <br /> * 45223109,12623,45.00,,0,58.154.209.141 <br /> * 45278986,13189,45.00,,0,58.154.209.141 <br /> * 流量,时长,余额,,0,IP地址 * * @return */ private static String getConnInfoHtml() { // 创建请求
Request<String> request = NoHttp.createStringRequest(IPGWUrl.POST_DETAILS, RequestMethod.POST);
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/db/ExpressServices.java
// Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.liying.ipgw.model.Express; import java.util.ArrayList; import java.util.List;
package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:34 * 版本:1.0 * 描述:快递单信息存取操作 * 备注: * ======================================================= */ public class ExpressServices extends BaseDbService { private DatabaseHelper dbHelper;
// Path: app/src/main/java/com/liying/ipgw/model/Express.java // public class Express { // /** 时间戳 */ // private long time; // /** 快递单号 */ // private String expressCode; // /** 快递公司公司 */ // private String shipperName; // /** 快递公司编码 */ // private String shipperCode; // /** 备注 */ // private String mark; // // public static final String TIME = "time"; // public static final String EXPRESS_CODE = "expressCode"; // public static final String SHIPPER_NAME = "shipperName"; // public static final String SHIPPER_CODE = "shipperCode"; // public static final String MARK = "mark"; // // public Express() { // } // // public Express(String expressCode, String shipperName, String shipperCode, String mark) { // this.expressCode = expressCode; // this.shipperName = shipperName; // this.shipperCode = shipperCode; // this.mark = mark; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public String getExpressCode() { // return expressCode; // } // // public void setExpressCode(String expressCode) { // this.expressCode = expressCode; // } // // public String getShipperName() { // return shipperName; // } // // public void setShipperName(String shipperName) { // this.shipperName = shipperName; // } // // public String getShipperCode() { // return shipperCode; // } // // public void setShipperCode(String shipperCode) { // this.shipperCode = shipperCode; // } // // public String getMark() { // return mark; // } // // public void setMark(String mark) { // this.mark = mark; // } // } // Path: app/src/main/java/com/liying/ipgw/db/ExpressServices.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.liying.ipgw.model.Express; import java.util.ArrayList; import java.util.List; package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:34 * 版本:1.0 * 描述:快递单信息存取操作 * 备注: * ======================================================= */ public class ExpressServices extends BaseDbService { private DatabaseHelper dbHelper;
private String[] columns = {Express.TIME, Express.EXPRESS_CODE, Express.SHIPPER_NAME, Express.SHIPPER_CODE, Express.MARK};
liying2008/neu-ipgw
app/src/main/java/lxy/liying/ipgw/post/DisconnectAll.java
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // }
import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl;
package lxy.liying.ipgw.post; /** * 断开全部连接 * * @author 李颖 */ class DisconnectAll { private static Request<String> mRequest; /** * 静态方法,断开网络 * * @param username 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String disconnectAll(String username, String password) throws UnknownHostException { // 创建请求
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // } // Path: app/src/main/java/lxy/liying/ipgw/post/DisconnectAll.java import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl; package lxy.liying.ipgw.post; /** * 断开全部连接 * * @author 李颖 */ class DisconnectAll { private static Request<String> mRequest; /** * 静态方法,断开网络 * * @param username 用户名 * @param password 密码 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String disconnectAll(String username, String password) throws UnknownHostException { // 创建请求
mRequest = NoHttp.createStringRequest(IPGWUrl.POST_DISCONNECTALL_URL, RequestMethod.POST);
liying2008/neu-ipgw
app/src/main/java/lxy/liying/ipgw/post/Disconnect.java
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // }
import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl;
package lxy.liying.ipgw.post; /** * 断开网络 * * @author 李颖 */ class Disconnect { private static Request<String> mRequest; /** * 静态方法,断开网络 * * @param ip 用户连接的IP地址 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String disconnect(String ip) throws UnknownHostException { // 创建请求
// Path: app/src/main/java/lxy/liying/ipgw/url/IPGWUrl.java // public class IPGWUrl { // /** 连接网络的POST地址 */ // public static String POST_CONNECT_URL = ""; // /** 主机端连接网络的POST地址 */ // public static String PC_POST_CONNECT_URL = ""; // /** 断开网络的POST地址 */ // public static String POST_DISCONNECT_URL = ""; // /** 断开全部连接的POST地址 */ // public static String POST_DISCONNECTALL_URL = ""; // /** 获取详细信息的Post的服务器地址 */ // public static String POST_DETAILS = ""; // /** 获取详细信息的随机key */ // public static String KEY = ""; // // /** 静态块:用来初始化信息 */ // static { // POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // POST_DISCONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_phone.php?ac_id=1&"; // PC_POST_CONNECT_URL = "https://ipgw.neu.edu.cn/srun_portal_pc.php?ac_id=1&"; // POST_DISCONNECTALL_URL = "https://ipgw.neu.edu.cn/include/auth_action.php"; // KEY = String.valueOf(getRandomKey()); // POST_DETAILS = "https://ipgw.neu.edu.cn/include/auth_action.php?k=" + KEY; // } // // /** // * 得到5位的随机数key // * // * @return // */ // private static int getRandomKey() { // int key = (int) Math.floor(Math.random() * (100000 + 1)); // return key; // } // } // Path: app/src/main/java/lxy/liying/ipgw/post/Disconnect.java import com.yanzhenjie.nohttp.NoHttp; import com.yanzhenjie.nohttp.RequestMethod; import com.yanzhenjie.nohttp.rest.Request; import com.yanzhenjie.nohttp.rest.Response; import java.net.UnknownHostException; import lxy.liying.ipgw.url.IPGWUrl; package lxy.liying.ipgw.post; /** * 断开网络 * * @author 李颖 */ class Disconnect { private static Request<String> mRequest; /** * 静态方法,断开网络 * * @param ip 用户连接的IP地址 * @return 成功:Post结果,网页源代码。 失败:"提交数据失败" */ static String disconnect(String ip) throws UnknownHostException { // 创建请求
mRequest = NoHttp.createStringRequest(IPGWUrl.POST_DISCONNECT_URL, RequestMethod.POST);
liying2008/neu-ipgw
app/src/main/java/com/liying/ipgw/db/AccountInfoServices.java
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.liying.ipgw.model.AccountInfo; import java.util.ArrayList; import java.util.List;
package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:34 * 版本:1.0 * 描述:数据库操作层 * 备注: * ======================================================= */ public class AccountInfoServices extends BaseDbService { private DatabaseHelper dbHelper;
// Path: app/src/main/java/com/liying/ipgw/model/AccountInfo.java // public class AccountInfo { // // private String userName = null; // private String psw = null; // private String range = "2"; // // public static final String USERNAME = "userName"; // public static final String PSW = "psw"; // public static final String RANGE = "range"; // // /** // * AccountInfo的构造方法 // * @param userName 用户名 // * @param psw 密码 // * @param range 访问范围:1 国际 2 国内 // */ // public AccountInfo(String userName, String psw, String range) { // super(); // this.userName = userName; // this.psw = psw; // this.range = range; // } // // /** // * 无参构造方法 // */ // public AccountInfo() { // } // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public String getPsw() { // return psw; // } // public void setPsw(String psw) { // this.psw = psw; // } // public String getRange() { // return range; // } // public void setRange(String range) { // this.range = range; // } // } // Path: app/src/main/java/com/liying/ipgw/db/AccountInfoServices.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.liying.ipgw.model.AccountInfo; import java.util.ArrayList; import java.util.List; package com.liying.ipgw.db; /** * ======================================================= * 作者:liying - [email protected] * 日期:2015/12/06 12:34 * 版本:1.0 * 描述:数据库操作层 * 备注: * ======================================================= */ public class AccountInfoServices extends BaseDbService { private DatabaseHelper dbHelper;
private String[] columns = {AccountInfo.USERNAME, AccountInfo.PSW, AccountInfo.RANGE};
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // }
import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*;
package com.amanvishnani.sim8085.domain.Impl; public class Compiler { private final Parser parser; Map<Integer, InstructionRow> instructionRowMap; Map<String, Integer> labelMap; public Compiler(Parser parser) { this.parser = parser; this.resetParams(); } public Compiler() { this(new Parser()); } public ArrayList<InstructionRow> compile(String code) { this.resetParams(); List<String> instructions = parser.getLineInstructions(code); this.passOne(instructions); this.passTwo(); ArrayList<InstructionRow> rows = new ArrayList<>(instructionRowMap.values()); rows.sort(new InstructionSortByAddress()); return rows; } private void resetParams() { instructionRowMap = new HashMap<>(); labelMap = new HashMap<>(); } private void passOne(List<String> instructions) { int localPointer = 0; for (String lineInstruction : instructions) { // Get Opcode
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*; package com.amanvishnani.sim8085.domain.Impl; public class Compiler { private final Parser parser; Map<Integer, InstructionRow> instructionRowMap; Map<String, Integer> labelMap; public Compiler(Parser parser) { this.parser = parser; this.resetParams(); } public Compiler() { this(new Parser()); } public ArrayList<InstructionRow> compile(String code) { this.resetParams(); List<String> instructions = parser.getLineInstructions(code); this.passOne(instructions); this.passTwo(); ArrayList<InstructionRow> rows = new ArrayList<>(instructionRowMap.values()); rows.sort(new InstructionSortByAddress()); return rows; } private void resetParams() { instructionRowMap = new HashMap<>(); labelMap = new HashMap<>(); } private void passOne(List<String> instructions) { int localPointer = 0; for (String lineInstruction : instructions) { // Get Opcode
IOpcode opcode = parser.getOpcode(lineInstruction);
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // }
import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*;
private void resetParams() { instructionRowMap = new HashMap<>(); labelMap = new HashMap<>(); } private void passOne(List<String> instructions) { int localPointer = 0; for (String lineInstruction : instructions) { // Get Opcode IOpcode opcode = parser.getOpcode(lineInstruction); // extract label String label = parser.extractLabel(lineInstruction); if(!label.isEmpty()) { labelMap.put(label, localPointer); } InstructionRow row = InstructionRow.createInstructionRow(localPointer); row.setData(opcode.getOpcodeData()); row.setLabel(label); row.setInstruction(opcode.getInstruction()); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; // Opcode length = 2 if (opcode.getOpcodeLength() == 2) { // Data flow
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*; private void resetParams() { instructionRowMap = new HashMap<>(); labelMap = new HashMap<>(); } private void passOne(List<String> instructions) { int localPointer = 0; for (String lineInstruction : instructions) { // Get Opcode IOpcode opcode = parser.getOpcode(lineInstruction); // extract label String label = parser.extractLabel(lineInstruction); if(!label.isEmpty()) { labelMap.put(label, localPointer); } InstructionRow row = InstructionRow.createInstructionRow(localPointer); row.setData(opcode.getOpcodeData()); row.setLabel(label); row.setInstruction(opcode.getInstruction()); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; // Opcode length = 2 if (opcode.getOpcodeLength() == 2) { // Data flow
IData data = parser.extractData(lineInstruction);
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // }
import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*;
for (String lineInstruction : instructions) { // Get Opcode IOpcode opcode = parser.getOpcode(lineInstruction); // extract label String label = parser.extractLabel(lineInstruction); if(!label.isEmpty()) { labelMap.put(label, localPointer); } InstructionRow row = InstructionRow.createInstructionRow(localPointer); row.setData(opcode.getOpcodeData()); row.setLabel(label); row.setInstruction(opcode.getInstruction()); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; // Opcode length = 2 if (opcode.getOpcodeLength() == 2) { // Data flow IData data = parser.extractData(lineInstruction); row = InstructionRow.createInstructionRow(localPointer); row.setData(data); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; } // Opcode length = 3 else if (opcode.getOpcodeLength() == 3) {
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IOpcode.java // public interface IOpcode { // String getInstruction(); // IData getOpcodeData(); // Integer getOpcodeLength(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/Compiler.java import com.amanvishnani.sim8085.domain.IAddress; import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IOpcode; import java.util.*; for (String lineInstruction : instructions) { // Get Opcode IOpcode opcode = parser.getOpcode(lineInstruction); // extract label String label = parser.extractLabel(lineInstruction); if(!label.isEmpty()) { labelMap.put(label, localPointer); } InstructionRow row = InstructionRow.createInstructionRow(localPointer); row.setData(opcode.getOpcodeData()); row.setLabel(label); row.setInstruction(opcode.getInstruction()); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; // Opcode length = 2 if (opcode.getOpcodeLength() == 2) { // Data flow IData data = parser.extractData(lineInstruction); row = InstructionRow.createInstructionRow(localPointer); row.setData(data); instructionRowMap.put(localPointer, row); localPointer = localPointer + 1; } // Opcode length = 3 else if (opcode.getOpcodeLength() == 3) {
IAddress address = parser.extractOperandAddress(opcode.getInstruction());
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/MemorySlice.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // }
import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IMemory;
/* * 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 com.amanvishnani.sim8085.domain.Impl; /** * * @author Aman Vishnani */ public class MemorySlice implements IMemorySlice { Integer start, end; String[] data;
// Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/MemorySlice.java import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IMemory; /* * 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 com.amanvishnani.sim8085.domain.Impl; /** * * @author Aman Vishnani */ public class MemorySlice implements IMemorySlice { Integer start, end; String[] data;
IMemory memoryRef;
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/Memory.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // }
import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IMemory; import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IAddress;
/* * 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 com.amanvishnani.sim8085.domain.Impl; /** * * @author Aman Vishnani */ public class Memory implements IMemory { public IAddress[] memory; private void initMemory() { for(int i=0; i<65536; i++) { memory[i] = Address.from(i); } } private Memory() { memory = new IAddress[65536]; initMemory(); } public static IMemory makeMemory() { return new Memory(); } @Override public IAddress getAddress(Integer intAddress) { return memory[intAddress]; } @Override
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/Memory.java import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IMemory; import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IAddress; /* * 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 com.amanvishnani.sim8085.domain.Impl; /** * * @author Aman Vishnani */ public class Memory implements IMemory { public IAddress[] memory; private void initMemory() { for(int i=0; i<65536; i++) { memory[i] = Address.from(i); } } private Memory() { memory = new IAddress[65536]; initMemory(); } public static IMemory makeMemory() { return new Memory(); } @Override public IAddress getAddress(Integer intAddress) { return memory[intAddress]; } @Override
public IData getData(Integer intAddress) {
amanvishnani/8085
src/main/java/com/amanvishnani/sim8085/domain/Impl/Memory.java
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // }
import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IMemory; import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IAddress;
IAddress addr = Address.from(hexAddress); return getHexData(addr.intValue()); } @Override public void setData(IAddress address, IData data) { address.setData(data); memory[address.intValue()] = address; } @Override public void setData(IAddress address, String data) { IData hexData = Data.from(data); address.setData(hexData); memory[address.intValue()] = address; } @Override public void setData(String hexAddress, String data) { IAddress addr = Address.from(hexAddress); setData(addr, data); } @Override public void setData(Integer intAddress, String data) { IAddress addr = Address.from(intAddress); setData(addr.hexValue(), data); } @Override
// Path: src/main/java/com/amanvishnani/sim8085/domain/IAddress.java // public interface IAddress { // String hexValue(); // Integer intValue(); // IData getLSB(); // IData getMSB(); // IData getData(); // void setData(IData data); // static IAddress ZERO = Address.from(0); // static IAddress FFFF = Address.from("FFFF"); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IData.java // public interface IData { // IData ZERO = Data.from("00"); // String hexValue(); // Integer intValue(); // IOperationResult add(IData data); // IOperationResult add(IData data, Integer carry); // IOperationResult minus(IData data); // IRegister toRegister(); // public IData getLSB(); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemory.java // public interface IMemory { // IData getData(Integer intAddress); // IAddress getAddress(Integer intAddress); // String getHexData(Integer intAddress); // String getHexData(String hexAddress); // void setData(String hexAddress, String data); // void setData(Integer intAddress, String data); // void setData(IAddress address, String data); // void setData(IAddress address, IData data); // IMemorySlice getSlice(Integer start, Integer end); // } // // Path: src/main/java/com/amanvishnani/sim8085/domain/IMemorySlice.java // public interface IMemorySlice { // String[] getHexDataArray(); // } // Path: src/main/java/com/amanvishnani/sim8085/domain/Impl/Memory.java import com.amanvishnani.sim8085.domain.IData; import com.amanvishnani.sim8085.domain.IMemory; import com.amanvishnani.sim8085.domain.IMemorySlice; import com.amanvishnani.sim8085.domain.IAddress; IAddress addr = Address.from(hexAddress); return getHexData(addr.intValue()); } @Override public void setData(IAddress address, IData data) { address.setData(data); memory[address.intValue()] = address; } @Override public void setData(IAddress address, String data) { IData hexData = Data.from(data); address.setData(hexData); memory[address.intValue()] = address; } @Override public void setData(String hexAddress, String data) { IAddress addr = Address.from(hexAddress); setData(addr, data); } @Override public void setData(Integer intAddress, String data) { IAddress addr = Address.from(intAddress); setData(addr.hexValue(), data); } @Override
public IMemorySlice getSlice(Integer start, Integer end) {