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
NineWorlds/serenity-android
serenity-app/src/main/java/us/nineworlds/serenity/jobs/SubtitleJob.java
// Path: serenity-common/src/main/java/us/nineworlds/serenity/common/media/model/IMediaContainer.java // public interface IMediaContainer { // String getTitle2(); // // void setTitle2(String title2); // // List<IDirectory> getDirectories(); // // void setDirectories(List<IDirectory> directory); // // int getSize(); // // void setSize(int size); // // int getAllowSync(); // // void setAllowSync(int allowSync); // // String getIdentifier(); // // void setIdentifier(String identifier); // // String getMediaTagPrefix(); // // void setMediaTagPrefix(String mediaTagPrefix); // // long getMediaTagVersion(); // // String getArt(); // // void setArt(String art); // // int getSortAsc(); // // void setSortAsc(int sortAsc); // // String getContent(); // // void setContent(String content); // // String getViewGroup(); // // void setViewGroup(String viewGroup); // // int getViewMode(); // // void setViewMode(int viewMode); // // void setMediaTagVersion(long mediaTagVersion); // // void setMediaTagVersion(int mediaTagVersion); // // String getTitle1(); // // void setTitle1(String title1); // // List<IVideo> getVideos(); // // void setVideos(List<IVideo> videos); // // String getParentPosterURL(); // // void setParentPosterURL(String parentPosterURL); // // List<ITrack> getTracks(); // // void setTracks(List<ITrack> tracks); // // String getParentIndex(); // // void setParentIndex(String parentIndex); // }
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.birbit.android.jobqueue.RetryConstraint; import javax.inject.Inject; import org.greenrobot.eventbus.EventBus; import us.nineworlds.serenity.common.android.injection.InjectingJob; import us.nineworlds.serenity.common.media.model.IMediaContainer; import us.nineworlds.serenity.common.rest.SerenityClient; import us.nineworlds.serenity.events.SubtitleEvent;
package us.nineworlds.serenity.jobs; public class SubtitleJob extends InjectingJob { EventBus eventBus = EventBus.getDefault(); @Inject SerenityClient client; String metaDataKey; public SubtitleJob(String metaDataKey) { this.metaDataKey = metaDataKey; } @Override public void onAdded() { } @Override public void onRun() throws Throwable {
// Path: serenity-common/src/main/java/us/nineworlds/serenity/common/media/model/IMediaContainer.java // public interface IMediaContainer { // String getTitle2(); // // void setTitle2(String title2); // // List<IDirectory> getDirectories(); // // void setDirectories(List<IDirectory> directory); // // int getSize(); // // void setSize(int size); // // int getAllowSync(); // // void setAllowSync(int allowSync); // // String getIdentifier(); // // void setIdentifier(String identifier); // // String getMediaTagPrefix(); // // void setMediaTagPrefix(String mediaTagPrefix); // // long getMediaTagVersion(); // // String getArt(); // // void setArt(String art); // // int getSortAsc(); // // void setSortAsc(int sortAsc); // // String getContent(); // // void setContent(String content); // // String getViewGroup(); // // void setViewGroup(String viewGroup); // // int getViewMode(); // // void setViewMode(int viewMode); // // void setMediaTagVersion(long mediaTagVersion); // // void setMediaTagVersion(int mediaTagVersion); // // String getTitle1(); // // void setTitle1(String title1); // // List<IVideo> getVideos(); // // void setVideos(List<IVideo> videos); // // String getParentPosterURL(); // // void setParentPosterURL(String parentPosterURL); // // List<ITrack> getTracks(); // // void setTracks(List<ITrack> tracks); // // String getParentIndex(); // // void setParentIndex(String parentIndex); // } // Path: serenity-app/src/main/java/us/nineworlds/serenity/jobs/SubtitleJob.java import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.birbit.android.jobqueue.RetryConstraint; import javax.inject.Inject; import org.greenrobot.eventbus.EventBus; import us.nineworlds.serenity.common.android.injection.InjectingJob; import us.nineworlds.serenity.common.media.model.IMediaContainer; import us.nineworlds.serenity.common.rest.SerenityClient; import us.nineworlds.serenity.events.SubtitleEvent; package us.nineworlds.serenity.jobs; public class SubtitleJob extends InjectingJob { EventBus eventBus = EventBus.getDefault(); @Inject SerenityClient client; String metaDataKey; public SubtitleJob(String metaDataKey) { this.metaDataKey = metaDataKey; } @Override public void onAdded() { } @Override public void onRun() throws Throwable {
IMediaContainer mediaContainer = client.retrieveMovieMetaData(metaDataKey);
NineWorlds/serenity-android
serenity-app/src/main/java/us/nineworlds/serenity/jobs/EpisodesRetrievalJob.java
// Path: serenity-common/src/main/java/us/nineworlds/serenity/common/media/model/IMediaContainer.java // public interface IMediaContainer { // String getTitle2(); // // void setTitle2(String title2); // // List<IDirectory> getDirectories(); // // void setDirectories(List<IDirectory> directory); // // int getSize(); // // void setSize(int size); // // int getAllowSync(); // // void setAllowSync(int allowSync); // // String getIdentifier(); // // void setIdentifier(String identifier); // // String getMediaTagPrefix(); // // void setMediaTagPrefix(String mediaTagPrefix); // // long getMediaTagVersion(); // // String getArt(); // // void setArt(String art); // // int getSortAsc(); // // void setSortAsc(int sortAsc); // // String getContent(); // // void setContent(String content); // // String getViewGroup(); // // void setViewGroup(String viewGroup); // // int getViewMode(); // // void setViewMode(int viewMode); // // void setMediaTagVersion(long mediaTagVersion); // // void setMediaTagVersion(int mediaTagVersion); // // String getTitle1(); // // void setTitle1(String title1); // // List<IVideo> getVideos(); // // void setVideos(List<IVideo> videos); // // String getParentPosterURL(); // // void setParentPosterURL(String parentPosterURL); // // List<ITrack> getTracks(); // // void setTracks(List<ITrack> tracks); // // String getParentIndex(); // // void setParentIndex(String parentIndex); // }
import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.birbit.android.jobqueue.RetryConstraint; import javax.inject.Inject; import org.greenrobot.eventbus.EventBus; import us.nineworlds.serenity.common.android.injection.InjectingJob; import us.nineworlds.serenity.common.media.model.IMediaContainer; import us.nineworlds.serenity.common.rest.SerenityClient; import us.nineworlds.serenity.core.logger.Logger; import us.nineworlds.serenity.events.EpisodesRetrievalEvent;
package us.nineworlds.serenity.jobs; public class EpisodesRetrievalJob extends InjectingJob { @Inject SerenityClient client; EventBus eventBus = EventBus.getDefault(); @Inject Logger logger; String key; public EpisodesRetrievalJob(@NonNull String key) { this.key = key; } @Override public void onAdded() { } @Override public void onRun() throws Throwable {
// Path: serenity-common/src/main/java/us/nineworlds/serenity/common/media/model/IMediaContainer.java // public interface IMediaContainer { // String getTitle2(); // // void setTitle2(String title2); // // List<IDirectory> getDirectories(); // // void setDirectories(List<IDirectory> directory); // // int getSize(); // // void setSize(int size); // // int getAllowSync(); // // void setAllowSync(int allowSync); // // String getIdentifier(); // // void setIdentifier(String identifier); // // String getMediaTagPrefix(); // // void setMediaTagPrefix(String mediaTagPrefix); // // long getMediaTagVersion(); // // String getArt(); // // void setArt(String art); // // int getSortAsc(); // // void setSortAsc(int sortAsc); // // String getContent(); // // void setContent(String content); // // String getViewGroup(); // // void setViewGroup(String viewGroup); // // int getViewMode(); // // void setViewMode(int viewMode); // // void setMediaTagVersion(long mediaTagVersion); // // void setMediaTagVersion(int mediaTagVersion); // // String getTitle1(); // // void setTitle1(String title1); // // List<IVideo> getVideos(); // // void setVideos(List<IVideo> videos); // // String getParentPosterURL(); // // void setParentPosterURL(String parentPosterURL); // // List<ITrack> getTracks(); // // void setTracks(List<ITrack> tracks); // // String getParentIndex(); // // void setParentIndex(String parentIndex); // } // Path: serenity-app/src/main/java/us/nineworlds/serenity/jobs/EpisodesRetrievalJob.java import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.birbit.android.jobqueue.RetryConstraint; import javax.inject.Inject; import org.greenrobot.eventbus.EventBus; import us.nineworlds.serenity.common.android.injection.InjectingJob; import us.nineworlds.serenity.common.media.model.IMediaContainer; import us.nineworlds.serenity.common.rest.SerenityClient; import us.nineworlds.serenity.core.logger.Logger; import us.nineworlds.serenity.events.EpisodesRetrievalEvent; package us.nineworlds.serenity.jobs; public class EpisodesRetrievalJob extends InjectingJob { @Inject SerenityClient client; EventBus eventBus = EventBus.getDefault(); @Inject Logger logger; String key; public EpisodesRetrievalJob(@NonNull String key) { this.key = key; } @Override public void onAdded() { } @Override public void onRun() throws Throwable {
IMediaContainer mediaContainer = client.retrieveEpisodes(key);
LklCBPay/javasdk
src/main/java/com/lakala/crossborder/client/util/webhook/recon/LklReconDownload.java
// Path: src/main/java/com/lakala/crossborder/client/entities/notify/ReconDownload.java // public class ReconDownload extends SuperWebHookRequest { // // private InputStream in; // // private String fileName; // // private String privData; // // public InputStream getIn() { // return in; // } // // public void setIn(InputStream in) { // this.in = in; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getPrivData() { // return privData; // } // // public void setPrivData(String privData) { // this.privData = privData; // } // } // // Path: src/main/java/com/lakala/crossborder/client/util/webhook/WebHookHandler.java // public interface WebHookHandler<T extends SuperWebHookRequest> { // // /** // * 处理拉卡拉通知 // * // * @param notifyMsg // * @return // * @throws LklCommonException // */ // void handle(T notifyMsg) throws LklCommonException; // }
import com.lakala.crossborder.client.entities.notify.ReconDownload; import com.lakala.crossborder.client.util.webhook.WebHookHandler; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder;
package com.lakala.crossborder.client.util.webhook.recon; /** * Created by jiang on 16/4/26. */ @Controller public class LklReconDownload { private static final Logger logger = LoggerFactory.getLogger(LklReconDownload.class); @Autowired(required = false) @Qualifier("lklreconFileHandle")
// Path: src/main/java/com/lakala/crossborder/client/entities/notify/ReconDownload.java // public class ReconDownload extends SuperWebHookRequest { // // private InputStream in; // // private String fileName; // // private String privData; // // public InputStream getIn() { // return in; // } // // public void setIn(InputStream in) { // this.in = in; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getPrivData() { // return privData; // } // // public void setPrivData(String privData) { // this.privData = privData; // } // } // // Path: src/main/java/com/lakala/crossborder/client/util/webhook/WebHookHandler.java // public interface WebHookHandler<T extends SuperWebHookRequest> { // // /** // * 处理拉卡拉通知 // * // * @param notifyMsg // * @return // * @throws LklCommonException // */ // void handle(T notifyMsg) throws LklCommonException; // } // Path: src/main/java/com/lakala/crossborder/client/util/webhook/recon/LklReconDownload.java import com.lakala.crossborder.client.entities.notify.ReconDownload; import com.lakala.crossborder.client.util.webhook.WebHookHandler; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; package com.lakala.crossborder.client.util.webhook.recon; /** * Created by jiang on 16/4/26. */ @Controller public class LklReconDownload { private static final Logger logger = LoggerFactory.getLogger(LklReconDownload.class); @Autowired(required = false) @Qualifier("lklreconFileHandle")
private WebHookHandler<ReconDownload> webHookIntf;
LklCBPay/javasdk
src/main/java/com/lakala/crossborder/client/util/webhook/recon/LklReconDownload.java
// Path: src/main/java/com/lakala/crossborder/client/entities/notify/ReconDownload.java // public class ReconDownload extends SuperWebHookRequest { // // private InputStream in; // // private String fileName; // // private String privData; // // public InputStream getIn() { // return in; // } // // public void setIn(InputStream in) { // this.in = in; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getPrivData() { // return privData; // } // // public void setPrivData(String privData) { // this.privData = privData; // } // } // // Path: src/main/java/com/lakala/crossborder/client/util/webhook/WebHookHandler.java // public interface WebHookHandler<T extends SuperWebHookRequest> { // // /** // * 处理拉卡拉通知 // * // * @param notifyMsg // * @return // * @throws LklCommonException // */ // void handle(T notifyMsg) throws LklCommonException; // }
import com.lakala.crossborder.client.entities.notify.ReconDownload; import com.lakala.crossborder.client.util.webhook.WebHookHandler; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder;
package com.lakala.crossborder.client.util.webhook.recon; /** * Created by jiang on 16/4/26. */ @Controller public class LklReconDownload { private static final Logger logger = LoggerFactory.getLogger(LklReconDownload.class); @Autowired(required = false) @Qualifier("lklreconFileHandle")
// Path: src/main/java/com/lakala/crossborder/client/entities/notify/ReconDownload.java // public class ReconDownload extends SuperWebHookRequest { // // private InputStream in; // // private String fileName; // // private String privData; // // public InputStream getIn() { // return in; // } // // public void setIn(InputStream in) { // this.in = in; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getPrivData() { // return privData; // } // // public void setPrivData(String privData) { // this.privData = privData; // } // } // // Path: src/main/java/com/lakala/crossborder/client/util/webhook/WebHookHandler.java // public interface WebHookHandler<T extends SuperWebHookRequest> { // // /** // * 处理拉卡拉通知 // * // * @param notifyMsg // * @return // * @throws LklCommonException // */ // void handle(T notifyMsg) throws LklCommonException; // } // Path: src/main/java/com/lakala/crossborder/client/util/webhook/recon/LklReconDownload.java import com.lakala.crossborder.client.entities.notify.ReconDownload; import com.lakala.crossborder.client.util.webhook.WebHookHandler; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; package com.lakala.crossborder.client.util.webhook.recon; /** * Created by jiang on 16/4/26. */ @Controller public class LklReconDownload { private static final Logger logger = LoggerFactory.getLogger(LklReconDownload.class); @Autowired(required = false) @Qualifier("lklreconFileHandle")
private WebHookHandler<ReconDownload> webHookIntf;
LklCBPay/javasdk
src/main/java/com/lakala/crossborder/client/entities/query/AgentPayAcctBalanceQueryReq.java
// Path: src/main/java/com/lakala/crossborder/client/enums/LklCurrency.java // public enum LklCurrency { // USD("USD", "美元"), // HKD("HKD", "港币"), // EUR("EUR", "欧元"), // JPY("JPY", "日元"), // GBP("GBP", "英镑"), // CHF("CHF", "瑞士法郎"), // SGD("SGD", "新加坡元"), // AUD("AUD", "澳元"), // CAD("CAD", "加元"), // KRW("KRW", "韩元"), // MYR("MYR", "马来西亚林吉特"), // NZD("NZD", "新西兰"), // RUB("RUB", "卢布"), // THB("THB", "泰铢"), // TWD("TWD", "新台币"), // CNY("CNY", "人民币"); // // LklCurrency(String code, String desc) { // this.code = code; // this.desc = desc; // } // // private String code; // // private String desc; // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // }
import com.lakala.crossborder.client.enums.LklCurrency; import java.io.Serializable;
package com.lakala.crossborder.client.entities.query; /** * <p> * 拉卡拉跨境支付-商户代付账户余额查询请求参数 * </p> * * @author jiangzhifei [email protected] */ public class AgentPayAcctBalanceQueryReq implements Serializable { private static final long serialVersionUID = -6981545435426441159L; /** * 币种,目前只支持人民币 {@link LklCurrency} */
// Path: src/main/java/com/lakala/crossborder/client/enums/LklCurrency.java // public enum LklCurrency { // USD("USD", "美元"), // HKD("HKD", "港币"), // EUR("EUR", "欧元"), // JPY("JPY", "日元"), // GBP("GBP", "英镑"), // CHF("CHF", "瑞士法郎"), // SGD("SGD", "新加坡元"), // AUD("AUD", "澳元"), // CAD("CAD", "加元"), // KRW("KRW", "韩元"), // MYR("MYR", "马来西亚林吉特"), // NZD("NZD", "新西兰"), // RUB("RUB", "卢布"), // THB("THB", "泰铢"), // TWD("TWD", "新台币"), // CNY("CNY", "人民币"); // // LklCurrency(String code, String desc) { // this.code = code; // this.desc = desc; // } // // private String code; // // private String desc; // // public String getCode() { // return code; // } // // public void setCode(String code) { // this.code = code; // } // // public String getDesc() { // return desc; // } // // public void setDesc(String desc) { // this.desc = desc; // } // } // Path: src/main/java/com/lakala/crossborder/client/entities/query/AgentPayAcctBalanceQueryReq.java import com.lakala.crossborder.client.enums.LklCurrency; import java.io.Serializable; package com.lakala.crossborder.client.entities.query; /** * <p> * 拉卡拉跨境支付-商户代付账户余额查询请求参数 * </p> * * @author jiangzhifei [email protected] */ public class AgentPayAcctBalanceQueryReq implements Serializable { private static final long serialVersionUID = -6981545435426441159L; /** * 币种,目前只支持人民币 {@link LklCurrency} */
private String currency = LklCurrency.CNY.getCode();
LklCBPay/javasdk
src/main/java/com/lakala/crossborder/client/util/LklCrossPayEnv.java
// Path: src/main/java/com/lakala/crossborder/client/enums/LklEnv.java // public enum LklEnv { // // SANDBOX("sandbox"), // LIVE("live"); // // LklEnv(String env) { // this.env = env; // } // // private String env; // // public String getEnv() { // return env; // } // // public void setEnv(String env) { // this.env = env; // } // }
import com.lakala.crossborder.client.enums.LklEnv; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
package com.lakala.crossborder.client.util; /** * <p> * 拉卡拉跨境支付环境信息 * </p> * * @author jiangzhifei [email protected] */ @Component public class LklCrossPayEnv { @Autowired @Qualifier("yamlMap") private Map<String, Object> yamlMap; private static Map<String, Object> YML_MAP;
// Path: src/main/java/com/lakala/crossborder/client/enums/LklEnv.java // public enum LklEnv { // // SANDBOX("sandbox"), // LIVE("live"); // // LklEnv(String env) { // this.env = env; // } // // private String env; // // public String getEnv() { // return env; // } // // public void setEnv(String env) { // this.env = env; // } // } // Path: src/main/java/com/lakala/crossborder/client/util/LklCrossPayEnv.java import com.lakala.crossborder.client.enums.LklEnv; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; package com.lakala.crossborder.client.util; /** * <p> * 拉卡拉跨境支付环境信息 * </p> * * @author jiangzhifei [email protected] */ @Component public class LklCrossPayEnv { @Autowired @Qualifier("yamlMap") private Map<String, Object> yamlMap; private static Map<String, Object> YML_MAP;
private static final Map<LklEnv, LklCrossPayClientConfig> ENV_CONFIG = new ConcurrentHashMap<LklEnv, LklCrossPayClientConfig>();
destin/SO-answers
SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/client/Main.java
// Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebService.java // @WebService(name = "MyWebService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/") // @XmlSeeAlso({ // ObjectFactory.class // }) // public interface MyWebService { // // // /** // * // * @param name // * @return // * returns java.lang.String // */ // @WebMethod // @WebResult(targetNamespace = "") // @RequestWrapper(localName = "hello", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.Hello") // @ResponseWrapper(localName = "helloResponse", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.HelloResponse") // public String hello( // @WebParam(name = "name", targetNamespace = "") // String name); // // } // // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebServiceImplService.java // @WebServiceClient(name = "MyWebServiceImplService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", wsdlLocation = "http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl") // @HandlerChain(file = "handlers.xml") // public class MyWebServiceImplService // extends Service // { // // private final static URL MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // private final static WebServiceException MYWEBSERVICEIMPLSERVICE_EXCEPTION; // private final static QName MYWEBSERVICEIMPLSERVICE_QNAME = new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplService"); // // static { // URL url = null; // WebServiceException e = null; // try { // url = new URL("http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl"); // } catch (MalformedURLException ex) { // e = new WebServiceException(ex); // } // MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url; // MYWEBSERVICEIMPLSERVICE_EXCEPTION = e; // } // // public MyWebServiceImplService() { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(WebServiceFeature... features) { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName) { // super(wsdlLocation, serviceName); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { // super(wsdlLocation, serviceName, features); // } // // /** // * // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort() { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class); // } // // /** // * // * @param features // * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort(WebServiceFeature... features) { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class, features); // } // // private static URL __getWsdlLocation() { // if (MYWEBSERVICEIMPLSERVICE_EXCEPTION!= null) { // throw MYWEBSERVICEIMPLSERVICE_EXCEPTION; // } // return MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // } // // }
import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebService; import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebServiceImplService;
package org.dpytel.jaxws.jaxws_java_first_jboss.client; public class Main { public static void main(String[] args) {
// Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebService.java // @WebService(name = "MyWebService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/") // @XmlSeeAlso({ // ObjectFactory.class // }) // public interface MyWebService { // // // /** // * // * @param name // * @return // * returns java.lang.String // */ // @WebMethod // @WebResult(targetNamespace = "") // @RequestWrapper(localName = "hello", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.Hello") // @ResponseWrapper(localName = "helloResponse", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.HelloResponse") // public String hello( // @WebParam(name = "name", targetNamespace = "") // String name); // // } // // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebServiceImplService.java // @WebServiceClient(name = "MyWebServiceImplService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", wsdlLocation = "http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl") // @HandlerChain(file = "handlers.xml") // public class MyWebServiceImplService // extends Service // { // // private final static URL MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // private final static WebServiceException MYWEBSERVICEIMPLSERVICE_EXCEPTION; // private final static QName MYWEBSERVICEIMPLSERVICE_QNAME = new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplService"); // // static { // URL url = null; // WebServiceException e = null; // try { // url = new URL("http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl"); // } catch (MalformedURLException ex) { // e = new WebServiceException(ex); // } // MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url; // MYWEBSERVICEIMPLSERVICE_EXCEPTION = e; // } // // public MyWebServiceImplService() { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(WebServiceFeature... features) { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName) { // super(wsdlLocation, serviceName); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { // super(wsdlLocation, serviceName, features); // } // // /** // * // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort() { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class); // } // // /** // * // * @param features // * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort(WebServiceFeature... features) { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class, features); // } // // private static URL __getWsdlLocation() { // if (MYWEBSERVICEIMPLSERVICE_EXCEPTION!= null) { // throw MYWEBSERVICEIMPLSERVICE_EXCEPTION; // } // return MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // } // // } // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/client/Main.java import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebService; import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebServiceImplService; package org.dpytel.jaxws.jaxws_java_first_jboss.client; public class Main { public static void main(String[] args) {
MyWebServiceImplService service = new MyWebServiceImplService();
destin/SO-answers
SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/client/Main.java
// Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebService.java // @WebService(name = "MyWebService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/") // @XmlSeeAlso({ // ObjectFactory.class // }) // public interface MyWebService { // // // /** // * // * @param name // * @return // * returns java.lang.String // */ // @WebMethod // @WebResult(targetNamespace = "") // @RequestWrapper(localName = "hello", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.Hello") // @ResponseWrapper(localName = "helloResponse", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.HelloResponse") // public String hello( // @WebParam(name = "name", targetNamespace = "") // String name); // // } // // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebServiceImplService.java // @WebServiceClient(name = "MyWebServiceImplService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", wsdlLocation = "http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl") // @HandlerChain(file = "handlers.xml") // public class MyWebServiceImplService // extends Service // { // // private final static URL MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // private final static WebServiceException MYWEBSERVICEIMPLSERVICE_EXCEPTION; // private final static QName MYWEBSERVICEIMPLSERVICE_QNAME = new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplService"); // // static { // URL url = null; // WebServiceException e = null; // try { // url = new URL("http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl"); // } catch (MalformedURLException ex) { // e = new WebServiceException(ex); // } // MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url; // MYWEBSERVICEIMPLSERVICE_EXCEPTION = e; // } // // public MyWebServiceImplService() { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(WebServiceFeature... features) { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName) { // super(wsdlLocation, serviceName); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { // super(wsdlLocation, serviceName, features); // } // // /** // * // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort() { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class); // } // // /** // * // * @param features // * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort(WebServiceFeature... features) { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class, features); // } // // private static URL __getWsdlLocation() { // if (MYWEBSERVICEIMPLSERVICE_EXCEPTION!= null) { // throw MYWEBSERVICEIMPLSERVICE_EXCEPTION; // } // return MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // } // // }
import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebService; import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebServiceImplService;
package org.dpytel.jaxws.jaxws_java_first_jboss.client; public class Main { public static void main(String[] args) { MyWebServiceImplService service = new MyWebServiceImplService();
// Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebService.java // @WebService(name = "MyWebService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/") // @XmlSeeAlso({ // ObjectFactory.class // }) // public interface MyWebService { // // // /** // * // * @param name // * @return // * returns java.lang.String // */ // @WebMethod // @WebResult(targetNamespace = "") // @RequestWrapper(localName = "hello", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.Hello") // @ResponseWrapper(localName = "helloResponse", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", className = "org.dpytel.jaxws.jaxws_java_first_jboss.HelloResponse") // public String hello( // @WebParam(name = "name", targetNamespace = "") // String name); // // } // // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/MyWebServiceImplService.java // @WebServiceClient(name = "MyWebServiceImplService", targetNamespace = "http://jaxws_java_first_jboss.jaxws.dpytel.org/", wsdlLocation = "http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl") // @HandlerChain(file = "handlers.xml") // public class MyWebServiceImplService // extends Service // { // // private final static URL MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // private final static WebServiceException MYWEBSERVICEIMPLSERVICE_EXCEPTION; // private final static QName MYWEBSERVICEIMPLSERVICE_QNAME = new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplService"); // // static { // URL url = null; // WebServiceException e = null; // try { // url = new URL("http://localhost:8080/jaxws-java-first-jboss/MyWebService?wsdl"); // } catch (MalformedURLException ex) { // e = new WebServiceException(ex); // } // MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION = url; // MYWEBSERVICEIMPLSERVICE_EXCEPTION = e; // } // // public MyWebServiceImplService() { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(WebServiceFeature... features) { // super(__getWsdlLocation(), MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME); // } // // public MyWebServiceImplService(URL wsdlLocation, WebServiceFeature... features) { // super(wsdlLocation, MYWEBSERVICEIMPLSERVICE_QNAME, features); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName) { // super(wsdlLocation, serviceName); // } // // public MyWebServiceImplService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { // super(wsdlLocation, serviceName, features); // } // // /** // * // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort() { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class); // } // // /** // * // * @param features // * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. // * @return // * returns MyWebService // */ // @WebEndpoint(name = "MyWebServiceImplPort") // public MyWebService getMyWebServiceImplPort(WebServiceFeature... features) { // return super.getPort(new QName("http://jaxws_java_first_jboss.jaxws.dpytel.org/", "MyWebServiceImplPort"), MyWebService.class, features); // } // // private static URL __getWsdlLocation() { // if (MYWEBSERVICEIMPLSERVICE_EXCEPTION!= null) { // throw MYWEBSERVICEIMPLSERVICE_EXCEPTION; // } // return MYWEBSERVICEIMPLSERVICE_WSDL_LOCATION; // } // // } // Path: SO-how-get-xml-responce-using-jax-ws-soap-handler/src/main/java/org/dpytel/jaxws/jaxws_java_first_jboss/client/Main.java import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebService; import org.dpytel.jaxws.jaxws_java_first_jboss.MyWebServiceImplService; package org.dpytel.jaxws.jaxws_java_first_jboss.client; public class Main { public static void main(String[] args) { MyWebServiceImplService service = new MyWebServiceImplService();
MyWebService myWebService = service.getMyWebServiceImplPort();
destin/SO-answers
SO-how-to-add-soap-security-header-usernametoken-information-to-code-first-webser/src/main/java/demo/wssec/server/GreeterImpl.java
// Path: SO-how-to-add-soap-security-header-usernametoken-information-to-code-first-webser/src/main/java/org/apache/cxf/hello_world_soap_http/Greeter.java // @WebService(targetNamespace = "http://cxf.apache.org/hello_world_soap_http", name = "Greeter") // @XmlSeeAlso({org.apache.cxf.hello_world_soap_http.types.ObjectFactory.class}) // @Policies({ @Policy(uri = "ut.policy") }) // public interface Greeter { // // @WebResult(name = "responseType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // @RequestWrapper(localName = "sayHi", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.SayHi") // @WebMethod // @ResponseWrapper(localName = "sayHiResponse", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.SayHiResponse") // public java.lang.String sayHi(); // // @WebResult(name = "responseType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // @RequestWrapper(localName = "greetMe", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMe") // @WebMethod // @ResponseWrapper(localName = "greetMeResponse", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMeResponse") // public java.lang.String greetMe( // @WebParam(name = "requestType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // java.lang.String requestType // ); // // @Oneway // @RequestWrapper(localName = "greetMeOneWay", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMeOneWay") // @WebMethod // public void greetMeOneWay( // @WebParam(name = "requestType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // java.lang.String requestType // ); // }
import org.apache.cxf.annotations.Policy; import org.apache.cxf.hello_world_soap_http.Greeter; import java.util.logging.Logger; import org.apache.cxf.annotations.Policies;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package demo.wssec.server; @javax.jws.WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.hello_world_soap_http.Greeter", targetNamespace = "http://cxf.apache.org/hello_world_soap_http") @Policies({ @Policy(uri = "ut.policy.xml") })
// Path: SO-how-to-add-soap-security-header-usernametoken-information-to-code-first-webser/src/main/java/org/apache/cxf/hello_world_soap_http/Greeter.java // @WebService(targetNamespace = "http://cxf.apache.org/hello_world_soap_http", name = "Greeter") // @XmlSeeAlso({org.apache.cxf.hello_world_soap_http.types.ObjectFactory.class}) // @Policies({ @Policy(uri = "ut.policy") }) // public interface Greeter { // // @WebResult(name = "responseType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // @RequestWrapper(localName = "sayHi", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.SayHi") // @WebMethod // @ResponseWrapper(localName = "sayHiResponse", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.SayHiResponse") // public java.lang.String sayHi(); // // @WebResult(name = "responseType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // @RequestWrapper(localName = "greetMe", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMe") // @WebMethod // @ResponseWrapper(localName = "greetMeResponse", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMeResponse") // public java.lang.String greetMe( // @WebParam(name = "requestType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // java.lang.String requestType // ); // // @Oneway // @RequestWrapper(localName = "greetMeOneWay", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types", className = "org.apache.cxf.hello_world_soap_http.types.GreetMeOneWay") // @WebMethod // public void greetMeOneWay( // @WebParam(name = "requestType", targetNamespace = "http://cxf.apache.org/hello_world_soap_http/types") // java.lang.String requestType // ); // } // Path: SO-how-to-add-soap-security-header-usernametoken-information-to-code-first-webser/src/main/java/demo/wssec/server/GreeterImpl.java import org.apache.cxf.annotations.Policy; import org.apache.cxf.hello_world_soap_http.Greeter; import java.util.logging.Logger; import org.apache.cxf.annotations.Policies; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package demo.wssec.server; @javax.jws.WebService(serviceName = "GreeterService", portName = "GreeterPort", endpointInterface = "org.apache.cxf.hello_world_soap_http.Greeter", targetNamespace = "http://cxf.apache.org/hello_world_soap_http") @Policies({ @Policy(uri = "ut.policy.xml") })
public class GreeterImpl implements Greeter {
basepom/duplicate-finder-maven-plugin
src/test/java/org/basepom/mojo/duplicatefinder/classpath/TestPackageNameHolder.java
// Path: src/main/java/org/basepom/mojo/duplicatefinder/classpath/PackageNameHolder.java // class PackageNameHolder // { // private final ImmutableList<String> packages; // private final String packageName; // private final String path; // // PackageNameHolder(final List<String> packages) // { // this.packages = ImmutableList.copyOf(checkNotNull(packages, "packages is null")); // this.packageName = Joiner.on('.').join(packages); // this.path = Joiner.on('/').join(packages); // } // // PackageNameHolder() // { // this.packages = ImmutableList.of(); // this.packageName = ""; // this.path = ""; // } // // PackageNameHolder getChildPackage(final String packageName) // { // checkNotNull(packageName, "packageName is null"); // checkArgument(packageName.length() > 0, "package name must have at least one character"); // // return new PackageNameHolder(ImmutableList.<String>builder().addAll(packages).add(packageName).build()); // } // // String getQualifiedName(final String className) // { // checkNotNull(className, "className is null"); // return packages.isEmpty() ? className : packageName + "." + className; // } // // String getQualifiedPath(final String className) // { // checkNotNull(className, "className is null"); // return packages.isEmpty() ? className : path + "/" + className; // } // // @Override // public String toString() // { // return getClass().getSimpleName() + "(" + packageName + ")"; // } // }
import com.google.common.collect.ImmutableList; import org.basepom.mojo.duplicatefinder.classpath.PackageNameHolder; import org.junit.Test; import static org.junit.Assert.assertEquals;
/* * 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.basepom.mojo.duplicatefinder.classpath; public class TestPackageNameHolder { @Test public void testEmpty() {
// Path: src/main/java/org/basepom/mojo/duplicatefinder/classpath/PackageNameHolder.java // class PackageNameHolder // { // private final ImmutableList<String> packages; // private final String packageName; // private final String path; // // PackageNameHolder(final List<String> packages) // { // this.packages = ImmutableList.copyOf(checkNotNull(packages, "packages is null")); // this.packageName = Joiner.on('.').join(packages); // this.path = Joiner.on('/').join(packages); // } // // PackageNameHolder() // { // this.packages = ImmutableList.of(); // this.packageName = ""; // this.path = ""; // } // // PackageNameHolder getChildPackage(final String packageName) // { // checkNotNull(packageName, "packageName is null"); // checkArgument(packageName.length() > 0, "package name must have at least one character"); // // return new PackageNameHolder(ImmutableList.<String>builder().addAll(packages).add(packageName).build()); // } // // String getQualifiedName(final String className) // { // checkNotNull(className, "className is null"); // return packages.isEmpty() ? className : packageName + "." + className; // } // // String getQualifiedPath(final String className) // { // checkNotNull(className, "className is null"); // return packages.isEmpty() ? className : path + "/" + className; // } // // @Override // public String toString() // { // return getClass().getSimpleName() + "(" + packageName + ")"; // } // } // Path: src/test/java/org/basepom/mojo/duplicatefinder/classpath/TestPackageNameHolder.java import com.google.common.collect.ImmutableList; import org.basepom.mojo.duplicatefinder.classpath.PackageNameHolder; import org.junit.Test; import static org.junit.Assert.assertEquals; /* * 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.basepom.mojo.duplicatefinder.classpath; public class TestPackageNameHolder { @Test public void testEmpty() {
final PackageNameHolder p1 = new PackageNameHolder();
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RequiredRxFieldsValidationRule.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // }
import org.apache.commons.lang3.StringUtils; import rxdemo.prescription.Prescription; import java.util.List;
package rxdemo.prescription.validation; public class RequiredRxFieldsValidationRule implements IRxValidationRule { @Override
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RequiredRxFieldsValidationRule.java import org.apache.commons.lang3.StringUtils; import rxdemo.prescription.Prescription; import java.util.List; package rxdemo.prescription.validation; public class RequiredRxFieldsValidationRule implements IRxValidationRule { @Override
public RxValidationResult validateAgainstRule(Prescription rx) {
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/prescription/validation/OpiateDurationValidationRuleShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/DrugDatabase.java // public class DrugDatabase { // private static List<DispensableDrug> drugsInDatabase; // // static { // drugsInDatabase = new ArrayList<>(); // loadDrugData(); // } // // public static List<DispensableDrug> getDrugsAvailableForPrescribing() { // return drugsInDatabase; // } // // public static List<DispensableDrug> getDrugsInClassification(int classCode) { // ArrayList<DispensableDrug> matchingDrugs = new ArrayList<>(); // for (DispensableDrug drug : drugsInDatabase) { // for (EDrugClassification classification : drug.getClassifications()) { // if (classCode == classification.getEtcClassificationCode()) { // matchingDrugs.add(drug); // break; // } // } // } // return matchingDrugs; // } // // public static DispensableDrug getDrugByName(String name) { // for (DispensableDrug dispensableDrug : drugsInDatabase) { // if (name.equals(dispensableDrug.getName())) { // return dispensableDrug; // } // } // return null; // } // // private static void loadDrugData() { // drugsInDatabase = new ArrayList<>(); // drugsInDatabase.add(new DispensableDrug(100, "aspirin", // new EDrugClassification[]{EDrugClassification.ANALGESIC, EDrugClassification.PLATELET_AGGREGATION_INHIBITORS})); // drugsInDatabase.add(new DispensableDrug(150, "acetaminophen", // new EDrugClassification[]{EDrugClassification.ANALGESIC})); // drugsInDatabase.add(new DispensableDrug(200, "bactrim", // new EDrugClassification[]{EDrugClassification.ANTIBACTERIAL})); // drugsInDatabase.add(new DispensableDrug(300, "diazepam", // new EDrugClassification[]{EDrugClassification.ANTIANXIETY})); // drugsInDatabase.add(new DispensableDrug(400, "fluticasone", // new EDrugClassification[]{EDrugClassification.NASAL_CORTICOSTEROIDS})); // drugsInDatabase.add(new DispensableDrug(500, "folic acid", // new EDrugClassification[]{EDrugClassification.VITAMINS_WATER_SOLUBLE})); // drugsInDatabase.add(new DispensableDrug(600, "hydrocodone-chlorpheniramine", // new EDrugClassification[]{EDrugClassification.NARCOTIC_ANTHISTAMINE})); // drugsInDatabase.add(new DispensableDrug(700, "lisinopril", // new EDrugClassification[]{EDrugClassification.ACE_INHIBITORS})); // drugsInDatabase.add(new DispensableDrug(750, "lorazepam", // new EDrugClassification[]{EDrugClassification.ANTIANXIETY})); // drugsInDatabase.add(new DispensableDrug(800, "methadone", // new EDrugClassification[]{EDrugClassification.ANALGESICS_NARCOTIC})); // drugsInDatabase.add(new DispensableDrug(900, "oxycodone", // new EDrugClassification[]{EDrugClassification.ANALGESICS_NARCOTIC})); // drugsInDatabase.add(new DispensableDrug(1000, "simvastatin", // new EDrugClassification[]{EDrugClassification.ANTIHYPERLIPIDEMICS})); // // drugsInDatabase.add(new DispensableDrug(1100, "cowbell", new EDrugClassification[] {EDrugClassification.ANALGESIC})); // drugsInDatabase.add(new DispensableDrug(1200, "more cowbell", new EDrugClassification[] {EDrugClassification.ANALGESIC})); // } // // // }
import org.junit.Before; import org.junit.Test; import rxdemo.prescription.Prescription; import rxdemo.vendordata.DrugDatabase; import static org.junit.Assert.*;
package rxdemo.prescription.validation; public class OpiateDurationValidationRuleShould { private Prescription rx; private OpiateDurationValidationRule rule; @Before public void setUp() { rx = new Prescription(); rule = new OpiateDurationValidationRule(); } @Test public void returnInvalidResultForOpioidOverDurationLimit() { rx.setDuration("31 days");
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/DrugDatabase.java // public class DrugDatabase { // private static List<DispensableDrug> drugsInDatabase; // // static { // drugsInDatabase = new ArrayList<>(); // loadDrugData(); // } // // public static List<DispensableDrug> getDrugsAvailableForPrescribing() { // return drugsInDatabase; // } // // public static List<DispensableDrug> getDrugsInClassification(int classCode) { // ArrayList<DispensableDrug> matchingDrugs = new ArrayList<>(); // for (DispensableDrug drug : drugsInDatabase) { // for (EDrugClassification classification : drug.getClassifications()) { // if (classCode == classification.getEtcClassificationCode()) { // matchingDrugs.add(drug); // break; // } // } // } // return matchingDrugs; // } // // public static DispensableDrug getDrugByName(String name) { // for (DispensableDrug dispensableDrug : drugsInDatabase) { // if (name.equals(dispensableDrug.getName())) { // return dispensableDrug; // } // } // return null; // } // // private static void loadDrugData() { // drugsInDatabase = new ArrayList<>(); // drugsInDatabase.add(new DispensableDrug(100, "aspirin", // new EDrugClassification[]{EDrugClassification.ANALGESIC, EDrugClassification.PLATELET_AGGREGATION_INHIBITORS})); // drugsInDatabase.add(new DispensableDrug(150, "acetaminophen", // new EDrugClassification[]{EDrugClassification.ANALGESIC})); // drugsInDatabase.add(new DispensableDrug(200, "bactrim", // new EDrugClassification[]{EDrugClassification.ANTIBACTERIAL})); // drugsInDatabase.add(new DispensableDrug(300, "diazepam", // new EDrugClassification[]{EDrugClassification.ANTIANXIETY})); // drugsInDatabase.add(new DispensableDrug(400, "fluticasone", // new EDrugClassification[]{EDrugClassification.NASAL_CORTICOSTEROIDS})); // drugsInDatabase.add(new DispensableDrug(500, "folic acid", // new EDrugClassification[]{EDrugClassification.VITAMINS_WATER_SOLUBLE})); // drugsInDatabase.add(new DispensableDrug(600, "hydrocodone-chlorpheniramine", // new EDrugClassification[]{EDrugClassification.NARCOTIC_ANTHISTAMINE})); // drugsInDatabase.add(new DispensableDrug(700, "lisinopril", // new EDrugClassification[]{EDrugClassification.ACE_INHIBITORS})); // drugsInDatabase.add(new DispensableDrug(750, "lorazepam", // new EDrugClassification[]{EDrugClassification.ANTIANXIETY})); // drugsInDatabase.add(new DispensableDrug(800, "methadone", // new EDrugClassification[]{EDrugClassification.ANALGESICS_NARCOTIC})); // drugsInDatabase.add(new DispensableDrug(900, "oxycodone", // new EDrugClassification[]{EDrugClassification.ANALGESICS_NARCOTIC})); // drugsInDatabase.add(new DispensableDrug(1000, "simvastatin", // new EDrugClassification[]{EDrugClassification.ANTIHYPERLIPIDEMICS})); // // drugsInDatabase.add(new DispensableDrug(1100, "cowbell", new EDrugClassification[] {EDrugClassification.ANALGESIC})); // drugsInDatabase.add(new DispensableDrug(1200, "more cowbell", new EDrugClassification[] {EDrugClassification.ANALGESIC})); // } // // // } // Path: rxdemo-server/core/src/test/java/rxdemo/prescription/validation/OpiateDurationValidationRuleShould.java import org.junit.Before; import org.junit.Test; import rxdemo.prescription.Prescription; import rxdemo.vendordata.DrugDatabase; import static org.junit.Assert.*; package rxdemo.prescription.validation; public class OpiateDurationValidationRuleShould { private Prescription rx; private OpiateDurationValidationRule rule; @Before public void setUp() { rx = new Prescription(); rule = new OpiateDurationValidationRule(); } @Test public void returnInvalidResultForOpioidOverDurationLimit() { rx.setDuration("31 days");
rx.setDrug(DrugDatabase.getDrugByName("oxycodone"));
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/prescription/validation/OpiateDurationValidationRule.java
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/OpiatesDrugConcept.java // public class OpiatesDrugConcept { // // private static EDrugClassification[] opiateClasses = new EDrugClassification[]{ // EDrugClassification.ANTIANXIETY, // EDrugClassification.ANALGESICS_NARCOTIC, // EDrugClassification.NARCOTIC_ANTHISTAMINE}; // // public static List<EDrugClassification> getClassificationsInConcept() { // return Arrays.asList(opiateClasses); // } // // public static boolean isDrugInConcept(DispensableDrug drug) { // if (drug == null) { // return false; // } // HashSet<EDrugClassification> opiateClassesForThisDrug = new HashSet<>( // drug.getClassifications()); // opiateClassesForThisDrug.retainAll(Arrays.asList(opiateClasses)); // return !opiateClassesForThisDrug.isEmpty(); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // }
import rxdemo.drug.OpiatesDrugConcept; import rxdemo.prescription.Prescription;
package rxdemo.prescription.validation; public class OpiateDurationValidationRule implements IRxValidationRule { public static final String MESSAGE = "Prescribing opioids and benzodiazepines " + "in quantities greater than a 30-day" + " supply is prohibited. Refills may be used to extend the intended " + "duration of treatment."; @Override
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/OpiatesDrugConcept.java // public class OpiatesDrugConcept { // // private static EDrugClassification[] opiateClasses = new EDrugClassification[]{ // EDrugClassification.ANTIANXIETY, // EDrugClassification.ANALGESICS_NARCOTIC, // EDrugClassification.NARCOTIC_ANTHISTAMINE}; // // public static List<EDrugClassification> getClassificationsInConcept() { // return Arrays.asList(opiateClasses); // } // // public static boolean isDrugInConcept(DispensableDrug drug) { // if (drug == null) { // return false; // } // HashSet<EDrugClassification> opiateClassesForThisDrug = new HashSet<>( // drug.getClassifications()); // opiateClassesForThisDrug.retainAll(Arrays.asList(opiateClasses)); // return !opiateClassesForThisDrug.isEmpty(); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/OpiateDurationValidationRule.java import rxdemo.drug.OpiatesDrugConcept; import rxdemo.prescription.Prescription; package rxdemo.prescription.validation; public class OpiateDurationValidationRule implements IRxValidationRule { public static final String MESSAGE = "Prescribing opioids and benzodiazepines " + "in quantities greater than a 30-day" + " supply is prohibited. Refills may be used to extend the intended " + "duration of treatment."; @Override
public RxValidationResult validateAgainstRule(Prescription rx) {
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/prescription/validation/OpiateDurationValidationRule.java
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/OpiatesDrugConcept.java // public class OpiatesDrugConcept { // // private static EDrugClassification[] opiateClasses = new EDrugClassification[]{ // EDrugClassification.ANTIANXIETY, // EDrugClassification.ANALGESICS_NARCOTIC, // EDrugClassification.NARCOTIC_ANTHISTAMINE}; // // public static List<EDrugClassification> getClassificationsInConcept() { // return Arrays.asList(opiateClasses); // } // // public static boolean isDrugInConcept(DispensableDrug drug) { // if (drug == null) { // return false; // } // HashSet<EDrugClassification> opiateClassesForThisDrug = new HashSet<>( // drug.getClassifications()); // opiateClassesForThisDrug.retainAll(Arrays.asList(opiateClasses)); // return !opiateClassesForThisDrug.isEmpty(); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // }
import rxdemo.drug.OpiatesDrugConcept; import rxdemo.prescription.Prescription;
package rxdemo.prescription.validation; public class OpiateDurationValidationRule implements IRxValidationRule { public static final String MESSAGE = "Prescribing opioids and benzodiazepines " + "in quantities greater than a 30-day" + " supply is prohibited. Refills may be used to extend the intended " + "duration of treatment."; @Override public RxValidationResult validateAgainstRule(Prescription rx) { RxValidationResult result = new RxValidationResult(); if (rx.getDrug() != null && isForOpioid(rx) && durationInvalidForOpioid(rx)) { result.addInvalidComponent(ERxComponent.DURATION); result.setMessage(MESSAGE); } return result; } private boolean durationInvalidForOpioid(Prescription rx) { return rx.getDurationAsDays() > 30 || rx.getDurationAsDays() == 0; } private boolean isForOpioid(Prescription rx) {
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/OpiatesDrugConcept.java // public class OpiatesDrugConcept { // // private static EDrugClassification[] opiateClasses = new EDrugClassification[]{ // EDrugClassification.ANTIANXIETY, // EDrugClassification.ANALGESICS_NARCOTIC, // EDrugClassification.NARCOTIC_ANTHISTAMINE}; // // public static List<EDrugClassification> getClassificationsInConcept() { // return Arrays.asList(opiateClasses); // } // // public static boolean isDrugInConcept(DispensableDrug drug) { // if (drug == null) { // return false; // } // HashSet<EDrugClassification> opiateClassesForThisDrug = new HashSet<>( // drug.getClassifications()); // opiateClassesForThisDrug.retainAll(Arrays.asList(opiateClasses)); // return !opiateClassesForThisDrug.isEmpty(); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/OpiateDurationValidationRule.java import rxdemo.drug.OpiatesDrugConcept; import rxdemo.prescription.Prescription; package rxdemo.prescription.validation; public class OpiateDurationValidationRule implements IRxValidationRule { public static final String MESSAGE = "Prescribing opioids and benzodiazepines " + "in quantities greater than a 30-day" + " supply is prohibited. Refills may be used to extend the intended " + "duration of treatment."; @Override public RxValidationResult validateAgainstRule(Prescription rx) { RxValidationResult result = new RxValidationResult(); if (rx.getDrug() != null && isForOpioid(rx) && durationInvalidForOpioid(rx)) { result.addInvalidComponent(ERxComponent.DURATION); result.setMessage(MESSAGE); } return result; } private boolean durationInvalidForOpioid(Prescription rx) { return rx.getDurationAsDays() > 30 || rx.getDurationAsDays() == 0; } private boolean isForOpioid(Prescription rx) {
return OpiatesDrugConcept.isDrugInConcept(rx.getDrug());
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/RxMedicationPage.java
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/VerifyButton.java // public class VerifyButton { // public static void verifyButtonTextEnabledDisplayedByXpath(WebDriver inDriver, String inButtonID, // String inButtonValue, Boolean inEnabled, Boolean inDisplayed) // { // // WebElement searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsText = searchElement.getText().replace(" ", " "); // Boolean bEnabled = searchElement.isEnabled(); // Boolean bDisplayed = searchElement.isDisplayed(); // assertEquals(inButtonValue, jsText); // assertEquals(inEnabled, bEnabled); // assertEquals(inDisplayed, bDisplayed); // System.out.println(jsTag + " '" + jsText + "' Enabled - '" + bEnabled + "'; Displayed - '" // + bDisplayed + "'; were Verified!"); // } // }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import util.ButtonClick; import util.RxConstants; import util.VerifyButton; import java.util.List; import static org.openqa.selenium.By.xpath;
package page; public class RxMedicationPage { public static boolean isButtonEnabled(WebDriver mDriver) {
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/VerifyButton.java // public class VerifyButton { // public static void verifyButtonTextEnabledDisplayedByXpath(WebDriver inDriver, String inButtonID, // String inButtonValue, Boolean inEnabled, Boolean inDisplayed) // { // // WebElement searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsText = searchElement.getText().replace(" ", " "); // Boolean bEnabled = searchElement.isEnabled(); // Boolean bDisplayed = searchElement.isDisplayed(); // assertEquals(inButtonValue, jsText); // assertEquals(inEnabled, bEnabled); // assertEquals(inDisplayed, bDisplayed); // System.out.println(jsTag + " '" + jsText + "' Enabled - '" + bEnabled + "'; Displayed - '" // + bDisplayed + "'; were Verified!"); // } // } // Path: rxdemo-selenium/src/test/java/page/RxMedicationPage.java import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import util.ButtonClick; import util.RxConstants; import util.VerifyButton; import java.util.List; import static org.openqa.selenium.By.xpath; package page; public class RxMedicationPage { public static boolean isButtonEnabled(WebDriver mDriver) {
return mDriver.findElement(xpath(RxConstants.BTN_RX_ADD_RX_TO_CART)).isEnabled();
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/prescription/validation/RxValidatorShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // }
import org.junit.Test; import rxdemo.prescription.Prescription; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package rxdemo.prescription.validation; public class RxValidatorShould { @Test public void returnNoResultsIfRulesProvidedIsNull() { RxValidator validator = new RxValidator(null); List<RxValidationResult> results = validator.validatePrescription(
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // Path: rxdemo-server/core/src/test/java/rxdemo/prescription/validation/RxValidatorShould.java import org.junit.Test; import rxdemo.prescription.Prescription; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package rxdemo.prescription.validation; public class RxValidatorShould { @Test public void returnNoResultsIfRulesProvidedIsNull() { RxValidator validator = new RxValidator(null); List<RxValidationResult> results = validator.validatePrescription(
new Prescription());
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // }
import rxdemo.prescription.Prescription; import java.util.ArrayList; import java.util.List;
package rxdemo.prescription.validation; public class RxValidator { private static RxValidator defaultValidator; private List<IRxValidationRule> rules; static { ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); defaultRules.add(new RequiredRxFieldsValidationRule()); defaultRules.add(new OpiateDurationValidationRule()); defaultValidator = new RxValidator(defaultRules); } public static RxValidator getDefaultValidator() { return defaultValidator; } public RxValidator(List<IRxValidationRule> rules) { this.rules = (rules != null)? rules : new ArrayList<>(); }
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java import rxdemo.prescription.Prescription; import java.util.ArrayList; import java.util.List; package rxdemo.prescription.validation; public class RxValidator { private static RxValidator defaultValidator; private List<IRxValidationRule> rules; static { ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); defaultRules.add(new RequiredRxFieldsValidationRule()); defaultRules.add(new OpiateDurationValidationRule()); defaultValidator = new RxValidator(defaultRules); } public static RxValidator getDefaultValidator() { return defaultValidator; } public RxValidator(List<IRxValidationRule> rules) { this.rules = (rules != null)? rules : new ArrayList<>(); }
public List<RxValidationResult> validatePrescription(Prescription rx) {
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionResponse.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // }
import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.RxValidationResult; import java.util.ArrayList; import java.util.HashSet;
package rxdemo.commands; public class ValidatePrescriptionResponse { private boolean valid; private ArrayList<String> messages;
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionResponse.java import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.RxValidationResult; import java.util.ArrayList; import java.util.HashSet; package rxdemo.commands; public class ValidatePrescriptionResponse { private boolean valid; private ArrayList<String> messages;
private HashSet<ERxComponent> componentsInError;
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionResponse.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // }
import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.RxValidationResult; import java.util.ArrayList; import java.util.HashSet;
package rxdemo.commands; public class ValidatePrescriptionResponse { private boolean valid; private ArrayList<String> messages; private HashSet<ERxComponent> componentsInError; public ValidatePrescriptionResponse() { this.messages = new ArrayList<>(); this.componentsInError = new HashSet<>(); this.valid = true; } public boolean isValid() { return valid; } public ArrayList<String> getMessages() { return messages; } public HashSet<ERxComponent> getComponentsInError() { return componentsInError; }
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionResponse.java import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.RxValidationResult; import java.util.ArrayList; import java.util.HashSet; package rxdemo.commands; public class ValidatePrescriptionResponse { private boolean valid; private ArrayList<String> messages; private HashSet<ERxComponent> componentsInError; public ValidatePrescriptionResponse() { this.messages = new ArrayList<>(); this.componentsInError = new HashSet<>(); this.valid = true; } public boolean isValid() { return valid; } public ArrayList<String> getMessages() { return messages; } public HashSet<ERxComponent> getComponentsInError() { return componentsInError; }
public void includeValidationResult(RxValidationResult result) {
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/drug/DispensableDrugShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // }
import org.junit.Assert; import org.junit.Test; import rxdemo.vendordata.EDrugClassification;
package rxdemo.drug; public class DispensableDrugShould { // testing a change. @Test public void beConstructableWithListOfClassifications() { DispensableDrug drug = new DispensableDrug(1, "testdrug",
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // } // Path: rxdemo-server/core/src/test/java/rxdemo/drug/DispensableDrugShould.java import org.junit.Assert; import org.junit.Test; import rxdemo.vendordata.EDrugClassification; package rxdemo.drug; public class DispensableDrugShould { // testing a change. @Test public void beConstructableWithListOfClassifications() { DispensableDrug drug = new DispensableDrug(1, "testdrug",
EDrugClassification.ANALGESIC, EDrugClassification.ANTIANXIETY);
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*;
package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2;
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*; package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2;
private Prescription rx;
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*;
package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2; private Prescription rx; @Before public void setUp() { rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn(
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*; package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2; private Prescription rx; @Before public void setUp() { rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn(
invalidResult("Error Message 1", ERxComponent.DOSE_AMOUNT,
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*;
package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2; private Prescription rx; @Before public void setUp() { rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 1", ERxComponent.DOSE_AMOUNT, ERxComponent.DURATION)); invalidRule2 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule2.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 2", ERxComponent.FREQUENCY)); }
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*; package rxdemo.commands; public class ValidatePrescriptionCommandShould { private IRxValidationRule alwaysValidRule; private IRxValidationRule invalidRule1; private IRxValidationRule invalidRule2; private Prescription rx; @Before public void setUp() { rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 1", ERxComponent.DOSE_AMOUNT, ERxComponent.DURATION)); invalidRule2 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule2.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 2", ERxComponent.FREQUENCY)); }
private RxValidationResult validResult() {
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*;
rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 1", ERxComponent.DOSE_AMOUNT, ERxComponent.DURATION)); invalidRule2 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule2.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 2", ERxComponent.FREQUENCY)); } private RxValidationResult validResult() { return new RxValidationResult(); } private RxValidationResult invalidResult(String message, ERxComponent... components) { RxValidationResult result = new RxValidationResult(); result.setMessage(message); for (ERxComponent component : components) { result.addInvalidComponent(component); } return result; } @Test public void returnValidResponseIfNoRulesAreInError() {
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/ERxComponent.java // public enum ERxComponent { // // DRUG("Drug"), // DOSE_AMOUNT("Dose Amount"), // DOSE_UNIT("Dose Unit"), // ROUTE("Route"), // FREQUENCY("Frequency"), // DURATION("Duration"); // // private String description; // // ERxComponent(String description) { // this.description = description; // } // // public String getDescription() { // return description; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/IRxValidationRule.java // public interface IRxValidationRule { // // RxValidationResult validateAgainstRule(Prescription rx); // // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/test/java/rxdemo/commands/ValidatePrescriptionCommandShould.java import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.ERxComponent; import rxdemo.prescription.validation.IRxValidationRule; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.ArrayList; import java.util.Arrays; import static org.junit.Assert.*; rx = new Prescription(); alwaysValidRule = Mockito.mock(IRxValidationRule.class); Mockito.when(alwaysValidRule.validateAgainstRule(rx)).thenReturn(validResult()); invalidRule1 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule1.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 1", ERxComponent.DOSE_AMOUNT, ERxComponent.DURATION)); invalidRule2 = Mockito.mock(IRxValidationRule.class); Mockito.when(invalidRule2.validateAgainstRule(rx)).thenReturn( invalidResult("Error Message 2", ERxComponent.FREQUENCY)); } private RxValidationResult validResult() { return new RxValidationResult(); } private RxValidationResult invalidResult(String message, ERxComponent... components) { RxValidationResult result = new RxValidationResult(); result.setMessage(message); for (ERxComponent component : components) { result.addInvalidComponent(component); } return result; } @Test public void returnValidResponseIfNoRulesAreInError() {
RxValidator validator = buildValidatorWithRules(alwaysValidRule);
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/RxBase.java
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // }
import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection;
package page; public class RxBase { private static final String URL1 = "http://"
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // } // Path: rxdemo-selenium/src/test/java/page/RxBase.java import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection; package page; public class RxBase { private static final String URL1 = "http://"
+ RxConstants.RX_BASE_URL;
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/RxBase.java
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // }
import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection;
public RxBase(String inBrowserName, String inAddress, DesiredCapabilities inDC, String inItemName) { mBrowserName = inBrowserName; mDC = inDC; mAddress = inAddress; mItemName = inItemName; } public WebDriver getMDriver() { return mDriver; } public void setMDriver(WebDriver mDriver) { this.mDriver = mDriver; } public DesiredCapabilities getMDC() { return mDC; } public void setMDC(DesiredCapabilities mDC) { this.mDC = mDC; } public String getMAddress() { return mAddress; } public void setMAddress(String mAddress) { this.mAddress = mAddress; } @Parameterized.Parameters public static Collection<Object[]> browserId() {
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // } // Path: rxdemo-selenium/src/test/java/page/RxBase.java import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection; public RxBase(String inBrowserName, String inAddress, DesiredCapabilities inDC, String inItemName) { mBrowserName = inBrowserName; mDC = inDC; mAddress = inAddress; mItemName = inItemName; } public WebDriver getMDriver() { return mDriver; } public void setMDriver(WebDriver mDriver) { this.mDriver = mDriver; } public DesiredCapabilities getMDC() { return mDC; } public void setMDC(DesiredCapabilities mDC) { this.mDC = mDC; } public String getMAddress() { return mAddress; } public void setMAddress(String mAddress) { this.mAddress = mAddress; } @Parameterized.Parameters public static Collection<Object[]> browserId() {
return StartBrowserSelections
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/RxBase.java
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // }
import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection;
return mDriver; } public void setMDriver(WebDriver mDriver) { this.mDriver = mDriver; } public DesiredCapabilities getMDC() { return mDC; } public void setMDC(DesiredCapabilities mDC) { this.mDC = mDC; } public String getMAddress() { return mAddress; } public void setMAddress(String mAddress) { this.mAddress = mAddress; } @Parameterized.Parameters public static Collection<Object[]> browserId() { return StartBrowserSelections .startALocalBrowser(RxConstants.RX_ITEM); } @Before public void setUp() throws Exception { mDriver = new RemoteWebDriver(new URL("http://" + mAddress + ":4444/wd/hub"), mDC);
// Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/SetupRx.java // public class SetupRx // { // // public static void setupRx(WebDriver inDriver, // String inURL1, String inURL2, String inBrowserName, String inItemName) // { // inDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // inDriver.get(inURL1 + inURL2); // WaitForObjects.waitUntilxpath(inDriver, RxConstants.H1_TITLE_RX_DEMO); // System.out.println(inBrowserName + " - " + inItemName); // } // } // // Path: rxdemo-selenium/src/test/java/util/StartBrowserSelections.java // public class StartBrowserSelections { // public static Collection<Object[]> startALocalBrowser(String inItems) // { // // List<Object[]> retVal = new ArrayList<Object[]>(); // retVal.add( new Object[] // { // // "Chrome", RxConstants.SELENIUM_SERVER_FOR_L_CHROME, // DesiredCapabilities.chrome(), inItems // }); // // return retVal; // // } // } // Path: rxdemo-selenium/src/test/java/page/RxBase.java import org.junit.After; import org.junit.Before; import org.junit.runners.Parameterized; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import util.RxConstants; import util.SetupRx; import util.StartBrowserSelections; import java.net.URL; import java.util.Collection; return mDriver; } public void setMDriver(WebDriver mDriver) { this.mDriver = mDriver; } public DesiredCapabilities getMDC() { return mDC; } public void setMDC(DesiredCapabilities mDC) { this.mDC = mDC; } public String getMAddress() { return mAddress; } public void setMAddress(String mAddress) { this.mAddress = mAddress; } @Parameterized.Parameters public static Collection<Object[]> browserId() { return StartBrowserSelections .startALocalBrowser(RxConstants.RX_ITEM); } @Before public void setUp() throws Exception { mDriver = new RemoteWebDriver(new URL("http://" + mAddress + ":4444/wd/hub"), mDC);
SetupRx.setupRx(mDriver,
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // }
import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id;
public EnterPrescriptionCommand WithDoseAmount(int doseamount) { this.doseamount = doseamount; return this; } public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) {
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // } // Path: rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id; public EnterPrescriptionCommand WithDoseAmount(int doseamount) { this.doseamount = doseamount; return this; } public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) {
mDriver.findElement(id( RxConstants.INPUT_DRUG_MEDICATION_DOSE_AMOUNT)).sendKeys(String.valueOf(doseamount));;
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // }
import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id;
public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) { mDriver.findElement(id( RxConstants.INPUT_DRUG_MEDICATION_DOSE_AMOUNT)).sendKeys(String.valueOf(doseamount));; mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DOSE_UNIT)).sendKeys(doseunit); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_ROUTE)).sendKeys(route); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_FREQUENCY)).sendKeys(frequency); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DURATION)).sendKeys(duration);
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // } // Path: rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id; public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) { mDriver.findElement(id( RxConstants.INPUT_DRUG_MEDICATION_DOSE_AMOUNT)).sendKeys(String.valueOf(doseamount));; mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DOSE_UNIT)).sendKeys(doseunit); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_ROUTE)).sendKeys(route); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_FREQUENCY)).sendKeys(frequency); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DURATION)).sendKeys(duration);
WaitForObjects.waitUntilxpath(mDriver, RxConstants.BTN_RX_ADD_RX_TO_CART);
weaverj/testpyramidexample
rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // }
import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id;
public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) { mDriver.findElement(id( RxConstants.INPUT_DRUG_MEDICATION_DOSE_AMOUNT)).sendKeys(String.valueOf(doseamount));; mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DOSE_UNIT)).sendKeys(doseunit); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_ROUTE)).sendKeys(route); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_FREQUENCY)).sendKeys(frequency); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DURATION)).sendKeys(duration); WaitForObjects.waitUntilxpath(mDriver, RxConstants.BTN_RX_ADD_RX_TO_CART);
// Path: rxdemo-selenium/src/test/java/util/ButtonClick.java // public class ButtonClick { // public static void buttonClickByXpath(WebDriver inDriver, String inButtonID, String inButtonValue) // { // // WebElement // searchElement = inDriver.findElement(By.xpath(inButtonID)); // String jsTag = searchElement.getTagName(); // String jsValue = searchElement.getText().replaceAll("\\s+$", ""); // assertEquals(inButtonValue, jsValue); // searchElement.click(); // System.out.println(jsTag + " '" + jsValue + "'" + " was Clicked!"); // } // } // // Path: rxdemo-selenium/src/test/java/util/RxConstants.java // public class RxConstants { // // public static final String RX_ITEM = "Rx APP"; // // //http://localhost:9000/ // // public static final String RX_BASE_URL = "localhost:8090/rxdemo"; // public static final String RX_BASE_URL = "localhost:9000"; // // public static final String SELENIUM_SERVER_FOR_L_CHROME = "localhost"; // // public static final String H1_TITLE_RX_DEMO = "/html/body/div/h1"; // public static final String H1_TITLE_RX_DEMO_TEXT = "Rx Demo"; // // //"Medication" // public static final String LABEL_MEDICATION = "/html/body/form/fieldset[1]/div/label"; // public static final String LABEL_MEDICATION_TEXT = "Medication"; // // public static final String SELECT_DRUG_MEDICATION = "medication"; // public static final String SELECT_DRUG_MEDICATION_DIAZEPAM = "diazepam"; // public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT = "dose-amount"; // //public static final String INPUT_DRUG_MEDICATION_DOSE_AMOUNT_10 = "10"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT = "dose-unit"; // public static final String INPUT_DRUG_MEDICATION_DOSE_UNIT_TABLET = "tablet"; // public static final String INPUT_DRUG_MEDICATION_ROUTE = "route"; // public static final String INPUT_DRUG_MEDICATION_ROUTE_ORAL = "Oral"; // public static final String INPUT_DRUG_MEDICATION_DURATION = "duration"; // public static final String INPUT_DRUG_MEDICATION_DURATION_29_DAYS = "29 days"; // public static final String INPUT_DRUG_MEDICATION_DURATION_31_DAYS = "31 days"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY = "frequency"; // public static final String INPUT_DRUG_MEDICATION_FREQUENCY_ONCE_DAILY = "once per day"; // // public static final String SUCCESS_MESSAGE = "//*[@id=\'successMessages\']"; // public static final String PROHIBITED_MESSAGE = "//*[@id=\'errorMessages\']"; // public static final String BTN_RX_ADD_RX_TO_CART = "/html/body/form/button[1]"; // public static final String BTN_RX_ADD_RX_TO_CART_TEXT = "Add Rx to Cart"; // public static final String BTN_CANCEL = "/html/body/form/button[2]"; // public static final String BTN_CANCEL_TEXT = "Cancel"; // // public static final String DIV_TEXT_ERROR_MESSAGE = "//*[@id=\'errorMessages\']/div[1]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_TEXT = // "The following fields are required: Dose Amount, Dose Unit, Frequency, Route, Duration."; // // public static final String DIV_TEXT_ERROR_MESSAGE_2 = "//*[@id=\'errorMessages\']/div[2]/text()"; // public static final String DIV_TEXT_ERROR_MESSAGE_2_TEXT = // "Prescibing opioids and benzodiazepines in quantities greater than a 30-day supply is prohibited. " + // "Refills may be used to extend the intended duration of treatment."; // // public static final String MESSAGE_FAILED_TO_LAUNCH = "Failed to Launch Home Page!"; // public static final String MESSAGE_BUTTONS_UNAVAILABLE = "Buttons are not Available!"; // // public static final String SUCCESSFUL_PRESCRIPTION = "Prescription successfully transmitted."; // // // } // // Path: rxdemo-selenium/src/test/java/util/WaitForObjects.java // public class WaitForObjects { // public static void waitUntilxpath (WebDriver inDriver, String inID) { // WebElement myElement = (new WebDriverWait(inDriver, 20)) // .until( presenceOfElementLocated( By.xpath(inID))); // } // // // } // Path: rxdemo-selenium/src/test/java/page/EnterPrescriptionCommand.java import org.openqa.selenium.WebDriver; import util.ButtonClick; import util.RxConstants; import util.WaitForObjects; import static org.openqa.selenium.By.id; public EnterPrescriptionCommand WithDoseUnit(String doseunit) { this.doseunit = doseunit; return this; } public EnterPrescriptionCommand WithRoute(String route) { this.route = route; return this; } public EnterPrescriptionCommand WithFrequency(String frequency) { this.frequency = frequency; return this; } public EnterPrescriptionCommand WithDuration(String duration) { this.duration = duration; return this; } //TODO - submit new fields. public void AddRxtoCart(WebDriver mDriver) { mDriver.findElement(id( RxConstants.INPUT_DRUG_MEDICATION_DOSE_AMOUNT)).sendKeys(String.valueOf(doseamount));; mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DOSE_UNIT)).sendKeys(doseunit); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_ROUTE)).sendKeys(route); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_FREQUENCY)).sendKeys(frequency); mDriver.findElement(id(RxConstants.INPUT_DRUG_MEDICATION_DURATION)).sendKeys(duration); WaitForObjects.waitUntilxpath(mDriver, RxConstants.BTN_RX_ADD_RX_TO_CART);
ButtonClick.buttonClickByXpath(mDriver,
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionCommand.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.List;
package rxdemo.commands; public class ValidatePrescriptionCommand { private RxValidator validator; public ValidatePrescriptionCommand(RxValidator validator) { this.validator = validator; }
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionCommand.java import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.List; package rxdemo.commands; public class ValidatePrescriptionCommand { private RxValidator validator; public ValidatePrescriptionCommand(RxValidator validator) { this.validator = validator; }
public ValidatePrescriptionResponse validatePrescription(Prescription rx) {
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionCommand.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // }
import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.List;
package rxdemo.commands; public class ValidatePrescriptionCommand { private RxValidator validator; public ValidatePrescriptionCommand(RxValidator validator) { this.validator = validator; } public ValidatePrescriptionResponse validatePrescription(Prescription rx) { ValidatePrescriptionResponse response = new ValidatePrescriptionResponse();
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/Prescription.java // public class Prescription { // // private DispensableDrug drug; // private String doseAmount; // private String doseUnit; // private String route; // private String frequency; // private String duration; // // public DispensableDrug getDrug() { // return drug; // } // // public void setDrug(DispensableDrug drug) { // this.drug = drug; // } // // public String getDoseAmount() { // return doseAmount; // } // // public void setDoseAmount(String doseAmount) { // this.doseAmount = doseAmount; // } // // public String getDoseUnit() { // return doseUnit; // } // // public void setDoseUnit(String doseUnit) { // this.doseUnit = doseUnit; // } // // public String getRoute() { // return route; // } // // public void setRoute(String route) { // this.route = route; // } // // public String getFrequency() { // return frequency; // } // // public void setFrequency(String frequency) { // this.frequency = frequency; // } // // public String getDuration() { // return duration; // } // // public void setDuration(String duration) { // this.duration = duration; // } // // public int getDurationAsDays() { // return DurationParser.parseDays(this.duration); // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidationResult.java // public class RxValidationResult { // // private String message; // private List<ERxComponent> componentsInvalid; // // public RxValidationResult() { // this.componentsInvalid = new ArrayList<>(); // } // // public boolean isValid() { // return componentsInvalid.isEmpty(); // } // // public String getMessage() { // return message; // } // // public List<ERxComponent> getComponentsInvalid() { // return componentsInvalid; // } // // public void addInvalidComponent(ERxComponent component) { // componentsInvalid.add(component); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: rxdemo-server/core/src/main/java/rxdemo/prescription/validation/RxValidator.java // public class RxValidator { // // private static RxValidator defaultValidator; // private List<IRxValidationRule> rules; // // static { // ArrayList<IRxValidationRule> defaultRules = new ArrayList<>(); // defaultRules.add(new RequiredRxFieldsValidationRule()); // defaultRules.add(new OpiateDurationValidationRule()); // defaultValidator = new RxValidator(defaultRules); // } // // public static RxValidator getDefaultValidator() { // return defaultValidator; // } // // public RxValidator(List<IRxValidationRule> rules) { // this.rules = (rules != null)? rules : new ArrayList<>(); // } // // public List<RxValidationResult> validatePrescription(Prescription rx) { // ArrayList<RxValidationResult> results = new ArrayList<>(); // for (IRxValidationRule rule : rules) { // results.add(rule.validateAgainstRule(rx)); // } // return results; // } // // } // Path: rxdemo-server/core/src/main/java/rxdemo/commands/ValidatePrescriptionCommand.java import rxdemo.prescription.Prescription; import rxdemo.prescription.validation.RxValidationResult; import rxdemo.prescription.validation.RxValidator; import java.util.List; package rxdemo.commands; public class ValidatePrescriptionCommand { private RxValidator validator; public ValidatePrescriptionCommand(RxValidator validator) { this.validator = validator; } public ValidatePrescriptionResponse validatePrescription(Prescription rx) { ValidatePrescriptionResponse response = new ValidatePrescriptionResponse();
List<RxValidationResult> validationResults = validator.validatePrescription(rx);
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/fitnesse/DurationParsesToDays.java
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/DurationParser.java // public class DurationParser { // // /** // * Returns 0 for strings not parseable to days. // */ // public static int parseDays(String durationString) { // String[] parts = durationString.split(" "); // if (parts.length == 2) { // return unitValueCalculation(parts[1], parts[0]); // } // else if (parts.length == 1) // { // if (parts[0].equalsIgnoreCase("once")) return 1; // } // return 0; // } // // private static int unitValueCalculation(String unitString, String valueString) { // EDurationUnit unit = EDurationUnit.getByTextValue(unitString); // if (unit == null) { // return 0; // } // return (parseValue(valueString) * unit.getMultiplier()); // } // // private static int parseValue(String valueString) { // try { // return Integer.valueOf(valueString); // } // catch (Throwable t) { // return 0; // } // } // }
import rxdemo.prescription.DurationParser;
package rxdemo.fitnesse; public class DurationParsesToDays { private String duration; public void setDuration(String duration) { this.duration = duration; } public int days() {
// Path: rxdemo-server/core/src/main/java/rxdemo/prescription/DurationParser.java // public class DurationParser { // // /** // * Returns 0 for strings not parseable to days. // */ // public static int parseDays(String durationString) { // String[] parts = durationString.split(" "); // if (parts.length == 2) { // return unitValueCalculation(parts[1], parts[0]); // } // else if (parts.length == 1) // { // if (parts[0].equalsIgnoreCase("once")) return 1; // } // return 0; // } // // private static int unitValueCalculation(String unitString, String valueString) { // EDurationUnit unit = EDurationUnit.getByTextValue(unitString); // if (unit == null) { // return 0; // } // return (parseValue(valueString) * unit.getMultiplier()); // } // // private static int parseValue(String valueString) { // try { // return Integer.valueOf(valueString); // } // catch (Throwable t) { // return 0; // } // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/fitnesse/DurationParsesToDays.java import rxdemo.prescription.DurationParser; package rxdemo.fitnesse; public class DurationParsesToDays { private String duration; public void setDuration(String duration) { this.duration = duration; } public int days() {
return DurationParser.parseDays(duration);
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/drug/DispensableDrug.java
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // }
import rxdemo.vendordata.EDrugClassification; import java.util.Arrays; import java.util.HashSet; import java.util.Set;
package rxdemo.drug; public class DispensableDrug { private int drugId; private String name;
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/drug/DispensableDrug.java import rxdemo.vendordata.EDrugClassification; import java.util.Arrays; import java.util.HashSet; import java.util.Set; package rxdemo.drug; public class DispensableDrug { private int drugId; private String name;
private Set<EDrugClassification> classifications;
weaverj/testpyramidexample
rxdemo-server/core/src/test/java/rxdemo/drug/OpiatesDrugConceptShould.java
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // }
import org.junit.Assert; import org.junit.Test; import rxdemo.vendordata.EDrugClassification;
package rxdemo.drug; public class OpiatesDrugConceptShould { @Test public void identifyDrugInConcept() { DispensableDrug drug = new DispensableDrug(1, "diazepam",
// Path: rxdemo-server/core/src/main/java/rxdemo/vendordata/EDrugClassification.java // public enum EDrugClassification { // ANALGESIC(3645, "Analgesic, Anti-inflammatory, or Antipyretic"), // ANALGESICS_NARCOTIC(582, "Analgesics - Narcotic"), // ANTIANXIETY(523, "Antianxiety Agent - Benzodiazepines"), // ANTIBACTERIAL(2549, "Antibacterial Agents"), // VITAMINS_WATER_SOLUBLE(658, "Vitamins - Water Soluble"), // NASAL_CORTICOSTEROIDS(301, "Nasal Corticosteroids"), // ACE_INHIBITORS(6108, "ACE Inhibitors and ACE Inhibitor Combinations"), // ANTIHYPERLIPIDEMICS(263, "Antihyperlipidemics"), // NARCOTIC_ANTHISTAMINE(338, "Narcotic Antitussive-Antihistamine Combinations"), // PLATELET_AGGREGATION_INHIBITORS(3530, "Platelet Aggregation Inhibitors and Combinations"); // // // private int etcClassificationCode; // private String description; // // // EDrugClassification(int code, String description) { // this.etcClassificationCode = code; // this.description = description; // } // // public int getEtcClassificationCode() { // return etcClassificationCode; // } // // public String getDescription() { // return description; // } // } // Path: rxdemo-server/core/src/test/java/rxdemo/drug/OpiatesDrugConceptShould.java import org.junit.Assert; import org.junit.Test; import rxdemo.vendordata.EDrugClassification; package rxdemo.drug; public class OpiatesDrugConceptShould { @Test public void identifyDrugInConcept() { DispensableDrug drug = new DispensableDrug(1, "diazepam",
EDrugClassification.ANTIANXIETY);
weaverj/testpyramidexample
rxdemo-server/core/src/main/java/rxdemo/fitnesse/OpiatesClassRow.java
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/DispensableDrug.java // public class DispensableDrug { // private int drugId; // private String name; // private Set<EDrugClassification> classifications; // // public DispensableDrug(int drugId, String name, EDrugClassification...classifications) { // this.drugId = drugId; // this.name = name; // this.classifications = new HashSet<>(); // this.classifications.addAll(Arrays.asList(classifications)); // } // // public int getDrugId() { // return drugId; // } // // public String getName() { // return name; // } // // public Set<EDrugClassification> getClassifications() { // return classifications; // } // // public boolean isFreeText() { // return false; // } // }
import rxdemo.drug.DispensableDrug; import java.util.List;
package rxdemo.fitnesse; public class OpiatesClassRow { private int classCode; private String description;
// Path: rxdemo-server/core/src/main/java/rxdemo/drug/DispensableDrug.java // public class DispensableDrug { // private int drugId; // private String name; // private Set<EDrugClassification> classifications; // // public DispensableDrug(int drugId, String name, EDrugClassification...classifications) { // this.drugId = drugId; // this.name = name; // this.classifications = new HashSet<>(); // this.classifications.addAll(Arrays.asList(classifications)); // } // // public int getDrugId() { // return drugId; // } // // public String getName() { // return name; // } // // public Set<EDrugClassification> getClassifications() { // return classifications; // } // // public boolean isFreeText() { // return false; // } // } // Path: rxdemo-server/core/src/main/java/rxdemo/fitnesse/OpiatesClassRow.java import rxdemo.drug.DispensableDrug; import java.util.List; package rxdemo.fitnesse; public class OpiatesClassRow { private int classCode; private String description;
private List<DispensableDrug> includedDrugs;
yahoo/squidb
squidb-tests/src/com/yahoo/squidb/data/JSONPropertyTest.java
// Path: squidb-addons/squidb-json/squidb-json-plugin/src/com/yahoo/squidb/json/JSONPropertySupport.java // public class JSONPropertySupport { // // private static final String TAG = "squidb-json"; // // private static JSONMapper MAPPER = null; // // public static void setJSONMapper(JSONMapper jsonMapper) { // MAPPER = jsonMapper; // } // // private static class JSONObjectHolder<T> { // final T parsedObject; // final String jsonString; // // JSONObjectHolder(T parsedObject, String jsonString) { // this.parsedObject = parsedObject; // this.jsonString = jsonString; // } // } // // /** // * Deserialize a JSON string property into the specified Java type // */ // public static <T> T getValueFromJSON(AbstractModel model, JSONProperty<T> property, Type javaType) { // String transitoryKey = transitoryKeyForProperty(property); // checkCacheIntegrity(model, property, transitoryKey); // // if (!model.hasTransitory(transitoryKey)) { // T data = null; // String json = model.get(property); // Will throw if model doesn't have property // if (json != null) { // try { // if (MAPPER == null) { // throw new NullPointerException("JSONPropertySupport needs to be initialized with a " // + "JSONMapper instance using setJSONMapper()"); // } // data = MAPPER.fromJSON(json, javaType); // } catch (Exception e) { // // TODO: Should this throw or at least not cache null? // Logger.w(TAG, "Error deserializing JSON string: " + json, e); // model.clearValue(property); // } // } // putJSONTransitory(model, transitoryKey, data, json); // return data; // } // // JSONObjectHolder<T> holder = getJSONTransitory(model, transitoryKey); // return holder.parsedObject; // } // // /** // * Sets the given JSON-serialized property to the given value // * // * @return true if the value object was successfully serialized, false otherwise // */ // public static <T> boolean setValueAsJSON(AbstractModel model, JSONProperty<T> property, T data, Type javaType) { // try { // String json = null; // if (data != null) { // if (MAPPER == null) { // throw new NullPointerException("JSONPropertySupport needs to be initialized with a " // + "JSONMapper instance using setJSONMapper()"); // } // json = MAPPER.toJSON(data, javaType); // if (model.containsNonNullValue(property) && json.equals(model.get(property))) { // return false; // } // } // model.set(property, json); // putJSONTransitory(model, transitoryKeyForProperty(property), data, json); // return true; // } catch (Exception e) { // Logger.w(TAG, "Error serializing object to JSON string: " + data, e); // // TODO: Should this throw? // return false; // } // } // // private static String transitoryKeyForProperty(JSONProperty<?> property) { // return "json__" + property.getName(); // } // // private static <T> void putJSONTransitory(AbstractModel model, String transitoryKey, T data, String jsonString) { // model.putTransitory(transitoryKey, new JSONObjectHolder<>(data, jsonString)); // } // // // We need to be able to check that our cached value is still correct, because some methods like // // model.clear(property) aren't able to clear associated transitory values // private static void checkCacheIntegrity(AbstractModel model, JSONProperty<?> property, String transitoryKey) { // if (!model.hasTransitory(transitoryKey)) { // return; // } // JSONObjectHolder<?> holder = getJSONTransitory(model, transitoryKey); // if (model.containsValue(property) || model.getDefaultValues().containsKey(property.getName())) { // String jsonValue = model.get(property); // if (SqlUtils.equals(holder.jsonString, jsonValue)) { // return; // } // } // model.clearTransitory(transitoryKey); // } // // @SuppressWarnings("unchecked") // private static <T> JSONObjectHolder<T> getJSONTransitory(AbstractModel model, String transitoryKey) { // return (JSONObjectHolder<T>) model.getTransitory(transitoryKey); // } // // }
import com.yahoo.squidb.json.JSONMapper; import com.yahoo.squidb.json.JSONPropertySupport; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.Employee; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.TestViewModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map;
return JSONObject.NULL; } if (toSerialize instanceof Map) { JSONObject result = new JSONObject(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) toSerialize).entrySet()) { result.put((String) entry.getKey(), toOrgJsonObject(entry.getValue())); } return result; } else if (toSerialize instanceof Collection) { return new JSONArray((Collection) toSerialize); } else if (toSerialize instanceof JSONPojo) { JSONPojo pojo = (JSONPojo) toSerialize; JSONObject result = new JSONObject(); result.put("pojoStr", pojo.pojoStr); result.put("pojoInt", pojo.pojoInt); result.put("pojoDouble", pojo.pojoDouble); result.put("pojoList", toOrgJsonObject(pojo.pojoList)); return result; } else { return toSerialize; } } } protected void testWithAllMappers(Runnable toTest) { for (MapperAndCounter mapper : MAPPERS) { mapper.fromJSONCount = 0; mapper.toJSONCount = 0; currentMapper = mapper; database.clear();
// Path: squidb-addons/squidb-json/squidb-json-plugin/src/com/yahoo/squidb/json/JSONPropertySupport.java // public class JSONPropertySupport { // // private static final String TAG = "squidb-json"; // // private static JSONMapper MAPPER = null; // // public static void setJSONMapper(JSONMapper jsonMapper) { // MAPPER = jsonMapper; // } // // private static class JSONObjectHolder<T> { // final T parsedObject; // final String jsonString; // // JSONObjectHolder(T parsedObject, String jsonString) { // this.parsedObject = parsedObject; // this.jsonString = jsonString; // } // } // // /** // * Deserialize a JSON string property into the specified Java type // */ // public static <T> T getValueFromJSON(AbstractModel model, JSONProperty<T> property, Type javaType) { // String transitoryKey = transitoryKeyForProperty(property); // checkCacheIntegrity(model, property, transitoryKey); // // if (!model.hasTransitory(transitoryKey)) { // T data = null; // String json = model.get(property); // Will throw if model doesn't have property // if (json != null) { // try { // if (MAPPER == null) { // throw new NullPointerException("JSONPropertySupport needs to be initialized with a " // + "JSONMapper instance using setJSONMapper()"); // } // data = MAPPER.fromJSON(json, javaType); // } catch (Exception e) { // // TODO: Should this throw or at least not cache null? // Logger.w(TAG, "Error deserializing JSON string: " + json, e); // model.clearValue(property); // } // } // putJSONTransitory(model, transitoryKey, data, json); // return data; // } // // JSONObjectHolder<T> holder = getJSONTransitory(model, transitoryKey); // return holder.parsedObject; // } // // /** // * Sets the given JSON-serialized property to the given value // * // * @return true if the value object was successfully serialized, false otherwise // */ // public static <T> boolean setValueAsJSON(AbstractModel model, JSONProperty<T> property, T data, Type javaType) { // try { // String json = null; // if (data != null) { // if (MAPPER == null) { // throw new NullPointerException("JSONPropertySupport needs to be initialized with a " // + "JSONMapper instance using setJSONMapper()"); // } // json = MAPPER.toJSON(data, javaType); // if (model.containsNonNullValue(property) && json.equals(model.get(property))) { // return false; // } // } // model.set(property, json); // putJSONTransitory(model, transitoryKeyForProperty(property), data, json); // return true; // } catch (Exception e) { // Logger.w(TAG, "Error serializing object to JSON string: " + data, e); // // TODO: Should this throw? // return false; // } // } // // private static String transitoryKeyForProperty(JSONProperty<?> property) { // return "json__" + property.getName(); // } // // private static <T> void putJSONTransitory(AbstractModel model, String transitoryKey, T data, String jsonString) { // model.putTransitory(transitoryKey, new JSONObjectHolder<>(data, jsonString)); // } // // // We need to be able to check that our cached value is still correct, because some methods like // // model.clear(property) aren't able to clear associated transitory values // private static void checkCacheIntegrity(AbstractModel model, JSONProperty<?> property, String transitoryKey) { // if (!model.hasTransitory(transitoryKey)) { // return; // } // JSONObjectHolder<?> holder = getJSONTransitory(model, transitoryKey); // if (model.containsValue(property) || model.getDefaultValues().containsKey(property.getName())) { // String jsonValue = model.get(property); // if (SqlUtils.equals(holder.jsonString, jsonValue)) { // return; // } // } // model.clearTransitory(transitoryKey); // } // // @SuppressWarnings("unchecked") // private static <T> JSONObjectHolder<T> getJSONTransitory(AbstractModel model, String transitoryKey) { // return (JSONObjectHolder<T>) model.getTransitory(transitoryKey); // } // // } // Path: squidb-tests/src/com/yahoo/squidb/data/JSONPropertyTest.java import com.yahoo.squidb.json.JSONMapper; import com.yahoo.squidb.json.JSONPropertySupport; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Query; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.Employee; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.TestViewModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; return JSONObject.NULL; } if (toSerialize instanceof Map) { JSONObject result = new JSONObject(); for (Map.Entry<?, ?> entry : ((Map<?, ?>) toSerialize).entrySet()) { result.put((String) entry.getKey(), toOrgJsonObject(entry.getValue())); } return result; } else if (toSerialize instanceof Collection) { return new JSONArray((Collection) toSerialize); } else if (toSerialize instanceof JSONPojo) { JSONPojo pojo = (JSONPojo) toSerialize; JSONObject result = new JSONObject(); result.put("pojoStr", pojo.pojoStr); result.put("pojoInt", pojo.pojoInt); result.put("pojoDouble", pojo.pojoDouble); result.put("pojoList", toOrgJsonObject(pojo.pojoList)); return result; } else { return toSerialize; } } } protected void testWithAllMappers(Runnable toTest) { for (MapperAndCounter mapper : MAPPERS) { mapper.fromJSONCount = 0; mapper.toJSONCount = 0; currentMapper = mapper; database.clear();
JSONPropertySupport.setJSONMapper(mapper);
yahoo/squidb
squidb-tests/src/com/yahoo/squidb/sql/UpdateTest.java
// Path: squidb/src/com/yahoo/squidb/sql/TableStatement.java // public enum ConflictAlgorithm { // /** // * No conflict algorithm specified. // */ // NONE, // /** // * Aborts the command and reverts any changes made within the same transaction up to this point. // */ // ROLLBACK, // /** // * Aborts the command and reverts any changes made by this command up to this point. Changes made by other // * commands in the same transaction as this command and which have already completed are preserved. // */ // ABORT, // /** // * Aborts the command, but any changes to the database that the command made prior to encountering the // * constraint violation are preserved. // */ // FAIL, // /** // * When a constraint violation occurs, the one row that contains the constraint violation is not inserted or // * changed. Other rows before and after the row that contained the constraint violation continue to be inserted // * or updated normally. // */ // IGNORE, // /** // * When a UNIQUE constraint violation occurs, the pre-existing row that caused the constraint violation is // * removed prior to inserting or updating the current row. // */ // REPLACE // }
import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm; import com.yahoo.squidb.test.Constants; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.TestModel;
// update testModels set luckyNumber = 777 where luckyNumber <= 0; TestModel template = new TestModel().setLuckyNumber(777); Update update = Update.table(TestModel.TABLE).fromTemplate(template).where(criterion); CompiledStatement compiled = update.compile(database.getCompileContext()); verifyCompiledSqlArgs(compiled, 2, template.getLuckyNumber(), 0); assertEquals(rowsBeforeWithLuckyNumberLteZero, database.update(update)); int rowsAfterWithLuckyNumberLteZero = database.count(TestModel.class, criterion); int rowsWithNewLuckyNumber = database.count(TestModel.class, TestModel.LUCKY_NUMBER.eq(777)); assertEquals(0, rowsAfterWithLuckyNumberLteZero); assertTrue(rowsWithNewLuckyNumber >= rowsBeforeWithLuckyNumberLteZero); } public void testUpdateWithConflictIgnore() { final String samLastName = sam.getLastName(); final String kevinFirstName = kevin.getFirstName(); // check preconditions TestModel modelWithSamLastName = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eq(samLastName), TestModel.PROPERTIES); TestModel modelWithKevinFirstName = database .fetchByCriterion(TestModel.class, TestModel.FIRST_NAME.eq(kevinFirstName), TestModel.PROPERTIES); assertNotNull(modelWithSamLastName); assertNotNull(modelWithKevinFirstName); assertFalse(modelWithSamLastName.equals(modelWithKevinFirstName)); // update or ignore testModels set lastName = 'Bosley' where firstName = 'Kevin'
// Path: squidb/src/com/yahoo/squidb/sql/TableStatement.java // public enum ConflictAlgorithm { // /** // * No conflict algorithm specified. // */ // NONE, // /** // * Aborts the command and reverts any changes made within the same transaction up to this point. // */ // ROLLBACK, // /** // * Aborts the command and reverts any changes made by this command up to this point. Changes made by other // * commands in the same transaction as this command and which have already completed are preserved. // */ // ABORT, // /** // * Aborts the command, but any changes to the database that the command made prior to encountering the // * constraint violation are preserved. // */ // FAIL, // /** // * When a constraint violation occurs, the one row that contains the constraint violation is not inserted or // * changed. Other rows before and after the row that contained the constraint violation continue to be inserted // * or updated normally. // */ // IGNORE, // /** // * When a UNIQUE constraint violation occurs, the pre-existing row that caused the constraint violation is // * removed prior to inserting or updating the current row. // */ // REPLACE // } // Path: squidb-tests/src/com/yahoo/squidb/sql/UpdateTest.java import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm; import com.yahoo.squidb.test.Constants; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.TestModel; // update testModels set luckyNumber = 777 where luckyNumber <= 0; TestModel template = new TestModel().setLuckyNumber(777); Update update = Update.table(TestModel.TABLE).fromTemplate(template).where(criterion); CompiledStatement compiled = update.compile(database.getCompileContext()); verifyCompiledSqlArgs(compiled, 2, template.getLuckyNumber(), 0); assertEquals(rowsBeforeWithLuckyNumberLteZero, database.update(update)); int rowsAfterWithLuckyNumberLteZero = database.count(TestModel.class, criterion); int rowsWithNewLuckyNumber = database.count(TestModel.class, TestModel.LUCKY_NUMBER.eq(777)); assertEquals(0, rowsAfterWithLuckyNumberLteZero); assertTrue(rowsWithNewLuckyNumber >= rowsBeforeWithLuckyNumberLteZero); } public void testUpdateWithConflictIgnore() { final String samLastName = sam.getLastName(); final String kevinFirstName = kevin.getFirstName(); // check preconditions TestModel modelWithSamLastName = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eq(samLastName), TestModel.PROPERTIES); TestModel modelWithKevinFirstName = database .fetchByCriterion(TestModel.class, TestModel.FIRST_NAME.eq(kevinFirstName), TestModel.PROPERTIES); assertNotNull(modelWithSamLastName); assertNotNull(modelWithKevinFirstName); assertFalse(modelWithSamLastName.equals(modelWithKevinFirstName)); // update or ignore testModels set lastName = 'Bosley' where firstName = 'Kevin'
Update update = Update.table(TestModel.TABLE).onConflict(ConflictAlgorithm.IGNORE).set(TestModel.LAST_NAME,
yahoo/squidb
squidb-tests/src/com/yahoo/squidb/sql/InsertTest.java
// Path: squidb/src/com/yahoo/squidb/sql/TableStatement.java // public enum ConflictAlgorithm { // /** // * No conflict algorithm specified. // */ // NONE, // /** // * Aborts the command and reverts any changes made within the same transaction up to this point. // */ // ROLLBACK, // /** // * Aborts the command and reverts any changes made by this command up to this point. Changes made by other // * commands in the same transaction as this command and which have already completed are preserved. // */ // ABORT, // /** // * Aborts the command, but any changes to the database that the command made prior to encountering the // * constraint violation are preserved. // */ // FAIL, // /** // * When a constraint violation occurs, the one row that contains the constraint violation is not inserted or // * changed. Other rows before and after the row that contained the constraint violation continue to be inserted // * or updated normally. // */ // IGNORE, // /** // * When a UNIQUE constraint violation occurs, the pre-existing row that caused the constraint violation is // * removed prior to inserting or updating the current row. // */ // REPLACE // }
import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm; import com.yahoo.squidb.test.Constants; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.Thing;
cursor = database.query(Thing.class, Query.select(Thing.PROPERTIES).orderBy(Order.desc(Thing.ID)).limit(1)); if (cursor.moveToFirst()) { newThing = new Thing(cursor); } } finally { if (cursor != null) { cursor.close(); } } assertNotNull(newThing); assertEquals(Thing.DEFAULT_FOO, newThing.getFoo()); assertEquals(Thing.DEFAULT_BAR, newThing.getBar().intValue()); assertEquals(Thing.DEFAULT_IS_ALIVE, newThing.isAlive().booleanValue()); } public void testInsertWithCoflictIgnore() { final String lname = sam.getLastName(); // check preconditions // last name is unique TestModel shouldNotBeNull = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eq(lname), TestModel.PROPERTIES); assertNotNull(shouldNotBeNull); // insert or replace into testModels (firstName, lastName, isHappy, luckyNumber) values ("Jack", "Bosley", 0, // 777); final String fname = "Jack"; final boolean isHappy = false; final int luckyNumber = 777; Insert insert = Insert.into(TestModel.TABLE)
// Path: squidb/src/com/yahoo/squidb/sql/TableStatement.java // public enum ConflictAlgorithm { // /** // * No conflict algorithm specified. // */ // NONE, // /** // * Aborts the command and reverts any changes made within the same transaction up to this point. // */ // ROLLBACK, // /** // * Aborts the command and reverts any changes made by this command up to this point. Changes made by other // * commands in the same transaction as this command and which have already completed are preserved. // */ // ABORT, // /** // * Aborts the command, but any changes to the database that the command made prior to encountering the // * constraint violation are preserved. // */ // FAIL, // /** // * When a constraint violation occurs, the one row that contains the constraint violation is not inserted or // * changed. Other rows before and after the row that contained the constraint violation continue to be inserted // * or updated normally. // */ // IGNORE, // /** // * When a UNIQUE constraint violation occurs, the pre-existing row that caused the constraint violation is // * removed prior to inserting or updating the current row. // */ // REPLACE // } // Path: squidb-tests/src/com/yahoo/squidb/sql/InsertTest.java import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.sql.TableStatement.ConflictAlgorithm; import com.yahoo.squidb.test.Constants; import com.yahoo.squidb.test.DatabaseTestCase; import com.yahoo.squidb.test.TestModel; import com.yahoo.squidb.test.Thing; cursor = database.query(Thing.class, Query.select(Thing.PROPERTIES).orderBy(Order.desc(Thing.ID)).limit(1)); if (cursor.moveToFirst()) { newThing = new Thing(cursor); } } finally { if (cursor != null) { cursor.close(); } } assertNotNull(newThing); assertEquals(Thing.DEFAULT_FOO, newThing.getFoo()); assertEquals(Thing.DEFAULT_BAR, newThing.getBar().intValue()); assertEquals(Thing.DEFAULT_IS_ALIVE, newThing.isAlive().booleanValue()); } public void testInsertWithCoflictIgnore() { final String lname = sam.getLastName(); // check preconditions // last name is unique TestModel shouldNotBeNull = database.fetchByCriterion(TestModel.class, TestModel.LAST_NAME.eq(lname), TestModel.PROPERTIES); assertNotNull(shouldNotBeNull); // insert or replace into testModels (firstName, lastName, isHappy, luckyNumber) values ("Jack", "Bosley", 0, // 777); final String fname = "Jack"; final boolean isHappy = false; final int luckyNumber = 777; Insert insert = Insert.into(TestModel.TABLE)
.onConflict(ConflictAlgorithm.IGNORE)
yahoo/squidb
samples/squidb-ios-sample/squidb-ios-sample/squidb-gen/com/yahoo/squidb/sample/models/Task.java
// Path: squidb/src/com/yahoo/squidb/sql/Table.java // public class Table extends SqlTable<TableModel> { // // private final String tableConstraint; // protected LongProperty rowidProperty; // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name) { // this(modelClass, properties, name, null); // } // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, // String databaseName) { // this(modelClass, properties, name, databaseName, null, null); // } // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, String databaseName, // String tableConstraint) { // this(modelClass, properties, name, databaseName, tableConstraint, null); // } // // private Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, String databaseName, // String tableConstraint, String alias) { // super(modelClass, properties, name, databaseName); // this.tableConstraint = tableConstraint; // this.alias = alias; // } // // public Table qualifiedFromDatabase(String databaseName) { // Table result = new Table(modelClass, properties, getExpression(), databaseName, tableConstraint, alias); // result.rowidProperty = rowidProperty; // return result; // } // // @Override // public Table as(String newAlias) { // Table result = (Table) super.as(newAlias); // result.rowidProperty = rowidProperty == null ? null : result.qualifyField(rowidProperty); // return result; // } // // @Override // protected Table asNewAliasWithPropertiesArray(String newAlias, Property<?>[] newProperties) { // return new Table(modelClass, newProperties, getExpression(), qualifier, tableConstraint, newAlias); // } // // /** // * Construct an {@link Index} with the given name that indexes the given columns // * // * @param name the name for the index // * @param columns the properties representing the columns to index // * @return an Index // */ // public Index index(String name, Property<?>... columns) { // return new Index(name, this, false, columns); // } // // /** // * Construct a unique {@link Index} with the given name that indexes the given columns. Unique indexes do not allow // * duplicate entries. // * // * @param name the name for the index // * @param columns the properties representing the columns to index // * @return a unique Index // */ // public Index uniqueIndex(String name, Property<?>... columns) { // return new Index(name, this, true, columns); // } // // /** // * @return the additional table definition information used when creating the table // */ // public String getTableConstraint() { // return tableConstraint; // } // // @Override // public String toString() { // return super.toString() + " ModelClass=" + modelClass.getSimpleName() + " TableConstraint=" + tableConstraint; // } // // /** // * Append a CREATE TABLE statement that would create this table and its columns. Users should not call // * this method and instead let {@link com.yahoo.squidb.data.SquidDatabase} build tables automatically. // */ // public void appendCreateTableSql(CompileContext compileContext, StringBuilder sql, // PropertyVisitor<Void, StringBuilder> propertyVisitor) { // sql.append("CREATE TABLE IF NOT EXISTS ").append(getExpression()).append('('); // boolean needsComma = false; // for (Property<?> property : properties) { // if (TableModel.ROWID.equals(property.getExpression())) { // continue; // } // if (needsComma) { // sql.append(", "); // } // property.accept(propertyVisitor, sql); // needsComma = true; // } // if (!SqlUtils.isEmpty(getTableConstraint())) { // sql.append(", ").append(getTableConstraint()); // } // sql.append(')'); // } // // /** // * Sets the primary key column for this table. Do not call this method! Exposed only so that it can be set // * when initializing a model class. // * // * @param rowidProperty a LongProperty representing the table's primary key id column // */ // public void setRowIdProperty(LongProperty rowidProperty) { // if (this.rowidProperty != null) { // throw new UnsupportedOperationException("Can't call setRowIdProperty on a Table more than once"); // } // this.rowidProperty = rowidProperty; // } // // /** // * @return the property representing the table's rowid column (or a integer primary key rowid alias if one exists) // */ // public LongProperty getRowIdProperty() { // if (rowidProperty == null) { // throw new UnsupportedOperationException("Table " + getExpression() + " has no id property defined"); // } // return rowidProperty; // } // // /** // * Deprecated alias for {@link #getRowIdProperty()} // */ // @Deprecated // public LongProperty getIdProperty() { // return getRowIdProperty(); // } // }
import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.data.TableModel; import com.yahoo.squidb.data.ValuesStorage; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Property.IntegerProperty; import com.yahoo.squidb.sql.Property.LongProperty; import com.yahoo.squidb.sql.Property.StringProperty; import com.yahoo.squidb.sql.Table; import com.yahoo.squidb.sql.TableModelName; import java.util.Map;
package com.yahoo.squidb.sample.models; /** * This class was generated from the model spec at {@link com.yahoo.squidb.sample.models.TaskSpec} */ // Generated code -- do not modify! public class Task extends TableModel { // --- allocate properties array public static final Property<?>[] PROPERTIES = new Property<?>[5]; // --- table declaration
// Path: squidb/src/com/yahoo/squidb/sql/Table.java // public class Table extends SqlTable<TableModel> { // // private final String tableConstraint; // protected LongProperty rowidProperty; // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name) { // this(modelClass, properties, name, null); // } // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, // String databaseName) { // this(modelClass, properties, name, databaseName, null, null); // } // // public Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, String databaseName, // String tableConstraint) { // this(modelClass, properties, name, databaseName, tableConstraint, null); // } // // private Table(Class<? extends TableModel> modelClass, Property<?>[] properties, String name, String databaseName, // String tableConstraint, String alias) { // super(modelClass, properties, name, databaseName); // this.tableConstraint = tableConstraint; // this.alias = alias; // } // // public Table qualifiedFromDatabase(String databaseName) { // Table result = new Table(modelClass, properties, getExpression(), databaseName, tableConstraint, alias); // result.rowidProperty = rowidProperty; // return result; // } // // @Override // public Table as(String newAlias) { // Table result = (Table) super.as(newAlias); // result.rowidProperty = rowidProperty == null ? null : result.qualifyField(rowidProperty); // return result; // } // // @Override // protected Table asNewAliasWithPropertiesArray(String newAlias, Property<?>[] newProperties) { // return new Table(modelClass, newProperties, getExpression(), qualifier, tableConstraint, newAlias); // } // // /** // * Construct an {@link Index} with the given name that indexes the given columns // * // * @param name the name for the index // * @param columns the properties representing the columns to index // * @return an Index // */ // public Index index(String name, Property<?>... columns) { // return new Index(name, this, false, columns); // } // // /** // * Construct a unique {@link Index} with the given name that indexes the given columns. Unique indexes do not allow // * duplicate entries. // * // * @param name the name for the index // * @param columns the properties representing the columns to index // * @return a unique Index // */ // public Index uniqueIndex(String name, Property<?>... columns) { // return new Index(name, this, true, columns); // } // // /** // * @return the additional table definition information used when creating the table // */ // public String getTableConstraint() { // return tableConstraint; // } // // @Override // public String toString() { // return super.toString() + " ModelClass=" + modelClass.getSimpleName() + " TableConstraint=" + tableConstraint; // } // // /** // * Append a CREATE TABLE statement that would create this table and its columns. Users should not call // * this method and instead let {@link com.yahoo.squidb.data.SquidDatabase} build tables automatically. // */ // public void appendCreateTableSql(CompileContext compileContext, StringBuilder sql, // PropertyVisitor<Void, StringBuilder> propertyVisitor) { // sql.append("CREATE TABLE IF NOT EXISTS ").append(getExpression()).append('('); // boolean needsComma = false; // for (Property<?> property : properties) { // if (TableModel.ROWID.equals(property.getExpression())) { // continue; // } // if (needsComma) { // sql.append(", "); // } // property.accept(propertyVisitor, sql); // needsComma = true; // } // if (!SqlUtils.isEmpty(getTableConstraint())) { // sql.append(", ").append(getTableConstraint()); // } // sql.append(')'); // } // // /** // * Sets the primary key column for this table. Do not call this method! Exposed only so that it can be set // * when initializing a model class. // * // * @param rowidProperty a LongProperty representing the table's primary key id column // */ // public void setRowIdProperty(LongProperty rowidProperty) { // if (this.rowidProperty != null) { // throw new UnsupportedOperationException("Can't call setRowIdProperty on a Table more than once"); // } // this.rowidProperty = rowidProperty; // } // // /** // * @return the property representing the table's rowid column (or a integer primary key rowid alias if one exists) // */ // public LongProperty getRowIdProperty() { // if (rowidProperty == null) { // throw new UnsupportedOperationException("Table " + getExpression() + " has no id property defined"); // } // return rowidProperty; // } // // /** // * Deprecated alias for {@link #getRowIdProperty()} // */ // @Deprecated // public LongProperty getIdProperty() { // return getRowIdProperty(); // } // } // Path: samples/squidb-ios-sample/squidb-ios-sample/squidb-gen/com/yahoo/squidb/sample/models/Task.java import com.yahoo.squidb.data.SquidCursor; import com.yahoo.squidb.data.TableModel; import com.yahoo.squidb.data.ValuesStorage; import com.yahoo.squidb.sql.Property; import com.yahoo.squidb.sql.Property.IntegerProperty; import com.yahoo.squidb.sql.Property.LongProperty; import com.yahoo.squidb.sql.Property.StringProperty; import com.yahoo.squidb.sql.Table; import com.yahoo.squidb.sql.TableModelName; import java.util.Map; package com.yahoo.squidb.sample.models; /** * This class was generated from the model spec at {@link com.yahoo.squidb.sample.models.TaskSpec} */ // Generated code -- do not modify! public class Task extends TableModel { // --- allocate properties array public static final Property<?>[] PROPERTIES = new Property<?>[5]; // --- table declaration
public static final Table TABLE = new Table(Task.class, PROPERTIES, "tasks", null);
xia-st/JPython
src/pers/xia/jpython/grammar/Label.java
// Path: src/pers/xia/jpython/tokenizer/TokState.java // public enum TokState // { // ENDMARKER, // NAME, // NUMBER, // STRING, // NEWLINE, // INDENT, // DEDENT, // LPAR, // ( // RPAR, // ) // LSQB, // [ // RSQB, // ] // COLON, // : // COMMA, // , // SEMI, // ; // PLUS, // + // MINUS, // - // STAR, // * // SLASH, // / // VBAR, // | // AMPER, // & // LESS, // < // GREATER, // > // EQUAL, // = // DOT, // . // PERCENT, // % // BACKQUOTE, // LBRACE, // { // RBRACE, // } // EQEQUAL, // == // NOTEQUAL, // != // LESSEQUAL, // <= // GREATEREQUAL, // >= // TILDE, // ~ // CIRCUMFLEX, // ^ // LEFTSHIFT, // << // RIGHTSHIFT, // >> // DOUBLESTAR, // ** // PLUSEQUAL, // += // MINEQUAL, // -= // STAREQUAL, // *= // SLASHEQUAL, // /= // PERCENTEQUAL, // %= // AMPEREQUAL, // &= // VBAREQUAL, // |= // CIRCUMFLEXEQUAL, // ^= // LEFTSHIFTEQUAL, // <<= // RIGHTSHIFTEQUAL, // >>= // DOUBLESTAREQUAL, // **= // DOUBLESLASH, // \\ // DOUBLESLASHEQUAL, // \\= // AT, // @ // ATEQUAL, // @= // RARROW, // -> // ELLIPSIS, // ... // OP, // AWAIT, // await // ASYNC, // async // ERRORTOKEN, // N_TOKENS, // }
import pers.xia.jpython.tokenizer.TokState;
package pers.xia.jpython.grammar; public class Label { //DFAName dfaName; //DFA的名字 public int nextDfa; //下一个DFA
// Path: src/pers/xia/jpython/tokenizer/TokState.java // public enum TokState // { // ENDMARKER, // NAME, // NUMBER, // STRING, // NEWLINE, // INDENT, // DEDENT, // LPAR, // ( // RPAR, // ) // LSQB, // [ // RSQB, // ] // COLON, // : // COMMA, // , // SEMI, // ; // PLUS, // + // MINUS, // - // STAR, // * // SLASH, // / // VBAR, // | // AMPER, // & // LESS, // < // GREATER, // > // EQUAL, // = // DOT, // . // PERCENT, // % // BACKQUOTE, // LBRACE, // { // RBRACE, // } // EQEQUAL, // == // NOTEQUAL, // != // LESSEQUAL, // <= // GREATEREQUAL, // >= // TILDE, // ~ // CIRCUMFLEX, // ^ // LEFTSHIFT, // << // RIGHTSHIFT, // >> // DOUBLESTAR, // ** // PLUSEQUAL, // += // MINEQUAL, // -= // STAREQUAL, // *= // SLASHEQUAL, // /= // PERCENTEQUAL, // %= // AMPEREQUAL, // &= // VBAREQUAL, // |= // CIRCUMFLEXEQUAL, // ^= // LEFTSHIFTEQUAL, // <<= // RIGHTSHIFTEQUAL, // >>= // DOUBLESTAREQUAL, // **= // DOUBLESLASH, // \\ // DOUBLESLASHEQUAL, // \\= // AT, // @ // ATEQUAL, // @= // RARROW, // -> // ELLIPSIS, // ... // OP, // AWAIT, // await // ASYNC, // async // ERRORTOKEN, // N_TOKENS, // } // Path: src/pers/xia/jpython/grammar/Label.java import pers.xia.jpython.tokenizer.TokState; package pers.xia.jpython.grammar; public class Label { //DFAName dfaName; //DFA的名字 public int nextDfa; //下一个DFA
public TokState tokState;
xia-st/JPython
src/pers/xia/jpython/compiler/Compiler.java
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // }
import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode;
package pers.xia.jpython.compiler; public class Compiler {
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // } // Path: src/pers/xia/jpython/compiler/Compiler.java import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode; package pers.xia.jpython.compiler; public class Compiler {
public PyObject fileName;
xia-st/JPython
src/pers/xia/jpython/compiler/Compiler.java
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // }
import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode;
package pers.xia.jpython.compiler; public class Compiler { public PyObject fileName; public Symtable st; public int optimize; // optimization level public boolean interactive; // is or not interactive mode public int nestLevel; public CompilerUnit u;
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // } // Path: src/pers/xia/jpython/compiler/Compiler.java import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode; package pers.xia.jpython.compiler; public class Compiler { public PyObject fileName; public Symtable st; public int optimize; // optimization level public boolean interactive; // is or not interactive mode public int nestLevel; public CompilerUnit u;
public PyList stack;
xia-st/JPython
src/pers/xia/jpython/compiler/Compiler.java
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // }
import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode;
package pers.xia.jpython.compiler; public class Compiler { public PyObject fileName; public Symtable st; public int optimize; // optimization level public boolean interactive; // is or not interactive mode public int nestLevel; public CompilerUnit u; public PyList stack; private static PyObject __doc__; public Compiler() { this.stack = new PyList(0); } public Compiler(PyObject fileName, int optimize, Symtable st) { this.fileName = fileName; this.optimize = optimize; this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') {
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // } // Path: src/pers/xia/jpython/compiler/Compiler.java import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode; package pers.xia.jpython.compiler; public class Compiler { public PyObject fileName; public Symtable st; public int optimize; // optimization level public boolean interactive; // is or not interactive mode public int nestLevel; public CompilerUnit u; public PyList stack; private static PyObject __doc__; public Compiler() { this.stack = new PyList(0); } public Compiler(PyObject fileName, int optimize, Symtable st) { this.fileName = fileName; this.optimize = optimize; this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') {
return PyUnicode.internFromString(ident);
xia-st/JPython
src/pers/xia/jpython/compiler/Compiler.java
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // }
import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode;
this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') { return PyUnicode.internFromString(ident); } int nlen = ident.length(); int plen = privateStr.length(); if(ident.charAt(nlen - 1) == '_' && ident.charAt(nlen - 2) == '_' || ident.indexOf('.') < 0) { return PyUnicode.internFromString(ident); } int ipriv = 0; while(ipriv < plen && privateStr.charAt(ipriv) == '_') ipriv++; if(ipriv == plen) { return PyUnicode.internFromString(ident); } return PyUnicode.internFromString(privateStr.substring(ipriv) + ident); }
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // } // Path: src/pers/xia/jpython/compiler/Compiler.java import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode; this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') { return PyUnicode.internFromString(ident); } int nlen = ident.length(); int plen = privateStr.length(); if(ident.charAt(nlen - 1) == '_' && ident.charAt(nlen - 2) == '_' || ident.indexOf('.') < 0) { return PyUnicode.internFromString(ident); } int ipriv = 0; while(ipriv < plen && privateStr.charAt(ipriv) == '_') ipriv++; if(ipriv == plen) { return PyUnicode.internFromString(ident); } return PyUnicode.internFromString(privateStr.substring(ipriv) + ident); }
public PyCodeObject mod(modType mod)
xia-st/JPython
src/pers/xia/jpython/compiler/Compiler.java
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // }
import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode;
this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') { return PyUnicode.internFromString(ident); } int nlen = ident.length(); int plen = privateStr.length(); if(ident.charAt(nlen - 1) == '_' && ident.charAt(nlen - 2) == '_' || ident.indexOf('.') < 0) { return PyUnicode.internFromString(ident); } int ipriv = 0; while(ipriv < plen && privateStr.charAt(ipriv) == '_') ipriv++; if(ipriv == plen) { return PyUnicode.internFromString(ident); } return PyUnicode.internFromString(privateStr.substring(ipriv) + ident); }
// Path: src/pers/xia/jpython/ast/modType.java // public abstract class modType{ // } // // Path: src/pers/xia/jpython/object/PyCodeObject.java // public class PyCodeObject extends PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyList.java // public class PyList extends PySequence // { // private ArrayList<PyObject> list; // // public PyList(int n) // { // this.list = new ArrayList<PyObject>(n); // } // // public PyList(ArrayList<PyObject> list) // { // this.list = list; // } // // public boolean append(PyObject newitem) // { // // TODO Auto-generated method stub // list.add(newitem); // return true; // } // // public boolean extend(PyObject newitems) // { // PyList items = (PyList)newitems; // for(int i = 0; i < items.getSize(); i++) // { // this.append(items.getItem(i)); // } // return true; // } // // public int getSize() // { // // TODO Auto-generated method stub // return list.size(); // } // // public void setSlice(int ilow, int ihigh, PyObject v) // { // // F complete follow // if(v == null) // { // ArrayList<PyObject> l = new ArrayList<PyObject>(this.list.subList(0, ilow)); // ArrayList<PyObject> l2 = new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize())); // this.list = l; // this.list.addAll(l2); // } // else // { // PyList l = (PyList)v; // PyList l1 = new PyList(new ArrayList<PyObject>(this.list.subList(ihigh, this.getSize()))); // this.list = (ArrayList<PyObject>) this.list.subList(0, ilow); // this.extend(l); // this.extend(l1);; // } // } // // public PyList getSlice(int ilow, int ihigh) // { // ArrayList<PyObject> newList = new ArrayList<PyObject>(this.list.subList(ilow, ihigh)); // return new PyList(newList); // } // // public PyObject getItem(int l) // { // // TODO Auto-generated method stub // return list.get(l); // } // } // // Path: src/pers/xia/jpython/object/PyObject.java // public class PyObject // { // // } // // Path: src/pers/xia/jpython/object/PyUnicode.java // public class PyUnicode extends PyObject // { // String str; // // public PyUnicode(byte[] b, String encode) // { // try // { // this.str = new String(b, encode); // } // catch (UnsupportedEncodingException e) // { // // TODO Auto-generated catch block // e.printStackTrace(); // throw new PyExceptions(ErrorType.SYSTEM_ERROR, // "Can't convert bytes to str implicitly"); // } // } // // public static PyUnicode internFromString(String str) // { // return internFromString(str, false); // } // // public static PyUnicode internFromString(String str, boolean rawmode) // { // return new PyUnicode(str, rawmode); // } // // private PyUnicode(String str, boolean rawmode) // { // this.str = str; // if(!rawmode) // { // // FIXME should use faster and more complete method // this.str.replace("\\n", "\n"); // this.str.replace("\\t", "\t"); // this.str.replace("\\\\", "\\"); // } // } // // private PyUnicode(PyObject obj) // { // // TODO // } // // public static PyUnicode concat(PyObject left, PyObject right) // { // if(!(left instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // left); // } // // return ((PyUnicode) left).concat(right); // } // // public PyUnicode concat(PyObject obj) // { // if(!(obj instanceof PyUnicode)) // { // throw new PyExceptions(ErrorType.SYSTEM_ERROR, "transform error", // obj); // } // // String newStr = this.str + ((PyUnicode) obj).str; // return internFromString(newStr); // // } // // } // Path: src/pers/xia/jpython/compiler/Compiler.java import pers.xia.jpython.ast.modType; import pers.xia.jpython.object.PyCodeObject; import pers.xia.jpython.object.PyList; import pers.xia.jpython.object.PyObject; import pers.xia.jpython.object.PyUnicode; this.nestLevel = 0; this.st = st; } public static PyObject _PyMangLe(String privateStr, String ident) { if(privateStr == null || ident.charAt(0) == '_' || ident.charAt(0) == '_') { return PyUnicode.internFromString(ident); } int nlen = ident.length(); int plen = privateStr.length(); if(ident.charAt(nlen - 1) == '_' && ident.charAt(nlen - 2) == '_' || ident.indexOf('.') < 0) { return PyUnicode.internFromString(ident); } int ipriv = 0; while(ipriv < plen && privateStr.charAt(ipriv) == '_') ipriv++; if(ipriv == plen) { return PyUnicode.internFromString(ident); } return PyUnicode.internFromString(privateStr.substring(ipriv) + ident); }
public PyCodeObject mod(modType mod)
xia-st/JPython
src/pers/xia/jpython/object/PyUnicode.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // }
import java.io.UnsupportedEncodingException; import pers.xia.jpython.object.PyExceptions.ErrorType;
package pers.xia.jpython.object; public class PyUnicode extends PyObject { String str; public PyUnicode(byte[] b, String encode) { try { this.str = new String(b, encode); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace();
// Path: src/pers/xia/jpython/object/PyExceptions.java // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // Path: src/pers/xia/jpython/object/PyUnicode.java import java.io.UnsupportedEncodingException; import pers.xia.jpython.object.PyExceptions.ErrorType; package pers.xia.jpython.object; public class PyUnicode extends PyObject { String str; public PyUnicode(byte[] b, String encode) { try { this.str = new String(b, encode); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace();
throw new PyExceptions(ErrorType.SYSTEM_ERROR,
xia-st/JPython
src/pers/xia/jpython/grammar/pgen/_Grammar.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import pers.xia.jpython.object.PyExceptions;
package pers.xia.jpython.grammar.pgen; class _Grammar { static final int DFAMAXSIZE = 256; static final int LABELMAXSIZE = 512; int ndfas; _DFA[] dfas; int nlabels; _Label[] labels; _DFA start; public _Grammar() { this.ndfas = 0; this.dfas = new _DFA[_Grammar.DFAMAXSIZE]; this.nlabels = 0; this.labels = new _Label[_Grammar.LABELMAXSIZE]; } public _Grammar(int ndfas, _DFA[] dfas, int nlabels, _Label[] labels, _DFA start) { this.ndfas = ndfas; this.dfas = dfas; this.nlabels = nlabels; this.labels = labels; this.start = start; } private boolean addLabel(_Label label) { if(nlabels >= this.labels.length) {
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/grammar/pgen/_Grammar.java import pers.xia.jpython.object.PyExceptions; package pers.xia.jpython.grammar.pgen; class _Grammar { static final int DFAMAXSIZE = 256; static final int LABELMAXSIZE = 512; int ndfas; _DFA[] dfas; int nlabels; _Label[] labels; _DFA start; public _Grammar() { this.ndfas = 0; this.dfas = new _DFA[_Grammar.DFAMAXSIZE]; this.nlabels = 0; this.labels = new _Label[_Grammar.LABELMAXSIZE]; } public _Grammar(int ndfas, _DFA[] dfas, int nlabels, _Label[] labels, _DFA start) { this.ndfas = ndfas; this.dfas = dfas; this.nlabels = nlabels; this.labels = labels; this.start = start; } private boolean addLabel(_Label label) { if(nlabels >= this.labels.length) {
throw new PyExceptions("Over the max size of label");
xia-st/JPython
src/pers/xia/jpython/grammar/DFA.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import pers.xia.jpython.object.PyExceptions;
package pers.xia.jpython.grammar; public class DFA { public DFAType name; //DFA name public int initial; //Initial state, public int nstates; //the number of state public State[] states; //states for DFA public int[] acceptLabel; //保存跳转到当前DFA public DFA(DFAType name, int initial, int nstates, State[] states, int[] acceptLabel) { this.name = name; this.initial = initial; this.nstates = nstates; this.states = states; this.acceptLabel = acceptLabel; } public State getState(int index) { if(index >= nstates || index < 0) {
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/grammar/DFA.java import pers.xia.jpython.object.PyExceptions; package pers.xia.jpython.grammar; public class DFA { public DFAType name; //DFA name public int initial; //Initial state, public int nstates; //the number of state public State[] states; //states for DFA public int[] acceptLabel; //保存跳转到当前DFA public DFA(DFAType name, int initial, int nstates, State[] states, int[] acceptLabel) { this.name = name; this.initial = initial; this.nstates = nstates; this.states = states; this.acceptLabel = acceptLabel; } public State getState(int index) { if(index >= nstates || index < 0) {
throw new PyExceptions("DFA: Out of Index");
xia-st/JPython
src/pers/xia/jpython/object/Py.java
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // }
import pers.xia.jpython.config.Config;
package pers.xia.jpython.object; public final class Py { public final static PyNone None = new PyNone(); public final static PyBoolean True = new PyBoolean(true); public final static PyBoolean False = new PyBoolean(false); public static String encoding = "utf-8";
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // } // Path: src/pers/xia/jpython/object/Py.java import pers.xia.jpython.config.Config; package pers.xia.jpython.object; public final class Py { public final static PyNone None = new PyNone(); public final static PyBoolean True = new PyBoolean(true); public final static PyBoolean False = new PyBoolean(false); public static String encoding = "utf-8";
private final static PyLong[] integerCache = new PyLong[Config.NSMALLPOSINTS
xia-st/JPython
src/pers/xia/jpython/grammar/Grammar.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import pers.xia.jpython.object.PyExceptions;
//将生成的数组放到state里面 state.accel = new int[state.upper - state.lower]; for(int i = 0; i < upper - lower; i++) { state.accel[i] = accel[i + lower]; } } private void fixDFA(DFA dfa) { for(int i = 0; i < dfa.nstates; i++) { fixState(dfa.states[i]); } } public void addAccelerators() { for(int i = 0; i < this.ndfas; i++) { fixDFA(this.dfas[i]); } this.accel = true; } public DFA getDFA(int index) { if(index < 0 || index >= this.ndfas) {
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/grammar/Grammar.java import pers.xia.jpython.object.PyExceptions; //将生成的数组放到state里面 state.accel = new int[state.upper - state.lower]; for(int i = 0; i < upper - lower; i++) { state.accel[i] = accel[i + lower]; } } private void fixDFA(DFA dfa) { for(int i = 0; i < dfa.nstates; i++) { fixState(dfa.states[i]); } } public void addAccelerators() { for(int i = 0; i < this.ndfas; i++) { fixDFA(this.dfas[i]); } this.accel = true; } public DFA getDFA(int index) { if(index < 0 || index >= this.ndfas) {
throw new PyExceptions("Grammar: Out of Index while get DFA");
xia-st/JPython
src/pers/xia/jpython/grammar/pgen/_State.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import pers.xia.jpython.object.PyExceptions;
package pers.xia.jpython.grammar.pgen; /* * 用于Pgen生成数据 */ class _State { static final int MAXSIZE = 100; int narcs; _Arc[] arcs; public _State() { this.narcs = 0; this.arcs = new _Arc[_State.MAXSIZE]; } public boolean addArc(_Arc arc) { if(this.narcs >= this.arcs.length) {
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/grammar/pgen/_State.java import pers.xia.jpython.object.PyExceptions; package pers.xia.jpython.grammar.pgen; /* * 用于Pgen生成数据 */ class _State { static final int MAXSIZE = 100; int narcs; _Arc[] arcs; public _State() { this.narcs = 0; this.arcs = new _Arc[_State.MAXSIZE]; } public boolean addArc(_Arc arc) { if(this.narcs >= this.arcs.length) {
throw new PyExceptions("Over the max size of arcs");
xia-st/JPython
src/pers/xia/jpython/tokenizer/Token.java
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // } // // Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import pers.xia.jpython.config.Config; import pers.xia.jpython.object.PyExceptions;
// ErrorCode done; File file; int tabSize; int indent; int indstack[]; // Stack of indents boolean atbol; int pendin; String prompt; // For interactive prompting String nextPrompt; // For interactive prompting public int lineNo; public int level; // Parentheses nesting level String enc; public String str; String input; int start; int end; boolean contLine; boolean asyncDef; public TokState state; public int lineStart; // 一行的起始位置 public int lineEnd; // 一行的结束位置 public Token() { this.buf = null; this.cur = 0; // this.done = ErrorCode.E_OK; this.file = null; this.indent = 0;
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // } // // Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/tokenizer/Token.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import pers.xia.jpython.config.Config; import pers.xia.jpython.object.PyExceptions; // ErrorCode done; File file; int tabSize; int indent; int indstack[]; // Stack of indents boolean atbol; int pendin; String prompt; // For interactive prompting String nextPrompt; // For interactive prompting public int lineNo; public int level; // Parentheses nesting level String enc; public String str; String input; int start; int end; boolean contLine; boolean asyncDef; public TokState state; public int lineStart; // 一行的起始位置 public int lineEnd; // 一行的结束位置 public Token() { this.buf = null; this.cur = 0; // this.done = ErrorCode.E_OK; this.file = null; this.indent = 0;
this.tabSize = Config.TABSIZE;
xia-st/JPython
src/pers/xia/jpython/tokenizer/Token.java
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // } // // Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import pers.xia.jpython.config.Config; import pers.xia.jpython.object.PyExceptions;
this.input = null; this.start = this.end = 0; this.contLine = false; this.asyncDef = false; this.lineStart = lineEnd = 0; } public Token(String buf) { this(); this.buf = buf; } public Token(File file) { this(); this.file = file; try { FileInputStream in = new FileInputStream(file); byte[] data = new byte[in.available()]; in.read(data); in.close(); this.buf = new String(data); this.buf = this.buf.replaceAll("\r\n", "\n").replace('\r', '\n'); } catch (IOException e) { e.printStackTrace();
// Path: src/pers/xia/jpython/config/Config.java // public class Config // { // public static final int MAXINDENT = 100; // public static final int TABSIZE = 8; // public static final int BUFSIZ = 8192; // public static final int NSMALLPOSINTS = 105; // public static final int NSMALLNEGINTS = -5; // } // // Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/tokenizer/Token.java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import pers.xia.jpython.config.Config; import pers.xia.jpython.object.PyExceptions; this.input = null; this.start = this.end = 0; this.contLine = false; this.asyncDef = false; this.lineStart = lineEnd = 0; } public Token(String buf) { this(); this.buf = buf; } public Token(File file) { this(); this.file = file; try { FileInputStream in = new FileInputStream(file); byte[] data = new byte[in.available()]; in.read(data); in.close(); this.buf = new String(data); this.buf = this.buf.replaceAll("\r\n", "\n").replace('\r', '\n'); } catch (IOException e) { e.printStackTrace();
throw new PyExceptions("File not found");
xia-st/JPython
src/pers/xia/jpython/grammar/pgen/_Label.java
// Path: src/pers/xia/jpython/tokenizer/TokState.java // public enum TokState // { // ENDMARKER, // NAME, // NUMBER, // STRING, // NEWLINE, // INDENT, // DEDENT, // LPAR, // ( // RPAR, // ) // LSQB, // [ // RSQB, // ] // COLON, // : // COMMA, // , // SEMI, // ; // PLUS, // + // MINUS, // - // STAR, // * // SLASH, // / // VBAR, // | // AMPER, // & // LESS, // < // GREATER, // > // EQUAL, // = // DOT, // . // PERCENT, // % // BACKQUOTE, // LBRACE, // { // RBRACE, // } // EQEQUAL, // == // NOTEQUAL, // != // LESSEQUAL, // <= // GREATEREQUAL, // >= // TILDE, // ~ // CIRCUMFLEX, // ^ // LEFTSHIFT, // << // RIGHTSHIFT, // >> // DOUBLESTAR, // ** // PLUSEQUAL, // += // MINEQUAL, // -= // STAREQUAL, // *= // SLASHEQUAL, // /= // PERCENTEQUAL, // %= // AMPEREQUAL, // &= // VBAREQUAL, // |= // CIRCUMFLEXEQUAL, // ^= // LEFTSHIFTEQUAL, // <<= // RIGHTSHIFTEQUAL, // >>= // DOUBLESTAREQUAL, // **= // DOUBLESLASH, // \\ // DOUBLESLASHEQUAL, // \\= // AT, // @ // ATEQUAL, // @= // RARROW, // -> // ELLIPSIS, // ... // OP, // AWAIT, // await // ASYNC, // async // ERRORTOKEN, // N_TOKENS, // }
import pers.xia.jpython.tokenizer.TokState;
package pers.xia.jpython.grammar.pgen; /* * 用于Pgen生成数据 * Label类的替代。由于DFAName和DFA一开始没有定义,所以无法直接使用 * 原来的Lable,故后面的操作会用这个_Label来代替。 */ class _Label { String nextDfa; //下一个DFA对象
// Path: src/pers/xia/jpython/tokenizer/TokState.java // public enum TokState // { // ENDMARKER, // NAME, // NUMBER, // STRING, // NEWLINE, // INDENT, // DEDENT, // LPAR, // ( // RPAR, // ) // LSQB, // [ // RSQB, // ] // COLON, // : // COMMA, // , // SEMI, // ; // PLUS, // + // MINUS, // - // STAR, // * // SLASH, // / // VBAR, // | // AMPER, // & // LESS, // < // GREATER, // > // EQUAL, // = // DOT, // . // PERCENT, // % // BACKQUOTE, // LBRACE, // { // RBRACE, // } // EQEQUAL, // == // NOTEQUAL, // != // LESSEQUAL, // <= // GREATEREQUAL, // >= // TILDE, // ~ // CIRCUMFLEX, // ^ // LEFTSHIFT, // << // RIGHTSHIFT, // >> // DOUBLESTAR, // ** // PLUSEQUAL, // += // MINEQUAL, // -= // STAREQUAL, // *= // SLASHEQUAL, // /= // PERCENTEQUAL, // %= // AMPEREQUAL, // &= // VBAREQUAL, // |= // CIRCUMFLEXEQUAL, // ^= // LEFTSHIFTEQUAL, // <<= // RIGHTSHIFTEQUAL, // >>= // DOUBLESTAREQUAL, // **= // DOUBLESLASH, // \\ // DOUBLESLASHEQUAL, // \\= // AT, // @ // ATEQUAL, // @= // RARROW, // -> // ELLIPSIS, // ... // OP, // AWAIT, // await // ASYNC, // async // ERRORTOKEN, // N_TOKENS, // } // Path: src/pers/xia/jpython/grammar/pgen/_Label.java import pers.xia.jpython.tokenizer.TokState; package pers.xia.jpython.grammar.pgen; /* * 用于Pgen生成数据 * Label类的替代。由于DFAName和DFA一开始没有定义,所以无法直接使用 * 原来的Lable,故后面的操作会用这个_Label来代替。 */ class _Label { String nextDfa; //下一个DFA对象
TokState tokState;
xia-st/JPython
src/pers/xia/jpython/tokenizer/Tokenizer.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import java.io.File; import pers.xia.jpython.object.PyExceptions;
public Tokenizer() { } public Tokenizer(File file) { this(); this.tok = new Token(file); } public Token nextToken() { this.tok.get(); this.tok.str = this.tok.buf.substring(this.tok.start, this.tok.end); return tok; } public static void main(String[] args) { File file = new File("./test/test.py"); try { Tokenizer tokenizer = new Tokenizer(file); Token tok = tokenizer.nextToken(); while (tok.state != TokState.ENDMARKER) { System.out.println(tok); tok = tokenizer.nextToken(); } }
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/tokenizer/Tokenizer.java import java.io.File; import pers.xia.jpython.object.PyExceptions; public Tokenizer() { } public Tokenizer(File file) { this(); this.tok = new Token(file); } public Token nextToken() { this.tok.get(); this.tok.str = this.tok.buf.substring(this.tok.start, this.tok.end); return tok; } public static void main(String[] args) { File file = new File("./test/test.py"); try { Tokenizer tokenizer = new Tokenizer(file); Token tok = tokenizer.nextToken(); while (tok.state != TokState.ENDMARKER) { System.out.println(tok); tok = tokenizer.nextToken(); } }
catch (PyExceptions e)
xia-st/JPython
src/pers/xia/jpython/grammar/pgen/_DFA.java
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // }
import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import pers.xia.jpython.object.PyExceptions;
package pers.xia.jpython.grammar.pgen; class _DFA { String name; //DFA name _State initial; //Initial state, int nstates; //the number of state // 这里其实用List操作起来会方便很多。。。一开始没设计好后面也不好修改,还好这里对最终代码没影响 _State[] states; //states for DFA Map<_Label, _DFA> jumpedDFAs; //当跳转到本DFA时根据lebel判断实际需要跳转的DFA static final int MAXSIZE = 256; public _DFA(String name) { if(name == null) {
// Path: src/pers/xia/jpython/object/PyExceptions.java // public class PyExceptions extends RuntimeException // { // private static final long serialVersionUID = -5566345378602605958L; // // public static enum ErrorType // { // AST_ERROR, // PARSER_ERROR, // SYSTEM_ERROR, // SYMTABLE_ERROR, // SYNTAX_ERROR // } // // public Stack<String> map = new Stack<String>(); // public Token tok; // // public PyExceptions() // { // super(); // } // // public PyExceptions(String msg) // { // super(msg); // map.push(msg); // } // // public PyExceptions(String msg, Throwable cause) // { // super(msg, cause); // } // // public PyExceptions(ErrorType type, String msg) // { // this(type, msg, 0, 0); // } // // public PyExceptions(ErrorType type, String msg, int lineno, int colOffset) // { // super(msg); // msg += "\nlineno: " + lineno + ", colOffset: " + colOffset; // map.push(msg); // } // // public PyExceptions(String msg, Node n) // { // this(null, msg, n); // } // // public PyExceptions(ErrorType type, String msg, Node n) // { // super(msg); // msg = msg + "\n" + "line: " + n.lineNo + " colOffset: " + n.colOffset // + "\n" + n.dfaType + " " + n.str; // map.push(msg); // } // // public PyExceptions(String msg, Token tok) // { // super(msg); // msg = "line: " + tok.lineNo + "\n" // + tok.buf.substring(tok.lineStart, tok.lineEnd) + "\n" + msg; // map.push(msg); // this.tok = tok; // } // // public PyExceptions(ErrorType type, String msg, PyObject obj) // { // super(msg); // map.push(msg); // } // // public String toString() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // return msg; // } // // public void printStackTrace() // { // String msg = ""; // while (!map.empty()) // { // msg += map.pop() + "\n"; // } // if(msg.length() > 0) // { // System.err.println(msg); // } // else // { // super.printStackTrace(); // } // } // } // Path: src/pers/xia/jpython/grammar/pgen/_DFA.java import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import pers.xia.jpython.object.PyExceptions; package pers.xia.jpython.grammar.pgen; class _DFA { String name; //DFA name _State initial; //Initial state, int nstates; //the number of state // 这里其实用List操作起来会方便很多。。。一开始没设计好后面也不好修改,还好这里对最终代码没影响 _State[] states; //states for DFA Map<_Label, _DFA> jumpedDFAs; //当跳转到本DFA时根据lebel判断实际需要跳转的DFA static final int MAXSIZE = 256; public _DFA(String name) { if(name == null) {
throw new PyExceptions("_DFA must have name");
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/preferences/SharedPreferencesManager.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/encryption/StringEncryption.java // public interface StringEncryption { // String encrypt(String str); // String decrypt(String str); // }
import android.content.Context; import android.content.SharedPreferences; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.encryption.StringEncryption; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.preferences; /** * General shared preferences * Created by cirilla on 7/16/15. */ public class SharedPreferencesManager { protected SharedPreferences sharedPreferences; protected SharedPreferences.Editor editor;
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/encryption/StringEncryption.java // public interface StringEncryption { // String encrypt(String str); // String decrypt(String str); // } // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/preferences/SharedPreferencesManager.java import android.content.Context; import android.content.SharedPreferences; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.encryption.StringEncryption; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.preferences; /** * General shared preferences * Created by cirilla on 7/16/15. */ public class SharedPreferencesManager { protected SharedPreferences sharedPreferences; protected SharedPreferences.Editor editor;
protected StringEncryption stringEncryption;
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/ProgressRequestBody.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // }
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.internal.Util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import okio.BufferedSink; import okio.Okio; import okio.Source;
package com.ibm.mobilefirstplatform.clientsdk.android.core.internal; /** * @exclude * * Internal custom RequestBody that monitors the progress of Request or BaseRequest uploads */ public class ProgressRequestBody extends RequestBody { // The size of buffer segments used by Okio (2 KiB) protected static final int SEGMENT_SIZE = 2048; private Object payload;
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // } // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/ProgressRequestBody.java import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.Logger; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.internal.Util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import okio.BufferedSink; import okio.Okio; import okio.Source; package com.ibm.mobilefirstplatform.clientsdk.android.core.internal; /** * @exclude * * Internal custom RequestBody that monitors the progress of Request or BaseRequest uploads */ public class ProgressRequestBody extends RequestBody { // The size of buffer segments used by Okio (2 KiB) protected static final int SEGMENT_SIZE = 2048; private Object payload;
private ProgressListener listener;
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/RequestTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // }
import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; public class RequestTests { private CountDownLatch latch = null; private void setupBMSClient() {
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // } // Path: lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/RequestTests.java import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; public class RequestTests { private CountDownLatch latch = null; private void setupBMSClient() {
AuthorizationManager mockAuthorizationManager = mock(DummyAuthorizationManager.class);
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/RequestTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // }
import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; public class RequestTests { private CountDownLatch latch = null; private void setupBMSClient() {
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // } // Path: lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/RequestTests.java import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager; import okhttp3.Callback; import okhttp3.Headers; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* Copyright 2015 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; public class RequestTests { private CountDownLatch latch = null; private void setupBMSClient() {
AuthorizationManager mockAuthorizationManager = mock(DummyAuthorizationManager.class);
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/BMSClient.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/AbstractClient.java // public abstract class AbstractClient { // // protected static final CookieManager cookieManager = new CookieManager(); // // protected AuthorizationManager authorizationManager = null; // private int defaultTimeout = 20000; // // /** // * Gets active authorization manager. // * // * @return AuthorizationManager // */ // public AuthorizationManager getAuthorizationManager(){ // return authorizationManager; // } // // /** // * Sets active authorization manager. // * // * @param authorizationManager authorization manager. // */ // public void setAuthorizationManager(AuthorizationManager authorizationManager){ // this.authorizationManager = authorizationManager; // } // // /** // * @return default timeout, in milliseconds // */ // public int getDefaultTimeout() { // return defaultTimeout; // } // // /** // * Sets the default timeout. The SDK's default value is 20000 milliseconds. // * // * @param timeout specifies the new timeout, in milliseconds // */ // public void setDefaultTimeout(int timeout) { // defaultTimeout = timeout; // } // // /** // * @return cookieManager cookie manager // */ // public CookieManager getCookieManager(){ // return cookieManager; // } // // // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // }
import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.core.internal.AbstractClient; import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import java.net.CookiePolicy; import java.net.MalformedURLException;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; /** * The BMSClient is a singleton that serves as the entry point to MobileFirst. */ public class BMSClient extends AbstractClient { public final static String REGION_US_SOUTH = ".ng.bluemix.net"; public final static String REGION_UK = ".eu-gb.bluemix.net"; public final static String REGION_SYDNEY = ".au-syd.bluemix.net"; public final static String REGION_GERMANY = ".eu-de.bluemix.net"; public final static String REGION_US_EAST = ".us-east.bluemix.net"; public final static String REGION_TOKYO = ".jp-tok.bluemix.net"; public final static String REGION_JP_OSA = ".jp-osa.bluemix.net"; public final static String HTTP_SCHEME = "http"; public final static String HTTPS_SCHEME = "https"; private String backendRoute = null; private String backendGUID = null; private String bluemixRegionSuffix = null; private String defaultProtocol = HTTPS_SCHEME; protected static AbstractClient instance = null; /** * Should be called to obtain the instance of BMSClient. * @return the instance of BMSClient. */ public static BMSClient getInstance() { if (instance == null) { instance = new BMSClient(); } return (BMSClient)instance; } private BMSClient() { } /** * @deprecated As of release 2.2.0, replaced by {@link #initialize(Context, String)} * Initializes the SDK with supplied parameters * <p> * This method should be called before you send the first request * </p> * @param context Android application context * @param bluemixAppRoute Specifies the base URL for the authorization server * @param bluemixAppGUID Specifies the GUID of the application * @param bluemixRegion Specifies the Bluemix deployment to use. Use values in BMSClient.REGION* static props * @throws MalformedURLException {@code backendRoute} could not be parsed as a URL. */ public void initialize(Context context, String bluemixAppRoute, String bluemixAppGUID, String bluemixRegion) throws MalformedURLException{ this.backendGUID = bluemixAppGUID; this.backendRoute = bluemixAppRoute; this.bluemixRegionSuffix = bluemixRegion; if (null == this.authorizationManager) {
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/AbstractClient.java // public abstract class AbstractClient { // // protected static final CookieManager cookieManager = new CookieManager(); // // protected AuthorizationManager authorizationManager = null; // private int defaultTimeout = 20000; // // /** // * Gets active authorization manager. // * // * @return AuthorizationManager // */ // public AuthorizationManager getAuthorizationManager(){ // return authorizationManager; // } // // /** // * Sets active authorization manager. // * // * @param authorizationManager authorization manager. // */ // public void setAuthorizationManager(AuthorizationManager authorizationManager){ // this.authorizationManager = authorizationManager; // } // // /** // * @return default timeout, in milliseconds // */ // public int getDefaultTimeout() { // return defaultTimeout; // } // // /** // * Sets the default timeout. The SDK's default value is 20000 milliseconds. // * // * @param timeout specifies the new timeout, in milliseconds // */ // public void setDefaultTimeout(int timeout) { // defaultTimeout = timeout; // } // // /** // * @return cookieManager cookie manager // */ // public CookieManager getCookieManager(){ // return cookieManager; // } // // // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/DummyAuthorizationManager.java // public class DummyAuthorizationManager implements AuthorizationManager { // // private final DeviceIdentity deviceIdentity; // private final AppIdentity appIdentity; // // public DummyAuthorizationManager(Context context){ // deviceIdentity = new BaseDeviceIdentity(context); // appIdentity = new BaseAppIdentity(context); // } // // @Override // public boolean isAuthorizationRequired (int statusCode, Map<String, List<String>> headers) { // return false; // } // // @Override // public boolean isAuthorizationRequired (HttpURLConnection urlConnection) throws IOException { // return false; // } // // @Override // public void obtainAuthorization (Context context, ResponseListener listener, Object... params) { // listener.onSuccess(null); // } // // @Override // public String getCachedAuthorizationHeader () { // return null; // } // // @Override // public void clearAuthorizationData () { // // } // // @Override // public UserIdentity getUserIdentity () { // return null; // } // // @Override // public DeviceIdentity getDeviceIdentity () { // return deviceIdentity; // } // // @Override // public AppIdentity getAppIdentity () { // return appIdentity; // } // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // // @Override // public void logout(Context context, ResponseListener listener){} // } // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/BMSClient.java import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.core.internal.AbstractClient; import com.ibm.mobilefirstplatform.clientsdk.android.security.DummyAuthorizationManager; import java.net.CookiePolicy; import java.net.MalformedURLException; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.api; /** * The BMSClient is a singleton that serves as the entry point to MobileFirst. */ public class BMSClient extends AbstractClient { public final static String REGION_US_SOUTH = ".ng.bluemix.net"; public final static String REGION_UK = ".eu-gb.bluemix.net"; public final static String REGION_SYDNEY = ".au-syd.bluemix.net"; public final static String REGION_GERMANY = ".eu-de.bluemix.net"; public final static String REGION_US_EAST = ".us-east.bluemix.net"; public final static String REGION_TOKYO = ".jp-tok.bluemix.net"; public final static String REGION_JP_OSA = ".jp-osa.bluemix.net"; public final static String HTTP_SCHEME = "http"; public final static String HTTPS_SCHEME = "https"; private String backendRoute = null; private String backendGUID = null; private String bluemixRegionSuffix = null; private String defaultProtocol = HTTPS_SCHEME; protected static AbstractClient instance = null; /** * Should be called to obtain the instance of BMSClient. * @return the instance of BMSClient. */ public static BMSClient getInstance() { if (instance == null) { instance = new BMSClient(); } return (BMSClient)instance; } private BMSClient() { } /** * @deprecated As of release 2.2.0, replaced by {@link #initialize(Context, String)} * Initializes the SDK with supplied parameters * <p> * This method should be called before you send the first request * </p> * @param context Android application context * @param bluemixAppRoute Specifies the base URL for the authorization server * @param bluemixAppGUID Specifies the GUID of the application * @param bluemixRegion Specifies the Bluemix deployment to use. Use values in BMSClient.REGION* static props * @throws MalformedURLException {@code backendRoute} could not be parsed as a URL. */ public void initialize(Context context, String bluemixAppRoute, String bluemixAppGUID, String bluemixRegion) throws MalformedURLException{ this.backendGUID = bluemixAppGUID; this.backendRoute = bluemixAppRoute; this.bluemixRegionSuffix = bluemixRegion; if (null == this.authorizationManager) {
this.authorizationManager = new DummyAuthorizationManager(context);
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/AbstractClient.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // }
import java.net.CookieManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.internal; public abstract class AbstractClient { protected static final CookieManager cookieManager = new CookieManager();
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java // public interface AuthorizationManager { // // String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; // // /** // * @return Whether authorization is required // * @param headers http response headers // * @param statusCode http response status code // */ // boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); // // /** // * @return Whether authorization is required // * @param urlConnection HttpURLConnection representing http response // */ // boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; // // /** // * Starts authorization process // * @param context Context for obtaining authorization. Should be Activity if authorization in interactive // */ // void obtainAuthorization (Context context, ResponseListener listener, Object... params); // // /** // * Returns previously obtained authorization header. The value will be added to all outgoing requests // * as Authorization header. // * @return cached authorization header // */ // String getCachedAuthorizationHeader(); // // /** // * Clears authorization data // */ // void clearAuthorizationData(); // // /** // * @return UserIdentity object // */ // UserIdentity getUserIdentity(); // // /** // * @return DeviceIdentity object // */ // DeviceIdentity getDeviceIdentity(); // // /** // * @return AppIdentity object // */ // AppIdentity getAppIdentity(); // // /** // * logs out user // * @param context Android Activity that will handle the authorization (like facebook or google) // * @param listener Response listener // */ // void logout(Context context, ResponseListener listener); // // } // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/AbstractClient.java import java.net.CookieManager; import com.ibm.mobilefirstplatform.clientsdk.android.security.api.AuthorizationManager; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.internal; public abstract class AbstractClient { protected static final CookieManager cookieManager = new CookieManager();
protected AuthorizationManager authorizationManager = null;
ibm-bluemix-mobile-services/bms-clientsdk-android-core
app/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/app/MyResponseListener.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/Response.java // public interface Response { // // /** // * Returns the URL that the request was made to. // * // * @return The URL of the request. // */ // String getRequestURL(); // // /** // * This method gets the HTTP status of the response. // * // * @return The HTTP status of the response. Will be 0 when there was no response. // */ // int getStatus(); // // /** // * This method parses the response body as a String. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a String. Empty string if there is no body. // */ // String getResponseText(); // // /** // * This method parses the response body as a JSONObject. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a JSONObject. // */ // JSONObject getResponseJSON(); // // /** // * This method gets the bytes of the response body. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return the bytes of the response body. Will be null if there is no body. // */ // byte[] getResponseBytes(); // // /** // * This method gets the response body as an input stream. // * // * <p> // * <b>Important: </b>This method may not be used for requests made with any of the {@link Request} download() methods, // * since the stream will already be closed. Use {@link Response#getResponseBytes()} instead. // * </p> // * // * @return The input stream representing the response body. Will be null if there is no body. // */ // InputStream getResponseByteStream(); // // /** // * This method gets the Content-Length of the response body. // * // * @return The content length of the response. // */ // long getContentLength(); // // /** // * Get the HTTP headers from the response. // * // * @return A map with all the headers, and the corresponding values for each one. // */ // Map<String, List<String>> getHeaders(); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // }
import android.util.Log; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import org.json.JSONObject;
/* *     Copyright 2017 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.app; public class MyResponseListener implements ResponseListener { @Override
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/Response.java // public interface Response { // // /** // * Returns the URL that the request was made to. // * // * @return The URL of the request. // */ // String getRequestURL(); // // /** // * This method gets the HTTP status of the response. // * // * @return The HTTP status of the response. Will be 0 when there was no response. // */ // int getStatus(); // // /** // * This method parses the response body as a String. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a String. Empty string if there is no body. // */ // String getResponseText(); // // /** // * This method parses the response body as a JSONObject. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a JSONObject. // */ // JSONObject getResponseJSON(); // // /** // * This method gets the bytes of the response body. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return the bytes of the response body. Will be null if there is no body. // */ // byte[] getResponseBytes(); // // /** // * This method gets the response body as an input stream. // * // * <p> // * <b>Important: </b>This method may not be used for requests made with any of the {@link Request} download() methods, // * since the stream will already be closed. Use {@link Response#getResponseBytes()} instead. // * </p> // * // * @return The input stream representing the response body. Will be null if there is no body. // */ // InputStream getResponseByteStream(); // // /** // * This method gets the Content-Length of the response body. // * // * @return The content length of the response. // */ // long getContentLength(); // // /** // * Get the HTTP headers from the response. // * // * @return A map with all the headers, and the corresponding values for each one. // */ // Map<String, List<String>> getHeaders(); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // } // Path: app/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/app/MyResponseListener.java import android.util.Log; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import org.json.JSONObject; /* *     Copyright 2017 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.app; public class MyResponseListener implements ResponseListener { @Override
public void onSuccess(Response response) {
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/BaseRequestTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/Response.java // public interface Response { // // /** // * Returns the URL that the request was made to. // * // * @return The URL of the request. // */ // String getRequestURL(); // // /** // * This method gets the HTTP status of the response. // * // * @return The HTTP status of the response. Will be 0 when there was no response. // */ // int getStatus(); // // /** // * This method parses the response body as a String. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a String. Empty string if there is no body. // */ // String getResponseText(); // // /** // * This method parses the response body as a JSONObject. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a JSONObject. // */ // JSONObject getResponseJSON(); // // /** // * This method gets the bytes of the response body. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return the bytes of the response body. Will be null if there is no body. // */ // byte[] getResponseBytes(); // // /** // * This method gets the response body as an input stream. // * // * <p> // * <b>Important: </b>This method may not be used for requests made with any of the {@link Request} download() methods, // * since the stream will already be closed. Use {@link Response#getResponseBytes()} instead. // * </p> // * // * @return The input stream representing the response body. Will be null if there is no body. // */ // InputStream getResponseByteStream(); // // /** // * This method gets the Content-Length of the response body. // * // * @return The content length of the response. // */ // long getContentLength(); // // /** // * Get the HTTP headers from the response. // * // * @return A map with all the headers, and the corresponding values for each one. // */ // Map<String, List<String>> getHeaders(); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // }
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import okhttp3.Callback; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
request.upload(requestBodyFile, progressListener, expectedResponseListener); assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); } @Test public void testUploadFileWithNullListeners() throws Exception { latch = new CountDownLatch(1); final File requestBodyFile = mock(File.class); BaseRequest request = new BaseRequest("", "") { @Override protected void sendRequest(final ProgressListener progressListener, final ResponseListener responseListener, final RequestBody requestBody) { assertNull(progressListener); assertNull(responseListener); assertNotNull(requestBody); latch.countDown(); } }; request.upload(requestBodyFile, null, null); assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); } @Test public void testGetCallbackTriggersProgressListener() throws Exception { latch = new CountDownLatch(1);
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/Response.java // public interface Response { // // /** // * Returns the URL that the request was made to. // * // * @return The URL of the request. // */ // String getRequestURL(); // // /** // * This method gets the HTTP status of the response. // * // * @return The HTTP status of the response. Will be 0 when there was no response. // */ // int getStatus(); // // /** // * This method parses the response body as a String. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a String. Empty string if there is no body. // */ // String getResponseText(); // // /** // * This method parses the response body as a JSONObject. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return The body of the response as a JSONObject. // */ // JSONObject getResponseJSON(); // // /** // * This method gets the bytes of the response body. // * If this method is called, then subsequent calls to {@link #getResponseByteStream()} or {@link #getResponseBytes()} // * will return null unless the {@link Request} was made using a <code>download()</code> method. // * // * @return the bytes of the response body. Will be null if there is no body. // */ // byte[] getResponseBytes(); // // /** // * This method gets the response body as an input stream. // * // * <p> // * <b>Important: </b>This method may not be used for requests made with any of the {@link Request} download() methods, // * since the stream will already be closed. Use {@link Response#getResponseBytes()} instead. // * </p> // * // * @return The input stream representing the response body. Will be null if there is no body. // */ // InputStream getResponseByteStream(); // // /** // * This method gets the Content-Length of the response body. // * // * @return The content length of the response. // */ // long getContentLength(); // // /** // * Get the HTTP headers from the response. // * // * @return A map with all the headers, and the corresponding values for each one. // */ // Map<String, List<String>> getHeaders(); // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // } // Path: lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/BaseRequestTests.java import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import okhttp3.Callback; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.ResponseBody; import org.json.JSONObject; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; request.upload(requestBodyFile, progressListener, expectedResponseListener); assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); } @Test public void testUploadFileWithNullListeners() throws Exception { latch = new CountDownLatch(1); final File requestBodyFile = mock(File.class); BaseRequest request = new BaseRequest("", "") { @Override protected void sendRequest(final ProgressListener progressListener, final ResponseListener responseListener, final RequestBody requestBody) { assertNull(progressListener); assertNull(responseListener); assertNotNull(requestBody); latch.countDown(); } }; request.upload(requestBodyFile, null, null); assertTrue(latch.await(100, TimeUnit.MILLISECONDS)); } @Test public void testGetCallbackTriggersProgressListener() throws Exception { latch = new CountDownLatch(1);
okhttp3.Response mockedOkHttpResponse = mock(okhttp3.Response.class);
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/ProgressRequestBodyTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // }
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import okhttp3.MediaType; import okhttp3.RequestBody; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okio.Buffer; import okio.BufferedSink; import okio.Okio; import okio.Source; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
} @Test public void testContentType() { MediaType expectedContentType = MediaType.parse("text/plain; charset=utf-8"); RequestBody mockedRequestBody = mock(RequestBody.class); when(mockedRequestBody.contentType()).thenReturn(expectedContentType); ProgressRequestBody progressBody = new ProgressRequestBody(null, mockedRequestBody, null); assertEquals(expectedContentType, progressBody.contentType()); } @Test public void testWriteTo() throws Exception { final byte[] testPayload = new byte[100000]; new Random().nextBytes(testPayload); RequestBody mockedRequestBody = mock(RequestBody.class); try { when(mockedRequestBody.contentLength()).thenReturn((long)testPayload.length); } catch (IOException e) { fail("Failed to get the length of the test payload"); } int numberOfOnProgressCalls = testPayload.length / ProgressRequestBody.SEGMENT_SIZE + 1; latch = new CountDownLatch(numberOfOnProgressCalls);
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ProgressListener.java // public interface ProgressListener { // // /** // * This method will be called repeatedly as a download or upload is in progress. // * Specifically, this method will be called once for every 2 KiB downloaded or uploaded. // * // * If the ProgressListener is used for downloading and the response does not include a // * "Content-Length" header, the totalBytesExpected parameter will be 0. // * // * @param bytesSoFar The number of bytes sent or received so far // * @param totalBytesExpected The total number of bytes expected to be sent or received // */ // void onProgress(long bytesSoFar, long totalBytesExpected); // } // Path: lib/src/test/java/com/ibm/mobilefirstplatform/clientsdk/android/core/internal/ProgressRequestBodyTests.java import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ProgressListener; import okhttp3.MediaType; import okhttp3.RequestBody; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import okio.Buffer; import okio.BufferedSink; import okio.Okio; import okio.Source; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; } @Test public void testContentType() { MediaType expectedContentType = MediaType.parse("text/plain; charset=utf-8"); RequestBody mockedRequestBody = mock(RequestBody.class); when(mockedRequestBody.contentType()).thenReturn(expectedContentType); ProgressRequestBody progressBody = new ProgressRequestBody(null, mockedRequestBody, null); assertEquals(expectedContentType, progressBody.contentType()); } @Test public void testWriteTo() throws Exception { final byte[] testPayload = new byte[100000]; new Random().nextBytes(testPayload); RequestBody mockedRequestBody = mock(RequestBody.class); try { when(mockedRequestBody.contentLength()).thenReturn((long)testPayload.length); } catch (IOException e) { fail("Failed to get the length of the test payload"); } int numberOfOnProgressCalls = testPayload.length / ProgressRequestBody.SEGMENT_SIZE + 1; latch = new CountDownLatch(numberOfOnProgressCalls);
ProgressListener listener = new ProgressListener() {
ibm-bluemix-mobile-services/bms-clientsdk-android-core
app/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/app/MyChallengeHandler.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/AuthenticationContext.java // public interface AuthenticationContext { // /** // * Submits authentication challenge response. // * @param answer JSON with challenge response. // */ // void submitAuthenticationChallengeAnswer(JSONObject answer); // // /** // * Informs about authentication success. // */ // void submitAuthenticationSuccess (); // // /** // * Informs about authentication failure. This function must be called from a custom challenge // * handler when the authorization request should be canceled for any reason (for example, // * when user clicks 'cancel' on login dialog). The original {@link BaseRequest} // * will be failed. // * @param info Extended information about the failure. It will be passed to {@link com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener#onFailure(Response, Throwable, JSONObject)} of // * the resource request as 'extendedInfo' object. // */ // void submitAuthenticationFailure (JSONObject info); // // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/AuthenticationListener.java // public interface AuthenticationListener { // /** // * Called when authentication challenge was received. The implementor should handle the challenge and call // * {@link com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationContext#submitAuthenticationChallengeAnswer(JSONObject)} // * with authentication challenge answer. // * @param authContext Authentication context the answer should be sent to // * @param challenge Information about authentication challenge. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // */ // void onAuthenticationChallengeReceived(AuthenticationContext authContext, JSONObject challenge, Context context); // // /** // * Called when authentication succeeded. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // * @param info Extended data describing the authentication success. // */ // void onAuthenticationSuccess(Context context, JSONObject info); // // /** // * Called when authentication fails. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // * @param info Extended data describing authentication failure. // */ // void onAuthenticationFailure(Context context, JSONObject info); // // }
import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationContext; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationListener; import org.json.JSONException; import org.json.JSONObject;
/* *     Copyright 2017 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.app; public class MyChallengeHandler implements AuthenticationListener { @Override
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/AuthenticationContext.java // public interface AuthenticationContext { // /** // * Submits authentication challenge response. // * @param answer JSON with challenge response. // */ // void submitAuthenticationChallengeAnswer(JSONObject answer); // // /** // * Informs about authentication success. // */ // void submitAuthenticationSuccess (); // // /** // * Informs about authentication failure. This function must be called from a custom challenge // * handler when the authorization request should be canceled for any reason (for example, // * when user clicks 'cancel' on login dialog). The original {@link BaseRequest} // * will be failed. // * @param info Extended information about the failure. It will be passed to {@link com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener#onFailure(Response, Throwable, JSONObject)} of // * the resource request as 'extendedInfo' object. // */ // void submitAuthenticationFailure (JSONObject info); // // } // // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/api/AuthenticationListener.java // public interface AuthenticationListener { // /** // * Called when authentication challenge was received. The implementor should handle the challenge and call // * {@link com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationContext#submitAuthenticationChallengeAnswer(JSONObject)} // * with authentication challenge answer. // * @param authContext Authentication context the answer should be sent to // * @param challenge Information about authentication challenge. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // */ // void onAuthenticationChallengeReceived(AuthenticationContext authContext, JSONObject challenge, Context context); // // /** // * Called when authentication succeeded. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // * @param info Extended data describing the authentication success. // */ // void onAuthenticationSuccess(Context context, JSONObject info); // // /** // * Called when authentication fails. // * @param context A {@link Context} object that was passed to // * {@link Request#send(Context, ResponseListener)}, which triggered the // * authentication challenge. // * @param info Extended data describing authentication failure. // */ // void onAuthenticationFailure(Context context, JSONObject info); // // } // Path: app/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/app/MyChallengeHandler.java import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationContext; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.api.AuthenticationListener; import org.json.JSONException; import org.json.JSONObject; /* *     Copyright 2017 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.core.app; public class MyChallengeHandler implements AuthenticationListener { @Override
public void onAuthenticationChallengeReceived(AuthenticationContext authContext, JSONObject challenge, Context context) {
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // }
import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import java.io.IOException; import java.net.HttpURLConnection; import java.util.List; import java.util.Map;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.api; public interface AuthorizationManager { String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; /** * @return Whether authorization is required * @param headers http response headers * @param statusCode http response status code */ boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); /** * @return Whether authorization is required * @param urlConnection HttpURLConnection representing http response */ boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; /** * Starts authorization process * @param context Context for obtaining authorization. Should be Activity if authorization in interactive */
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/core/api/ResponseListener.java // public interface ResponseListener { // // /** // * This method will be called only when a response from the server has been received with a status // * in the 200 range. // * @param response the server response // */ // void onSuccess(Response response); // // /** // * This method will be called in the following cases: // * <ul> // * <li>There is no response from the server.</li> // * <li>The status from the server response is in the 400 or 500 ranges.</li> // * <li>There is an operational failure such as: authentication failure, data validation failure, or custom failure.</li> // * </ul> // * @param response Contains detail regarding why the Http request failed. May be null if the request did not reach the server // * @param t Exception that could have caused the request to fail. null if no Exception thrown. // * @param extendedInfo Contains details regarding operational failure. null if no operational failure occurred. // */ // void onFailure(Response response, Throwable t, JSONObject extendedInfo); // // } // Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/api/AuthorizationManager.java import android.content.Context; import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener; import java.io.IOException; import java.net.HttpURLConnection; import java.util.List; import java.util.Map; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.api; public interface AuthorizationManager { String WWW_AUTHENTICATE_HEADER_NAME = "Www-Authenticate"; /** * @return Whether authorization is required * @param headers http response headers * @param statusCode http response status code */ boolean isAuthorizationRequired(int statusCode, Map<String, List<String>> headers); /** * @return Whether authorization is required * @param urlConnection HttpURLConnection representing http response */ boolean isAuthorizationRequired(HttpURLConnection urlConnection) throws IOException; /** * Starts authorization process * @param context Context for obtaining authorization. Should be Activity if authorization in interactive */
void obtainAuthorization (Context context, ResponseListener listener, Object... params);
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/androidTest/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/security/AESEncryptionTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/encryption/AESStringEncryption.java // public class AESStringEncryption implements StringEncryption { // // final static String Algorithm = "AES"; // final static int minKeySize = 16; // final static String hashStr = "zDfb2E9yZartghdY"; // // Key key; // // public AESStringEncryption(String password) { // key = new SecretKeySpec(hash(password.getBytes()), Algorithm); // } // // @Override // public String encrypt(String str) { // byte[] bytes = doFinalWithMode(Cipher.ENCRYPT_MODE, str.getBytes()); // return Base64.encodeToString(bytes, Base64.NO_WRAP); // } // // @Override // public String decrypt(String str) { // byte[] decode = Base64.decode(str.getBytes(), Base64.NO_WRAP); // byte[] bytes = doFinalWithMode(Cipher.DECRYPT_MODE, decode); // return new String(bytes); // } // // private byte[] doFinalWithMode(int mode, byte[] data) { // try { // Cipher cipher = Cipher.getInstance(Algorithm); // cipher.init(mode, key); // return cipher.doFinal(data); // } catch (Exception e) { // e.printStackTrace(); // } // // return new byte[0]; // } // // private byte[] hash(byte[] array){ // byte[] result = Arrays.copyOf(array, minKeySize); // byte[] hash = hashStr.getBytes(); // // for (int i = 0 ; i < minKeySize ; ++i){ // result[i] ^= hash[i]; // } // return result; // } // }
import android.test.InstrumentationTestCase; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.encryption.AESStringEncryption;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.security; public class AESEncryptionTests extends InstrumentationTestCase { final static String testStr = "Hello this is Test String";
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/encryption/AESStringEncryption.java // public class AESStringEncryption implements StringEncryption { // // final static String Algorithm = "AES"; // final static int minKeySize = 16; // final static String hashStr = "zDfb2E9yZartghdY"; // // Key key; // // public AESStringEncryption(String password) { // key = new SecretKeySpec(hash(password.getBytes()), Algorithm); // } // // @Override // public String encrypt(String str) { // byte[] bytes = doFinalWithMode(Cipher.ENCRYPT_MODE, str.getBytes()); // return Base64.encodeToString(bytes, Base64.NO_WRAP); // } // // @Override // public String decrypt(String str) { // byte[] decode = Base64.decode(str.getBytes(), Base64.NO_WRAP); // byte[] bytes = doFinalWithMode(Cipher.DECRYPT_MODE, decode); // return new String(bytes); // } // // private byte[] doFinalWithMode(int mode, byte[] data) { // try { // Cipher cipher = Cipher.getInstance(Algorithm); // cipher.init(mode, key); // return cipher.doFinal(data); // } catch (Exception e) { // e.printStackTrace(); // } // // return new byte[0]; // } // // private byte[] hash(byte[] array){ // byte[] result = Arrays.copyOf(array, minKeySize); // byte[] hash = hashStr.getBytes(); // // for (int i = 0 ; i < minKeySize ; ++i){ // result[i] ^= hash[i]; // } // return result; // } // } // Path: lib/src/androidTest/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/security/AESEncryptionTests.java import android.test.InstrumentationTestCase; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.encryption.AESStringEncryption; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.security; public class AESEncryptionTests extends InstrumentationTestCase { final static String testStr = "Hello this is Test String";
AESStringEncryption encryption;
ibm-bluemix-mobile-services/bms-clientsdk-android-core
lib/src/androidTest/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/security/CertificateAuxiliaryTests.java
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/certificate/CertificatesUtility.java // public class CertificatesUtility { // // public static X509Certificate base64StringToCertificate(String certificateString) throws CertificateException, IOException { // // if (certificateString == null){ // throw new IllegalArgumentException("certificateString cannot be null"); // } // // byte[] encodedCert = Base64.decode(certificateString,Base64.DEFAULT); // InputStream inStream = new ByteArrayInputStream(encodedCert); // CertificateFactory cf = CertificateFactory.getInstance("X.509"); // X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); // inStream.close(); // // return cert; // } // // public static void checkValidityWithPublicKey(X509Certificate certificate, PublicKey publicKey) throws CertificateNotYetValidException, CertificateExpiredException { // // Date now = new Date(); // long nowTime = now.getTime(); // final int oneMinute = 60000; // Date afterAddingOneMinute = new Date(nowTime + (5 * oneMinute)); // // //we are checking the certificate against current time plus five minutes to prevent false failure because of sync problems // certificate.checkValidity(afterAddingOneMinute); // if (!certificate.getPublicKey().equals(publicKey)) { // throw new RuntimeException("Failed to validate public key"); // } // } // // public static String getClientIdFromCertificate(X509Certificate certificate){ // // if (certificate == null){ // throw new IllegalArgumentException("Certificate cannot be null"); // } // // //subjectDN is of the form: "UID=<clientId>, DC=<some other value>" or "DC=<some other value>, UID=<clientId>" // String clientId = null; // // String subjectDN = certificate.getSubjectDN().getName(); // String[] parts = subjectDN.split(Pattern.quote(",")); // for (String part: parts){ // if (part.contains("UID=")){ // String uid=part.substring(part.indexOf("UID=")); // clientId = uid.split(Pattern.quote("="))[1]; // } // } // // return clientId; // } // }
import android.test.InstrumentationTestCase; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.CertificatesUtility; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate;
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.security; /** * Created by cirilla on 8/11/15. */ public class CertificateAuxiliaryTests extends InstrumentationTestCase { final String certificateInBase64 = "MIICbTCCAVWgAwIBAgIIG0w8ZSCfbeQwDQYJKoZIhvcNAQELBQAwYDELMAkGA1UEBhMCSUwxCzAJBgNVBAgTAklMMREwDwYDVQQHEwhTaGVmYXlpbTEMMAoGA1UEChMDSUJNMRIwEAYDVQQLEwlXb3JrbGlnaHQxDzANBgNVBAMTBldMIERldjAgFw0xNTA4MTcwNzQ5MDZaGA8yMDY1MDgxNzA3NDkwNlowUzEXMBUGCgmSJomT8ixkARkWB25vdGhpbmcxODA2BgoJkiaJk\\/IsZAEBEyg2ZmQ4YjViN2FhYzBmNDZkNGQwYzUzY2MyM2M2ZGQyZWMyYmMxOGIxMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMA0jApej21k0ztkgJ4LCrtfT64tvDBq37c5pwCDudyfQqVrySCIc42PuZbQujKMawqJytO168P7Gev\\/z4JlAjsCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAA+0kgTMLNiOALF2T\\/w+4Tf\\/Vcs\\/TZ+5ztSV2xZmLj+cNt18vnAs+Zt\\/zs2v45WVFOE2t58XUIiE5XQ5wqsXdsMRPABwbNj1PGs1o0\\/yWeAHlas0JtJNlgQ4p8SkybnlKdUMzZqtUA0mBb5\\/GqVBrxdl9ci\\/Y1TP6jh+7eQM5Oyj31F7PjfowTxVuxjm7kz87B0MsrZlulTE2h02pFMdNanTdJS3Cx6RmerAXUgn90qKQsMjKTzrnF0lknO6cOSPbyLurJv2t5eJ65wyanpO38IaC31Uy4ARZUU5lPMoBpciCBdiJMfl2QQQFpfxrIQzQDWMNV5AEF1hSKZfTEvAWfQ=="; final String expectedClientId = "6fd8b5b7aac0f46d4d0c53cc23c6dd2ec2bc18b1"; public void testParamForNull() throws CertificateException, IOException { boolean isIlligalArgument = false; try{
// Path: lib/src/main/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/certificate/CertificatesUtility.java // public class CertificatesUtility { // // public static X509Certificate base64StringToCertificate(String certificateString) throws CertificateException, IOException { // // if (certificateString == null){ // throw new IllegalArgumentException("certificateString cannot be null"); // } // // byte[] encodedCert = Base64.decode(certificateString,Base64.DEFAULT); // InputStream inStream = new ByteArrayInputStream(encodedCert); // CertificateFactory cf = CertificateFactory.getInstance("X.509"); // X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); // inStream.close(); // // return cert; // } // // public static void checkValidityWithPublicKey(X509Certificate certificate, PublicKey publicKey) throws CertificateNotYetValidException, CertificateExpiredException { // // Date now = new Date(); // long nowTime = now.getTime(); // final int oneMinute = 60000; // Date afterAddingOneMinute = new Date(nowTime + (5 * oneMinute)); // // //we are checking the certificate against current time plus five minutes to prevent false failure because of sync problems // certificate.checkValidity(afterAddingOneMinute); // if (!certificate.getPublicKey().equals(publicKey)) { // throw new RuntimeException("Failed to validate public key"); // } // } // // public static String getClientIdFromCertificate(X509Certificate certificate){ // // if (certificate == null){ // throw new IllegalArgumentException("Certificate cannot be null"); // } // // //subjectDN is of the form: "UID=<clientId>, DC=<some other value>" or "DC=<some other value>, UID=<clientId>" // String clientId = null; // // String subjectDN = certificate.getSubjectDN().getName(); // String[] parts = subjectDN.split(Pattern.quote(",")); // for (String part: parts){ // if (part.contains("UID=")){ // String uid=part.substring(part.indexOf("UID=")); // clientId = uid.split(Pattern.quote("="))[1]; // } // } // // return clientId; // } // } // Path: lib/src/androidTest/java/com/ibm/mobilefirstplatform/clientsdk/android/security/mca/internal/security/CertificateAuxiliaryTests.java import android.test.InstrumentationTestCase; import com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.CertificatesUtility; import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ package com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.security; /** * Created by cirilla on 8/11/15. */ public class CertificateAuxiliaryTests extends InstrumentationTestCase { final String certificateInBase64 = "MIICbTCCAVWgAwIBAgIIG0w8ZSCfbeQwDQYJKoZIhvcNAQELBQAwYDELMAkGA1UEBhMCSUwxCzAJBgNVBAgTAklMMREwDwYDVQQHEwhTaGVmYXlpbTEMMAoGA1UEChMDSUJNMRIwEAYDVQQLEwlXb3JrbGlnaHQxDzANBgNVBAMTBldMIERldjAgFw0xNTA4MTcwNzQ5MDZaGA8yMDY1MDgxNzA3NDkwNlowUzEXMBUGCgmSJomT8ixkARkWB25vdGhpbmcxODA2BgoJkiaJk\\/IsZAEBEyg2ZmQ4YjViN2FhYzBmNDZkNGQwYzUzY2MyM2M2ZGQyZWMyYmMxOGIxMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMA0jApej21k0ztkgJ4LCrtfT64tvDBq37c5pwCDudyfQqVrySCIc42PuZbQujKMawqJytO168P7Gev\\/z4JlAjsCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAA+0kgTMLNiOALF2T\\/w+4Tf\\/Vcs\\/TZ+5ztSV2xZmLj+cNt18vnAs+Zt\\/zs2v45WVFOE2t58XUIiE5XQ5wqsXdsMRPABwbNj1PGs1o0\\/yWeAHlas0JtJNlgQ4p8SkybnlKdUMzZqtUA0mBb5\\/GqVBrxdl9ci\\/Y1TP6jh+7eQM5Oyj31F7PjfowTxVuxjm7kz87B0MsrZlulTE2h02pFMdNanTdJS3Cx6RmerAXUgn90qKQsMjKTzrnF0lknO6cOSPbyLurJv2t5eJ65wyanpO38IaC31Uy4ARZUU5lPMoBpciCBdiJMfl2QQQFpfxrIQzQDWMNV5AEF1hSKZfTEvAWfQ=="; final String expectedClientId = "6fd8b5b7aac0f46d4d0c53cc23c6dd2ec2bc18b1"; public void testParamForNull() throws CertificateException, IOException { boolean isIlligalArgument = false; try{
CertificatesUtility.base64StringToCertificate(null);
idega/com.idega.block.category
src/java/com/idega/block/category/presentation/FolderBlock.java
// Path: src/java/com/idega/block/category/business/FolderBlockBusiness.java // public interface FolderBlockBusiness extends com.idega.business.IBOService // { // public void addCategoryToInstance(com.idega.block.category.data.ICInformationCategory p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void addCategoryToInstance(com.idega.core.component.data.ICObjectInstance p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public java.util.Collection collectCategoryIntegerIds(int p0) throws java.rmi.RemoteException; // public boolean copyCategoryAttachments(int p0,int p1) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategory createICInformationCategory(com.idega.presentation.IWContext p0,int p1,java.lang.String p2,java.lang.String p3,java.lang.String p4,int p5,int p6) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryTranslation createICInformationCategoryTranslation(int p0,java.lang.String p1,java.lang.String p2,int p3) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder createICInformationFolder(java.lang.String p0,java.lang.String p1,java.lang.String p2,int p3,int p4,int p5)throws java.sql.SQLException, java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder createICInformationFolderForLocale(java.lang.String p0,int p1,int p2,int p3)throws java.sql.SQLException, java.rmi.RemoteException; // public boolean detachWorkfolderFromObjectInstance(com.idega.core.component.data.ICObjectInstance p0) throws java.rmi.RemoteException; // public java.util.Collection getAvailableCategories(int p0,int p1) throws java.rmi.RemoteException; // public java.util.Collection getAvailableTopNodeCategories(int p0,int p1) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategory getCategory(int p0) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryHome getCategoryHome()throws com.idega.data.IDOLookupException, java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryTranslationHome getCategoryTranslationHome()throws com.idega.data.IDOLookupException, java.rmi.RemoteException; // public java.util.List getInstanceCategories(int p0) throws java.rmi.RemoteException; // public java.util.List getInstanceViewFolders(int p0) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder getInstanceWorkeFolder(int p0,int p1,int p2,boolean p3) throws java.rmi.RemoteException; // public boolean removeCategory(com.idega.presentation.IWContext p0,int p1) throws java.rmi.RemoteException; // public void removeCategoryFromInstance(com.idega.block.category.data.ICInformationCategory p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void removeCategoryFromInstance(com.idega.core.component.data.ICObjectInstance p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void storeCategoryToParent(int p0,int p1)throws java.rmi.RemoteException, java.rmi.RemoteException; // public void storeInstanceCategories(int p0,int[] p1) throws java.rmi.RemoteException; // public boolean updateCategory(com.idega.presentation.IWContext p0,int p1,java.lang.String p2,java.lang.String p3,int p4)throws java.rmi.RemoteException, java.rmi.RemoteException; // public boolean hasAvailableCategory(int icObjectId); // }
import java.rmi.RemoteException; import java.util.Iterator; import java.util.List; import com.idega.block.category.business.FolderBlockBusiness; import com.idega.block.category.data.InformationCategory; import com.idega.block.category.data.InformationFolder; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.core.component.data.ICObject; import com.idega.core.component.data.ICObjectHome; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.core.localisation.data.ICLocale; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.text.Link;
package com.idega.block.category.presentation; /** * <p> * Title: idegaWeb</p> <p> * Description: </p> <p> * Copyright: Copyright (c) 2002</p> <p> * Company: idega</p> * *@author <a href="[email protected]">Gudmundur Agust Saemundsson</a> *@created 15. mars 2002 *@version 1.0 */ public class FolderBlock extends Block { private boolean _useLocalizedFolders = true; private InformationFolder _workFolder = null; private InformationFolder[] _visibleFolders = null; private InformationCategory[] _categoriesForInstance = null; private boolean _autocreate = true; private String _contentLocaleIdentifier = null;
// Path: src/java/com/idega/block/category/business/FolderBlockBusiness.java // public interface FolderBlockBusiness extends com.idega.business.IBOService // { // public void addCategoryToInstance(com.idega.block.category.data.ICInformationCategory p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void addCategoryToInstance(com.idega.core.component.data.ICObjectInstance p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public java.util.Collection collectCategoryIntegerIds(int p0) throws java.rmi.RemoteException; // public boolean copyCategoryAttachments(int p0,int p1) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategory createICInformationCategory(com.idega.presentation.IWContext p0,int p1,java.lang.String p2,java.lang.String p3,java.lang.String p4,int p5,int p6) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryTranslation createICInformationCategoryTranslation(int p0,java.lang.String p1,java.lang.String p2,int p3) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder createICInformationFolder(java.lang.String p0,java.lang.String p1,java.lang.String p2,int p3,int p4,int p5)throws java.sql.SQLException, java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder createICInformationFolderForLocale(java.lang.String p0,int p1,int p2,int p3)throws java.sql.SQLException, java.rmi.RemoteException; // public boolean detachWorkfolderFromObjectInstance(com.idega.core.component.data.ICObjectInstance p0) throws java.rmi.RemoteException; // public java.util.Collection getAvailableCategories(int p0,int p1) throws java.rmi.RemoteException; // public java.util.Collection getAvailableTopNodeCategories(int p0,int p1) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategory getCategory(int p0) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryHome getCategoryHome()throws com.idega.data.IDOLookupException, java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationCategoryTranslationHome getCategoryTranslationHome()throws com.idega.data.IDOLookupException, java.rmi.RemoteException; // public java.util.List getInstanceCategories(int p0) throws java.rmi.RemoteException; // public java.util.List getInstanceViewFolders(int p0) throws java.rmi.RemoteException; // public com.idega.block.category.data.ICInformationFolder getInstanceWorkeFolder(int p0,int p1,int p2,boolean p3) throws java.rmi.RemoteException; // public boolean removeCategory(com.idega.presentation.IWContext p0,int p1) throws java.rmi.RemoteException; // public void removeCategoryFromInstance(com.idega.block.category.data.ICInformationCategory p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void removeCategoryFromInstance(com.idega.core.component.data.ICObjectInstance p0,int p1)throws java.sql.SQLException, java.rmi.RemoteException; // public void storeCategoryToParent(int p0,int p1)throws java.rmi.RemoteException, java.rmi.RemoteException; // public void storeInstanceCategories(int p0,int[] p1) throws java.rmi.RemoteException; // public boolean updateCategory(com.idega.presentation.IWContext p0,int p1,java.lang.String p2,java.lang.String p3,int p4)throws java.rmi.RemoteException, java.rmi.RemoteException; // public boolean hasAvailableCategory(int icObjectId); // } // Path: src/java/com/idega/block/category/presentation/FolderBlock.java import java.rmi.RemoteException; import java.util.Iterator; import java.util.List; import com.idega.block.category.business.FolderBlockBusiness; import com.idega.block.category.data.InformationCategory; import com.idega.block.category.data.InformationFolder; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.core.component.data.ICObject; import com.idega.core.component.data.ICObjectHome; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.core.localisation.data.ICLocale; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.text.Link; package com.idega.block.category.presentation; /** * <p> * Title: idegaWeb</p> <p> * Description: </p> <p> * Copyright: Copyright (c) 2002</p> <p> * Company: idega</p> * *@author <a href="[email protected]">Gudmundur Agust Saemundsson</a> *@created 15. mars 2002 *@version 1.0 */ public class FolderBlock extends Block { private boolean _useLocalizedFolders = true; private InformationFolder _workFolder = null; private InformationFolder[] _visibleFolders = null; private InformationCategory[] _categoriesForInstance = null; private boolean _autocreate = true; private String _contentLocaleIdentifier = null;
FolderBlockBusiness _business= null;
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/FloatArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class FloatArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<float[]> floatArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/FloatArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; /* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class FloatArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<float[]> floatArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
logInfo("FloatArrayCache[" + arraySize + "]: get: " + getOp
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/FloatArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
fill(array, fromIndex, toIndex, 0f); // fill cache: floatArrays.addLast(array); } static void fill(final float[] array, final int fromIndex, final int toIndex, final float value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final float[] array, final int fromIndex, final int toIndex, final float value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/FloatArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; fill(array, fromIndex, toIndex, 0f); // fill cache: floatArrays.addLast(array); } static void fill(final float[] array, final int fromIndex, final int toIndex, final float value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final float[] array, final int fromIndex, final int toIndex, final float value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
logException("Invalid array value at " + i + "\n"
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/RendererStats.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // // Path: src/main/java/org/marlin/pisces/stats/Histogram.java // public final class Histogram extends StatLong { // // static final int BUCKET = 2; // static final int MAX = 20; // static final int LAST = MAX - 1; // static final int[] STEPS = new int[MAX]; // // static { // STEPS[0] = 0; // STEPS[1] = 1; // // for (int i = 2; i < MAX; i++) { // STEPS[i] = STEPS[i - 1] * BUCKET; // } // // System.out.println("Histogram.STEPS = " + Arrays.toString(STEPS)); // } // // static int bucket(int val) { // for (int i = 1; i < MAX; i++) { // if (val < STEPS[i]) { // return i - 1; // } // } // return LAST; // } // // private final StatLong[] stats = new StatLong[MAX]; // // public Histogram(final String name) { // super(name); // for (int i = 0; i < MAX; i++) { // stats[i] = new StatLong(String.format("%5s .. %5s", STEPS[i], // ((i + 1 < MAX) ? STEPS[i + 1] : "~"))); // } // } // // @Override // public void reset() { // super.reset(); // for (int i = 0; i < MAX; i++) { // stats[i].reset(); // } // } // // @Override // public void add(int val) { // super.add(val); // stats[bucket(val)].add(val); // } // // @Override // public void add(long val) { // add((int) val); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(2048); // super.toString(sb).append(" { "); // // for (int i = 0; i < MAX; i++) { // if (stats[i].count != 0l) { // sb.append("\n ").append(stats[i].toString()); // } // } // // return sb.append(" }").toString(); // } // } // // Path: src/main/java/org/marlin/pisces/stats/Monitor.java // public final class Monitor extends StatLong { // // private final static long INVALID = -1L; // // private long start = INVALID; // // public Monitor(final String name) { // super(name); // } // // public void start() { // start = System.nanoTime(); // } // // public void stop() { // final long elapsed = System.nanoTime() - start; // if (start != INVALID && elapsed > 0l) { // add(elapsed); // } // start = INVALID; // } // } // // Path: src/main/java/org/marlin/pisces/stats/StatLong.java // public class StatLong { // // public final String name; // public long count = 0l; // public long sum = 0l; // public long min = Integer.MAX_VALUE; // public long max = Integer.MIN_VALUE; // // public StatLong(final String name) { // this.name = name; // } // // public void reset() { // count = 0l; // sum = 0l; // min = Integer.MAX_VALUE; // max = Integer.MIN_VALUE; // } // // public void add(final int val) { // count++; // sum += val; // if (val < min) { // min = val; // } // if (val > max) { // max = val; // } // } // // public void add(final long val) { // count++; // sum += val; // if (val < min) { // min = val; // } // if (val > max) { // max = val; // } // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(128); // toString(sb); // return sb.toString(); // } // // public final StringBuilder toString(final StringBuilder sb) { // sb.append(name).append('[').append(count); // sb.append("] sum: ").append(sum).append(" avg: "); // sb.append(trimTo3Digits(((double) sum) / count)); // sb.append(" [").append(min).append(" | ").append(max).append("]"); // return sb; // } // // /** // * Adjust the given double value to keep only 3 decimal digits // * // * @param value value to adjust // * @return double value with only 3 decimal digits // */ // public static double trimTo3Digits(final double value) { // return ((long) (1e3d * value)) / 1e3d; // } // }
import org.marlin.pisces.stats.StatLong; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import static org.marlin.pisces.MarlinUtils.logInfo; import org.marlin.pisces.stats.Histogram; import org.marlin.pisces.stats.Monitor;
}; private RendererStats() { super(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { dump(); } }); if (USE_DUMP_THREAD) { final Timer statTimer = new Timer("RendererStats"); statTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { dump(); } }, STAT_DUMP, STAT_DUMP); } } void dump() { if (DO_STATS) { ArrayCache.dumpStats(); } final RendererContext[] all = allContexts.toArray( new RendererContext[allContexts.size()]); for (RendererContext rdrCtx : all) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // // Path: src/main/java/org/marlin/pisces/stats/Histogram.java // public final class Histogram extends StatLong { // // static final int BUCKET = 2; // static final int MAX = 20; // static final int LAST = MAX - 1; // static final int[] STEPS = new int[MAX]; // // static { // STEPS[0] = 0; // STEPS[1] = 1; // // for (int i = 2; i < MAX; i++) { // STEPS[i] = STEPS[i - 1] * BUCKET; // } // // System.out.println("Histogram.STEPS = " + Arrays.toString(STEPS)); // } // // static int bucket(int val) { // for (int i = 1; i < MAX; i++) { // if (val < STEPS[i]) { // return i - 1; // } // } // return LAST; // } // // private final StatLong[] stats = new StatLong[MAX]; // // public Histogram(final String name) { // super(name); // for (int i = 0; i < MAX; i++) { // stats[i] = new StatLong(String.format("%5s .. %5s", STEPS[i], // ((i + 1 < MAX) ? STEPS[i + 1] : "~"))); // } // } // // @Override // public void reset() { // super.reset(); // for (int i = 0; i < MAX; i++) { // stats[i].reset(); // } // } // // @Override // public void add(int val) { // super.add(val); // stats[bucket(val)].add(val); // } // // @Override // public void add(long val) { // add((int) val); // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(2048); // super.toString(sb).append(" { "); // // for (int i = 0; i < MAX; i++) { // if (stats[i].count != 0l) { // sb.append("\n ").append(stats[i].toString()); // } // } // // return sb.append(" }").toString(); // } // } // // Path: src/main/java/org/marlin/pisces/stats/Monitor.java // public final class Monitor extends StatLong { // // private final static long INVALID = -1L; // // private long start = INVALID; // // public Monitor(final String name) { // super(name); // } // // public void start() { // start = System.nanoTime(); // } // // public void stop() { // final long elapsed = System.nanoTime() - start; // if (start != INVALID && elapsed > 0l) { // add(elapsed); // } // start = INVALID; // } // } // // Path: src/main/java/org/marlin/pisces/stats/StatLong.java // public class StatLong { // // public final String name; // public long count = 0l; // public long sum = 0l; // public long min = Integer.MAX_VALUE; // public long max = Integer.MIN_VALUE; // // public StatLong(final String name) { // this.name = name; // } // // public void reset() { // count = 0l; // sum = 0l; // min = Integer.MAX_VALUE; // max = Integer.MIN_VALUE; // } // // public void add(final int val) { // count++; // sum += val; // if (val < min) { // min = val; // } // if (val > max) { // max = val; // } // } // // public void add(final long val) { // count++; // sum += val; // if (val < min) { // min = val; // } // if (val > max) { // max = val; // } // } // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(128); // toString(sb); // return sb.toString(); // } // // public final StringBuilder toString(final StringBuilder sb) { // sb.append(name).append('[').append(count); // sb.append("] sum: ").append(sum).append(" avg: "); // sb.append(trimTo3Digits(((double) sum) / count)); // sb.append(" [").append(min).append(" | ").append(max).append("]"); // return sb; // } // // /** // * Adjust the given double value to keep only 3 decimal digits // * // * @param value value to adjust // * @return double value with only 3 decimal digits // */ // public static double trimTo3Digits(final double value) { // return ((long) (1e3d * value)) / 1e3d; // } // } // Path: src/main/java/org/marlin/pisces/RendererStats.java import org.marlin.pisces.stats.StatLong; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentLinkedQueue; import static org.marlin.pisces.MarlinUtils.logInfo; import org.marlin.pisces.stats.Histogram; import org.marlin.pisces.stats.Monitor; }; private RendererStats() { super(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { dump(); } }); if (USE_DUMP_THREAD) { final Timer statTimer = new Timer("RendererStats"); statTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { dump(); } }, STAT_DUMP, STAT_DUMP); } } void dump() { if (DO_STATS) { ArrayCache.dumpStats(); } final RendererContext[] all = allContexts.toArray( new RendererContext[allContexts.size()]); for (RendererContext rdrCtx : all) {
logInfo("RendererContext: " + rdrCtx.name);
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/Stroker.java
// Path: src/main/java/org/marlin/pisces/Curve.java // static final class BreakPtrIterator { // private int nextCurveIdx; // private int curCurveOff; // private float prevT; // private float[] pts; // private int type; // private float[] ts; // private int numTs; // // void init(final float[] pts, final int type, // final float[] ts, final int numTs) { // this.pts = pts; // this.type = type; // this.ts = ts; // this.numTs = numTs; // // nextCurveIdx = 0; // curCurveOff = 0; // prevT = 0f; // } // // public boolean hasNext() { // return nextCurveIdx <= numTs; // } // // public int next() { // int ret; // if (nextCurveIdx < numTs) { // float curT = ts[nextCurveIdx]; // float splitT = (curT - prevT) / (1f - prevT); // Helpers.subdivideAt(splitT, // pts, curCurveOff, // pts, 0, // pts, type, type); // prevT = curT; // ret = 0; // curCurveOff = type; // } else { // ret = curCurveOff; // } // nextCurveIdx++; // return ret; // } // }
import org.marlin.pisces.Curve.BreakPtrIterator; import java.util.Arrays; import static java.lang.Math.ulp; import static java.lang.Math.sqrt; import sun.awt.geom.PathConsumer2D;
} } if (dxs == 0f && dys == 0f) { // this happens if the "curve" is just a point lineTo(mid[0], mid[1]); return; } // if these vectors are too small, normalize them, to avoid future // precision problems. if (Math.abs(dxs) < 0.1f && Math.abs(dys) < 0.1f) { float len = (float) sqrt(dxs*dxs + dys*dys); dxs /= len; dys /= len; } if (Math.abs(dxf) < 0.1f && Math.abs(dyf) < 0.1f) { float len = (float) sqrt(dxf*dxf + dyf*dyf); dxf /= len; dyf /= len; } computeOffset(dxs, dys, lineWidth2, offset0); drawJoin(cdx, cdy, cx0, cy0, dxs, dys, cmx, cmy, offset0[0], offset0[1]); int nSplits = findSubdivPoints(curve, mid, subdivTs, 8, lineWidth2); final float[] l = lp; final float[] r = rp; int kind = 0;
// Path: src/main/java/org/marlin/pisces/Curve.java // static final class BreakPtrIterator { // private int nextCurveIdx; // private int curCurveOff; // private float prevT; // private float[] pts; // private int type; // private float[] ts; // private int numTs; // // void init(final float[] pts, final int type, // final float[] ts, final int numTs) { // this.pts = pts; // this.type = type; // this.ts = ts; // this.numTs = numTs; // // nextCurveIdx = 0; // curCurveOff = 0; // prevT = 0f; // } // // public boolean hasNext() { // return nextCurveIdx <= numTs; // } // // public int next() { // int ret; // if (nextCurveIdx < numTs) { // float curT = ts[nextCurveIdx]; // float splitT = (curT - prevT) / (1f - prevT); // Helpers.subdivideAt(splitT, // pts, curCurveOff, // pts, 0, // pts, type, type); // prevT = curT; // ret = 0; // curCurveOff = type; // } else { // ret = curCurveOff; // } // nextCurveIdx++; // return ret; // } // } // Path: src/main/java/org/marlin/pisces/Stroker.java import org.marlin.pisces.Curve.BreakPtrIterator; import java.util.Arrays; import static java.lang.Math.ulp; import static java.lang.Math.sqrt; import sun.awt.geom.PathConsumer2D; } } if (dxs == 0f && dys == 0f) { // this happens if the "curve" is just a point lineTo(mid[0], mid[1]); return; } // if these vectors are too small, normalize them, to avoid future // precision problems. if (Math.abs(dxs) < 0.1f && Math.abs(dys) < 0.1f) { float len = (float) sqrt(dxs*dxs + dys*dys); dxs /= len; dys /= len; } if (Math.abs(dxf) < 0.1f && Math.abs(dyf) < 0.1f) { float len = (float) sqrt(dxf*dxf + dyf*dyf); dxf /= len; dyf /= len; } computeOffset(dxs, dys, lineWidth2, offset0); drawJoin(cdx, cdy, cx0, cy0, dxs, dys, cmx, cmy, offset0[0], offset0[1]); int nSplits = findSubdivPoints(curve, mid, subdivTs, 8, lineWidth2); final float[] l = lp; final float[] r = rp; int kind = 0;
BreakPtrIterator it = curve.breakPtsAtTs(mid, 8, subdivTs, nSplits);
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/ArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logInfo;
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; public final class ArrayCache implements MarlinConst { final static int BUCKETS = 4; final static int MIN_ARRAY_SIZE = 4096; final static int MAX_ARRAY_SIZE; final static int MASK_CLR_1 = ~1; // threshold to grow arrays only by (3/2) instead of 2 final static int THRESHOLD_ARRAY_SIZE; final static int[] ARRAY_SIZES = new int[BUCKETS]; // dirty byte array sizes final static int MIN_DIRTY_BYTE_ARRAY_SIZE = 32 * 2048; // 32px x 2048px final static int MAX_DIRTY_BYTE_ARRAY_SIZE; final static int[] DIRTY_BYTE_ARRAY_SIZES = new int[BUCKETS]; // stats private static int resizeInt = 0; private static int resizeDirtyInt = 0; private static int resizeDirtyFloat = 0; private static int resizeDirtyByte = 0; private static int oversize = 0; static { // initialize buckets for int/float arrays int arraySize = MIN_ARRAY_SIZE; for (int i = 0; i < BUCKETS; i++, arraySize <<= 2) { ARRAY_SIZES[i] = arraySize; if (DO_TRACE) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/ArrayCache.java import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logInfo; /* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; public final class ArrayCache implements MarlinConst { final static int BUCKETS = 4; final static int MIN_ARRAY_SIZE = 4096; final static int MAX_ARRAY_SIZE; final static int MASK_CLR_1 = ~1; // threshold to grow arrays only by (3/2) instead of 2 final static int THRESHOLD_ARRAY_SIZE; final static int[] ARRAY_SIZES = new int[BUCKETS]; // dirty byte array sizes final static int MIN_DIRTY_BYTE_ARRAY_SIZE = 32 * 2048; // 32px x 2048px final static int MAX_DIRTY_BYTE_ARRAY_SIZE; final static int[] DIRTY_BYTE_ARRAY_SIZES = new int[BUCKETS]; // stats private static int resizeInt = 0; private static int resizeDirtyInt = 0; private static int resizeDirtyFloat = 0; private static int resizeDirtyByte = 0; private static int oversize = 0; static { // initialize buckets for int/float arrays int arraySize = MIN_ARRAY_SIZE; for (int i = 0; i < BUCKETS; i++, arraySize <<= 2) { ARRAY_SIZES[i] = arraySize; if (DO_TRACE) {
logInfo("arraySize[" + i + "]: " + arraySize);
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/MarlinProperties.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.security.AccessController; import static org.marlin.pisces.MarlinUtils.logInfo; import sun.security.action.GetPropertyAction;
return getBoolean("sun.java2d.renderer.logCreateContext", "false"); } public static boolean isLogUnsafeMalloc() { return getBoolean("sun.java2d.renderer.logUnsafeMalloc", "false"); } // quality settings public static double getGamma() { return getDouble("sun.java2d.renderer.gamma", 1.0, 0.5, 4.0); } // system property utilities static boolean getBoolean(final String key, final String def) { return Boolean.valueOf(AccessController.doPrivileged( new GetPropertyAction(key, def))); } static int getInteger(final String key, final int def, final int min, final int max) { final String property = AccessController.doPrivileged( new GetPropertyAction(key)); int value = def; if (property != null) { try { value = Integer.decode(property); } catch (NumberFormatException e) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/MarlinProperties.java import java.security.AccessController; import static org.marlin.pisces.MarlinUtils.logInfo; import sun.security.action.GetPropertyAction; return getBoolean("sun.java2d.renderer.logCreateContext", "false"); } public static boolean isLogUnsafeMalloc() { return getBoolean("sun.java2d.renderer.logUnsafeMalloc", "false"); } // quality settings public static double getGamma() { return getDouble("sun.java2d.renderer.gamma", 1.0, 0.5, 4.0); } // system property utilities static boolean getBoolean(final String key, final String def) { return Boolean.valueOf(AccessController.doPrivileged( new GetPropertyAction(key, def))); } static int getInteger(final String key, final int def, final int min, final int max) { final String property = AccessController.doPrivileged( new GetPropertyAction(key)); int value = def; if (property != null) { try { value = Integer.decode(property); } catch (NumberFormatException e) {
logInfo("Invalid integer value for " + key + " = " + property);
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/ByteArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class ByteArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<byte[]> byteArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/ByteArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; /* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class ByteArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<byte[]> byteArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
logInfo("ByteArrayCache[" + arraySize + "]: get: " + getOp
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/ByteArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
fill(array, fromIndex, toIndex, BYTE_0); // fill cache: byteArrays.addLast(array); } static void fill(final byte[] array, final int fromIndex, final int toIndex, final byte value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final byte[] array, final int fromIndex, final int toIndex, final byte value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/ByteArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; fill(array, fromIndex, toIndex, BYTE_0); // fill cache: byteArrays.addLast(array); } static void fill(final byte[] array, final int fromIndex, final int toIndex, final byte value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final byte[] array, final int fromIndex, final int toIndex, final byte value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
logException("Invalid array value at " + i + "\n"
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/IntArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class IntArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<int[]> intArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/IntArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; /* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.marlin.pisces; final class IntArrayCache implements MarlinConst { private final int arraySize; private final ArrayDeque<int[]> intArrays; // stats private int getOp = 0; private int createOp = 0; private int returnOp = 0; void dumpStats() { if (getOp > 0) {
logInfo("IntArrayCache[" + arraySize + "]: get: " + getOp
bourgesl/marlin-renderer
src/main/java/org/marlin/pisces/IntArrayCache.java
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // }
import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo;
fill(array, fromIndex, toIndex, 0); // fill cache: intArrays.addLast(array); } static void fill(final int[] array, final int fromIndex, final int toIndex, final int value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final int[] array, final int fromIndex, final int toIndex, final int value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
// Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logException(final String msg, final Throwable th) { // if (MarlinConst.USE_LOGGER) { // // log.warning(msg, th); // log.log(java.util.logging.Level.WARNING, msg, th); // } else { // System.out.print("WARNING: "); // System.out.println(msg); // th.printStackTrace(System.err); // } // } // // Path: src/main/java/org/marlin/pisces/MarlinUtils.java // public static void logInfo(final String msg) { // if (MarlinConst.USE_LOGGER) { // log.info(msg); // } else { // System.out.print("INFO: "); // System.out.println(msg); // } // } // Path: src/main/java/org/marlin/pisces/IntArrayCache.java import java.util.ArrayDeque; import java.util.Arrays; import static org.marlin.pisces.MarlinUtils.logException; import static org.marlin.pisces.MarlinUtils.logInfo; fill(array, fromIndex, toIndex, 0); // fill cache: intArrays.addLast(array); } static void fill(final int[] array, final int fromIndex, final int toIndex, final int value) { // clear array data: /* * Arrays.fill is faster than System.arraycopy(empty array) * or Unsafe.setMemory(byte 0) */ if (toIndex != 0) { Arrays.fill(array, fromIndex, toIndex, value); } if (DO_CHECKS) { check(array, 0, array.length, value); } } static void check(final int[] array, final int fromIndex, final int toIndex, final int value) { if (DO_CHECKS) { // check zero on full array: for (int i = fromIndex; i < toIndex; i++) { if (array[i] != value) {
logException("Invalid array value at " + i + "\n"
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/ModifyPrefixData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import java.util.Collection; import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
package owl2vcs.changes; public class ModifyPrefixData extends PrefixChangeData { private static final long serialVersionUID = -4830654067341708579L; private final String oldPrefix; public ModifyPrefixData(String prefixName, String oldPrefix, String newPrefix) { super(prefixName, newPrefix); this.oldPrefix = oldPrefix; } @Override public <R, E extends Exception> R accept(
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/ModifyPrefixData.java import java.util.Collection; import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; package owl2vcs.changes; public class ModifyPrefixData extends PrefixChangeData { private static final long serialVersionUID = -4830654067341708579L; private final String oldPrefix; public ModifyPrefixData(String prefixName, String oldPrefix, String newPrefix) { super(prefixName, newPrefix); this.oldPrefix = oldPrefix; } @Override public <R, E extends Exception> R accept(
CustomOntologyChangeDataVisitor<R, E> visitor) throws E {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/RemovePrefixData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
package owl2vcs.changes; public class RemovePrefixData extends PrefixChangeData { private static final long serialVersionUID = 938006048114096186L; public RemovePrefixData(String prefixName, String prefix) { super(prefixName, prefix); } @Override public <R, E extends Exception> R accept(
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/RemovePrefixData.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; package owl2vcs.changes; public class RemovePrefixData extends PrefixChangeData { private static final long serialVersionUID = 938006048114096186L; public RemovePrefixData(String prefixName, String prefix) { super(prefixName, prefix); } @Override public <R, E extends Exception> R accept(
CustomOntologyChangeDataVisitor<R, E> visitor) throws E {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/RemovePrefix.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor;
package owl2vcs.changes; public class RemovePrefix extends PrefixChange { public RemovePrefix(final OWLOntology ont, final String prefixName, final String prefix) { super(ont, prefixName, prefix); } @Override public int hashCode() { final int prime = 3; return prime * super.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RemovePrefix)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("REMOVE PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/RemovePrefix.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor; package owl2vcs.changes; public class RemovePrefix extends PrefixChange { public RemovePrefix(final OWLOntology ont, final String prefixName, final String prefix) { super(ont, prefixName, prefix); } @Override public int hashCode() { final int prime = 3; return prime * super.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RemovePrefix)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("REMOVE PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
public void accept(final CustomOntologyChangeVisitor visitor) {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/RenamePrefixData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import java.util.Collection; import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
package owl2vcs.changes; public class RenamePrefixData extends PrefixChangeData { private static final long serialVersionUID = -3363060595690396626L; private final String oldPrefixName; public RenamePrefixData(String oldPrefixName, String prefix, String newPrefixName) { super(newPrefixName, prefix); this.oldPrefixName = oldPrefixName; } @Override public <R, E extends Exception> R accept(
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/RenamePrefixData.java import java.util.Collection; import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; package owl2vcs.changes; public class RenamePrefixData extends PrefixChangeData { private static final long serialVersionUID = -3363060595690396626L; private final String oldPrefixName; public RenamePrefixData(String oldPrefixName, String prefix, String newPrefixName) { super(newPrefixName, prefix); this.oldPrefixName = oldPrefixName; } @Override public <R, E extends Exception> R accept(
CustomOntologyChangeDataVisitor<R, E> visitor) throws E {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/CustomOntologyChangeData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeDataVisitor; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
package owl2vcs.changes; public abstract class CustomOntologyChangeData extends OWLOntologyChangeData { private static final long serialVersionUID = -6017236080840691763L;
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/CustomOntologyChangeData.java import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeDataVisitor; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; package owl2vcs.changes; public abstract class CustomOntologyChangeData extends OWLOntologyChangeData { private static final long serialVersionUID = -6017236080840691763L;
public abstract <R, E extends Exception> R accept(CustomOntologyChangeDataVisitor<R, E> visitor) throws E;
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/AddPrefixData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
package owl2vcs.changes; public class AddPrefixData extends PrefixChangeData { private static final long serialVersionUID = 2801228470061214801L; public AddPrefixData(String prefixName, String prefix) { super(prefixName, prefix); } @Override public <R, E extends Exception> R accept(
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/AddPrefixData.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; package owl2vcs.changes; public class AddPrefixData extends PrefixChangeData { private static final long serialVersionUID = 2801228470061214801L; public AddPrefixData(String prefixName, String prefix) { super(prefixName, prefix); } @Override public <R, E extends Exception> R accept(
CustomOntologyChangeDataVisitor<R, E> visitor) throws E {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/SetOntologyFormat.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owl2vcs.changeset.CustomOntologyChangeVisitor;
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof SetOntologyFormat)) return false; SetOntologyFormat other = (SetOntologyFormat) obj; if (newOntologyFormat == null) { if (other.newOntologyFormat != null) return false; } else if (!newOntologyFormat.equals(other.newOntologyFormat)) return false; if (ontologyFormat == null) { if (other.ontologyFormat != null) return false; } else if (!ontologyFormat.equals(other.ontologyFormat)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SET ONTOLOGY FORMAT: "); sb.append(getNewOntologyFormat().toString()); return sb.toString(); } @Override
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/SetOntologyFormat.java import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owl2vcs.changeset.CustomOntologyChangeVisitor; public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof SetOntologyFormat)) return false; SetOntologyFormat other = (SetOntologyFormat) obj; if (newOntologyFormat == null) { if (other.newOntologyFormat != null) return false; } else if (!newOntologyFormat.equals(other.newOntologyFormat)) return false; if (ontologyFormat == null) { if (other.ontologyFormat != null) return false; } else if (!ontologyFormat.equals(other.ontologyFormat)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SET ONTOLOGY FORMAT: "); sb.append(getNewOntologyFormat().toString()); return sb.toString(); } @Override
public void accept(final CustomOntologyChangeVisitor visitor) {
utapyngo/owl2vcs
src/main/java/owl2vcs/changeset/MutableChangeSet.java
// Path: src/main/java/owl2vcs/changes/PrefixChangeData.java // public abstract class PrefixChangeData extends CustomOntologyChangeData { // // private static final long serialVersionUID = -1862023752748180868L; // // private final String prefixName; // private final String prefix; // // public PrefixChangeData(String prefixName, String prefix) { // if (prefixName == null) { // throw new NullPointerException("prefixName must not be null"); // } // if (prefix == null) { // throw new NullPointerException("prefix must not be null"); // } // this.prefixName = prefixName; // this.prefix = prefix; // } // // /** // * @return the prefixName // */ // public String getPrefixName() { // return prefixName; // } // // /** // * @return the prefix // */ // public String getPrefix() { // return prefix; // } // // public Collection<String> getPrefixSignature() { // final Collection<String> sig = new ArrayList<String>(); // sig.add(getPrefixName()); // sig.add(getPrefix()); // return sig; // } // // } // // Path: src/main/java/owl2vcs/changes/SetOntologyFormatData.java // public class SetOntologyFormatData extends CustomOntologyChangeData { // // private static final long serialVersionUID = 4000984588491273026L; // // private final OWLOntologyFormat newFormat; // // public SetOntologyFormatData(OWLOntologyFormat newFormat) { // if (newFormat == null) { // throw new NullPointerException("newFormat must not be null"); // } // this.newFormat = newFormat; // } // // /** // * Creates a set ontology format change, which will set the format of the // * ontology to the specified new format specified as a string. // * // * @param ont // * The ontology whose format is to be changed // * @param newOntologyFormat // * A string representing the new ontology format // * @throws UnknownOntologyFormatException // */ // public SetOntologyFormatData(final String newFormatString) // throws UnknownOntologyFormatException { // super(); // OWLOntologyFormat newOntologyFormat; // if (newFormatString.equals("RDF/XML")) // newOntologyFormat = new RDFXMLOntologyFormat(); // else if (newFormatString.equals("OWL/XML")) // newOntologyFormat = new OWLXMLOntologyFormat(); // else if (newFormatString.equals("Turtle")) // newOntologyFormat = new TurtleOntologyFormat(); // else if (newFormatString.equals("OWL Functional Syntax")) // newOntologyFormat = new OWLFunctionalSyntaxOntologyFormat(); // else if (newFormatString.equals("Manchester OWL Syntax")) // newOntologyFormat = new ManchesterOWLSyntaxOntologyFormat(); // else // throw new UnknownOntologyFormatException("Unknown format: " + newFormatString); // this.newFormat = newOntologyFormat; // } // // @Override // public SetOntologyFormat createOntologyChange(OWLOntology ontology) { // if (ontology == null) { // throw new NullPointerException("ontology must not be null"); // } // return new SetOntologyFormat(ontology, newFormat); // } // // public OWLOntologyFormat getNewFormat() { // return newFormat; // } // // @Override // public int hashCode() { // return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (!(obj instanceof SetOntologyFormatData)) { // return false; // } // SetOntologyFormatData other = (SetOntologyFormatData) obj; // return newFormat.equals(other.newFormat); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("SetOntologyFormatData"); // sb.append("(OntologyFormat("); // sb.append(newFormat); // sb.append("))"); // return sb.toString(); // } // // @Override // public <R, E extends Exception> R accept( // CustomOntologyChangeDataVisitor<R, E> visitor) throws E { // return visitor.visit(this); // } // // }
import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.semanticweb.owlapi.change.AxiomChangeData; import org.semanticweb.owlapi.change.ImportChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.SetOntologyIDData; import owl2vcs.changes.PrefixChangeData; import owl2vcs.changes.SetOntologyFormatData;
package owl2vcs.changeset; public class MutableChangeSet extends ChangeSet { public MutableChangeSet() { setFormatChange(null);
// Path: src/main/java/owl2vcs/changes/PrefixChangeData.java // public abstract class PrefixChangeData extends CustomOntologyChangeData { // // private static final long serialVersionUID = -1862023752748180868L; // // private final String prefixName; // private final String prefix; // // public PrefixChangeData(String prefixName, String prefix) { // if (prefixName == null) { // throw new NullPointerException("prefixName must not be null"); // } // if (prefix == null) { // throw new NullPointerException("prefix must not be null"); // } // this.prefixName = prefixName; // this.prefix = prefix; // } // // /** // * @return the prefixName // */ // public String getPrefixName() { // return prefixName; // } // // /** // * @return the prefix // */ // public String getPrefix() { // return prefix; // } // // public Collection<String> getPrefixSignature() { // final Collection<String> sig = new ArrayList<String>(); // sig.add(getPrefixName()); // sig.add(getPrefix()); // return sig; // } // // } // // Path: src/main/java/owl2vcs/changes/SetOntologyFormatData.java // public class SetOntologyFormatData extends CustomOntologyChangeData { // // private static final long serialVersionUID = 4000984588491273026L; // // private final OWLOntologyFormat newFormat; // // public SetOntologyFormatData(OWLOntologyFormat newFormat) { // if (newFormat == null) { // throw new NullPointerException("newFormat must not be null"); // } // this.newFormat = newFormat; // } // // /** // * Creates a set ontology format change, which will set the format of the // * ontology to the specified new format specified as a string. // * // * @param ont // * The ontology whose format is to be changed // * @param newOntologyFormat // * A string representing the new ontology format // * @throws UnknownOntologyFormatException // */ // public SetOntologyFormatData(final String newFormatString) // throws UnknownOntologyFormatException { // super(); // OWLOntologyFormat newOntologyFormat; // if (newFormatString.equals("RDF/XML")) // newOntologyFormat = new RDFXMLOntologyFormat(); // else if (newFormatString.equals("OWL/XML")) // newOntologyFormat = new OWLXMLOntologyFormat(); // else if (newFormatString.equals("Turtle")) // newOntologyFormat = new TurtleOntologyFormat(); // else if (newFormatString.equals("OWL Functional Syntax")) // newOntologyFormat = new OWLFunctionalSyntaxOntologyFormat(); // else if (newFormatString.equals("Manchester OWL Syntax")) // newOntologyFormat = new ManchesterOWLSyntaxOntologyFormat(); // else // throw new UnknownOntologyFormatException("Unknown format: " + newFormatString); // this.newFormat = newOntologyFormat; // } // // @Override // public SetOntologyFormat createOntologyChange(OWLOntology ontology) { // if (ontology == null) { // throw new NullPointerException("ontology must not be null"); // } // return new SetOntologyFormat(ontology, newFormat); // } // // public OWLOntologyFormat getNewFormat() { // return newFormat; // } // // @Override // public int hashCode() { // return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (!(obj instanceof SetOntologyFormatData)) { // return false; // } // SetOntologyFormatData other = (SetOntologyFormatData) obj; // return newFormat.equals(other.newFormat); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("SetOntologyFormatData"); // sb.append("(OntologyFormat("); // sb.append(newFormat); // sb.append("))"); // return sb.toString(); // } // // @Override // public <R, E extends Exception> R accept( // CustomOntologyChangeDataVisitor<R, E> visitor) throws E { // return visitor.visit(this); // } // // } // Path: src/main/java/owl2vcs/changeset/MutableChangeSet.java import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.semanticweb.owlapi.change.AxiomChangeData; import org.semanticweb.owlapi.change.ImportChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.SetOntologyIDData; import owl2vcs.changes.PrefixChangeData; import owl2vcs.changes.SetOntologyFormatData; package owl2vcs.changeset; public class MutableChangeSet extends ChangeSet { public MutableChangeSet() { setFormatChange(null);
setPrefixChanges(new HashSet<PrefixChangeData>());
utapyngo/owl2vcs
src/main/java/owl2vcs/changeset/MutableChangeSet.java
// Path: src/main/java/owl2vcs/changes/PrefixChangeData.java // public abstract class PrefixChangeData extends CustomOntologyChangeData { // // private static final long serialVersionUID = -1862023752748180868L; // // private final String prefixName; // private final String prefix; // // public PrefixChangeData(String prefixName, String prefix) { // if (prefixName == null) { // throw new NullPointerException("prefixName must not be null"); // } // if (prefix == null) { // throw new NullPointerException("prefix must not be null"); // } // this.prefixName = prefixName; // this.prefix = prefix; // } // // /** // * @return the prefixName // */ // public String getPrefixName() { // return prefixName; // } // // /** // * @return the prefix // */ // public String getPrefix() { // return prefix; // } // // public Collection<String> getPrefixSignature() { // final Collection<String> sig = new ArrayList<String>(); // sig.add(getPrefixName()); // sig.add(getPrefix()); // return sig; // } // // } // // Path: src/main/java/owl2vcs/changes/SetOntologyFormatData.java // public class SetOntologyFormatData extends CustomOntologyChangeData { // // private static final long serialVersionUID = 4000984588491273026L; // // private final OWLOntologyFormat newFormat; // // public SetOntologyFormatData(OWLOntologyFormat newFormat) { // if (newFormat == null) { // throw new NullPointerException("newFormat must not be null"); // } // this.newFormat = newFormat; // } // // /** // * Creates a set ontology format change, which will set the format of the // * ontology to the specified new format specified as a string. // * // * @param ont // * The ontology whose format is to be changed // * @param newOntologyFormat // * A string representing the new ontology format // * @throws UnknownOntologyFormatException // */ // public SetOntologyFormatData(final String newFormatString) // throws UnknownOntologyFormatException { // super(); // OWLOntologyFormat newOntologyFormat; // if (newFormatString.equals("RDF/XML")) // newOntologyFormat = new RDFXMLOntologyFormat(); // else if (newFormatString.equals("OWL/XML")) // newOntologyFormat = new OWLXMLOntologyFormat(); // else if (newFormatString.equals("Turtle")) // newOntologyFormat = new TurtleOntologyFormat(); // else if (newFormatString.equals("OWL Functional Syntax")) // newOntologyFormat = new OWLFunctionalSyntaxOntologyFormat(); // else if (newFormatString.equals("Manchester OWL Syntax")) // newOntologyFormat = new ManchesterOWLSyntaxOntologyFormat(); // else // throw new UnknownOntologyFormatException("Unknown format: " + newFormatString); // this.newFormat = newOntologyFormat; // } // // @Override // public SetOntologyFormat createOntologyChange(OWLOntology ontology) { // if (ontology == null) { // throw new NullPointerException("ontology must not be null"); // } // return new SetOntologyFormat(ontology, newFormat); // } // // public OWLOntologyFormat getNewFormat() { // return newFormat; // } // // @Override // public int hashCode() { // return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (!(obj instanceof SetOntologyFormatData)) { // return false; // } // SetOntologyFormatData other = (SetOntologyFormatData) obj; // return newFormat.equals(other.newFormat); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("SetOntologyFormatData"); // sb.append("(OntologyFormat("); // sb.append(newFormat); // sb.append("))"); // return sb.toString(); // } // // @Override // public <R, E extends Exception> R accept( // CustomOntologyChangeDataVisitor<R, E> visitor) throws E { // return visitor.visit(this); // } // // }
import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.semanticweb.owlapi.change.AxiomChangeData; import org.semanticweb.owlapi.change.ImportChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.SetOntologyIDData; import owl2vcs.changes.PrefixChangeData; import owl2vcs.changes.SetOntologyFormatData;
package owl2vcs.changeset; public class MutableChangeSet extends ChangeSet { public MutableChangeSet() { setFormatChange(null); setPrefixChanges(new HashSet<PrefixChangeData>()); setOntologyIdChange(null); setImportChanges(new HashSet<ImportChangeData>()); setAnnotationChanges(new HashSet<OWLOntologyChangeData>()); setAxiomChanges(new HashSet<AxiomChangeData>()); } public MutableChangeSet(final ChangeSet cs) { setFormatChange(cs.getFormatChange()); setPrefixChanges(new HashSet<PrefixChangeData>(cs.getPrefixChanges())); setOntologyIdChange(cs.getOntologyIdChange()); setImportChanges(new HashSet<ImportChangeData>(cs.getImportChanges())); setAnnotationChanges(new HashSet<OWLOntologyChangeData>( cs.getAnnotationChanges())); setAxiomChanges(new HashSet<AxiomChangeData>(cs.getAxiomChanges())); }
// Path: src/main/java/owl2vcs/changes/PrefixChangeData.java // public abstract class PrefixChangeData extends CustomOntologyChangeData { // // private static final long serialVersionUID = -1862023752748180868L; // // private final String prefixName; // private final String prefix; // // public PrefixChangeData(String prefixName, String prefix) { // if (prefixName == null) { // throw new NullPointerException("prefixName must not be null"); // } // if (prefix == null) { // throw new NullPointerException("prefix must not be null"); // } // this.prefixName = prefixName; // this.prefix = prefix; // } // // /** // * @return the prefixName // */ // public String getPrefixName() { // return prefixName; // } // // /** // * @return the prefix // */ // public String getPrefix() { // return prefix; // } // // public Collection<String> getPrefixSignature() { // final Collection<String> sig = new ArrayList<String>(); // sig.add(getPrefixName()); // sig.add(getPrefix()); // return sig; // } // // } // // Path: src/main/java/owl2vcs/changes/SetOntologyFormatData.java // public class SetOntologyFormatData extends CustomOntologyChangeData { // // private static final long serialVersionUID = 4000984588491273026L; // // private final OWLOntologyFormat newFormat; // // public SetOntologyFormatData(OWLOntologyFormat newFormat) { // if (newFormat == null) { // throw new NullPointerException("newFormat must not be null"); // } // this.newFormat = newFormat; // } // // /** // * Creates a set ontology format change, which will set the format of the // * ontology to the specified new format specified as a string. // * // * @param ont // * The ontology whose format is to be changed // * @param newOntologyFormat // * A string representing the new ontology format // * @throws UnknownOntologyFormatException // */ // public SetOntologyFormatData(final String newFormatString) // throws UnknownOntologyFormatException { // super(); // OWLOntologyFormat newOntologyFormat; // if (newFormatString.equals("RDF/XML")) // newOntologyFormat = new RDFXMLOntologyFormat(); // else if (newFormatString.equals("OWL/XML")) // newOntologyFormat = new OWLXMLOntologyFormat(); // else if (newFormatString.equals("Turtle")) // newOntologyFormat = new TurtleOntologyFormat(); // else if (newFormatString.equals("OWL Functional Syntax")) // newOntologyFormat = new OWLFunctionalSyntaxOntologyFormat(); // else if (newFormatString.equals("Manchester OWL Syntax")) // newOntologyFormat = new ManchesterOWLSyntaxOntologyFormat(); // else // throw new UnknownOntologyFormatException("Unknown format: " + newFormatString); // this.newFormat = newOntologyFormat; // } // // @Override // public SetOntologyFormat createOntologyChange(OWLOntology ontology) { // if (ontology == null) { // throw new NullPointerException("ontology must not be null"); // } // return new SetOntologyFormat(ontology, newFormat); // } // // public OWLOntologyFormat getNewFormat() { // return newFormat; // } // // @Override // public int hashCode() { // return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (obj == this) { // return true; // } // if (!(obj instanceof SetOntologyFormatData)) { // return false; // } // SetOntologyFormatData other = (SetOntologyFormatData) obj; // return newFormat.equals(other.newFormat); // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("SetOntologyFormatData"); // sb.append("(OntologyFormat("); // sb.append(newFormat); // sb.append("))"); // return sb.toString(); // } // // @Override // public <R, E extends Exception> R accept( // CustomOntologyChangeDataVisitor<R, E> visitor) throws E { // return visitor.visit(this); // } // // } // Path: src/main/java/owl2vcs/changeset/MutableChangeSet.java import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.semanticweb.owlapi.change.AxiomChangeData; import org.semanticweb.owlapi.change.ImportChangeData; import org.semanticweb.owlapi.change.OWLOntologyChangeData; import org.semanticweb.owlapi.change.SetOntologyIDData; import owl2vcs.changes.PrefixChangeData; import owl2vcs.changes.SetOntologyFormatData; package owl2vcs.changeset; public class MutableChangeSet extends ChangeSet { public MutableChangeSet() { setFormatChange(null); setPrefixChanges(new HashSet<PrefixChangeData>()); setOntologyIdChange(null); setImportChanges(new HashSet<ImportChangeData>()); setAnnotationChanges(new HashSet<OWLOntologyChangeData>()); setAxiomChanges(new HashSet<AxiomChangeData>()); } public MutableChangeSet(final ChangeSet cs) { setFormatChange(cs.getFormatChange()); setPrefixChanges(new HashSet<PrefixChangeData>(cs.getPrefixChanges())); setOntologyIdChange(cs.getOntologyIdChange()); setImportChanges(new HashSet<ImportChangeData>(cs.getImportChanges())); setAnnotationChanges(new HashSet<OWLOntologyChangeData>( cs.getAnnotationChanges())); setAxiomChanges(new HashSet<AxiomChangeData>(cs.getAxiomChanges())); }
public MutableChangeSet(final SetOntologyFormatData formatChange,
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/SetOntologyFormatData.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // }
import org.coode.owlapi.manchesterowlsyntax.ManchesterOWLSyntaxOntologyFormat; import org.coode.owlapi.turtle.TurtleOntologyFormat; import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat; import org.semanticweb.owlapi.io.OWLXMLOntologyFormat; import org.semanticweb.owlapi.io.RDFXMLOntologyFormat; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owl2vcs.changeset.CustomOntologyChangeDataVisitor;
@Override public int hashCode() { return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SetOntologyFormatData)) { return false; } SetOntologyFormatData other = (SetOntologyFormatData) obj; return newFormat.equals(other.newFormat); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SetOntologyFormatData"); sb.append("(OntologyFormat("); sb.append(newFormat); sb.append("))"); return sb.toString(); } @Override public <R, E extends Exception> R accept(
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeDataVisitor.java // public interface CustomOntologyChangeDataVisitor<R, E extends Exception> // extends OWLOntologyChangeDataVisitor<R, E> { // // R visit(SetOntologyFormatData data) throws E; // // R visit(AddPrefixData data) throws E; // // R visit(RemovePrefixData data) throws E; // // R visit(ModifyPrefixData data) throws E; // // R visit(RenamePrefixData data) throws E; // } // Path: src/main/java/owl2vcs/changes/SetOntologyFormatData.java import org.coode.owlapi.manchesterowlsyntax.ManchesterOWLSyntaxOntologyFormat; import org.coode.owlapi.turtle.TurtleOntologyFormat; import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat; import org.semanticweb.owlapi.io.OWLXMLOntologyFormat; import org.semanticweb.owlapi.io.RDFXMLOntologyFormat; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyFormat; import owl2vcs.changeset.CustomOntologyChangeDataVisitor; @Override public int hashCode() { return "SetOntologyFormatData".hashCode() + newFormat.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SetOntologyFormatData)) { return false; } SetOntologyFormatData other = (SetOntologyFormatData) obj; return newFormat.equals(other.newFormat); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SetOntologyFormatData"); sb.append("(OntologyFormat("); sb.append(newFormat); sb.append("))"); return sb.toString(); } @Override public <R, E extends Exception> R accept(
CustomOntologyChangeDataVisitor<R, E> visitor) throws E {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/RenamePrefix.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor;
+ ((oldPrefixName == null) ? 0 : oldPrefixName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RenamePrefix)) return false; RenamePrefix other = (RenamePrefix) obj; if (oldPrefixName == null) { if (other.oldPrefixName != null) return false; } else if (!oldPrefixName.equals(other.oldPrefixName)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RENAME PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/RenamePrefix.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor; + ((oldPrefixName == null) ? 0 : oldPrefixName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof RenamePrefix)) return false; RenamePrefix other = (RenamePrefix) obj; if (oldPrefixName == null) { if (other.oldPrefixName != null) return false; } else if (!oldPrefixName.equals(other.oldPrefixName)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RENAME PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
public void accept(final CustomOntologyChangeVisitor visitor) {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/CustomOntologyChange.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import java.util.Collections; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import org.semanticweb.owlapi.model.OWLOntologyChangeVisitor; import org.semanticweb.owlapi.model.OWLOntologyChangeVisitorEx; import owl2vcs.changeset.CustomOntologyChangeVisitor;
package owl2vcs.changes; public abstract class CustomOntologyChange extends OWLOntologyChange { public CustomOntologyChange(final OWLOntology ont) { super(ont); }
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/CustomOntologyChange.java import java.util.Collections; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import org.semanticweb.owlapi.model.OWLOntologyChangeVisitor; import org.semanticweb.owlapi.model.OWLOntologyChangeVisitorEx; import owl2vcs.changeset.CustomOntologyChangeVisitor; package owl2vcs.changes; public abstract class CustomOntologyChange extends OWLOntologyChange { public CustomOntologyChange(final OWLOntology ont) { super(ont); }
public abstract void accept(CustomOntologyChangeVisitor visitor);
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/ModifyPrefix.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor;
return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((oldPrefix == null) ? 0 : oldPrefix.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ModifyPrefix)) return false; ModifyPrefix other = (ModifyPrefix) obj; if (oldPrefix == null) { if (other.oldPrefix != null) return false; } else if (!oldPrefix.equals(other.oldPrefix)) return false; return true; } @Override
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/ModifyPrefix.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor; return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((oldPrefix == null) ? 0 : oldPrefix.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ModifyPrefix)) return false; ModifyPrefix other = (ModifyPrefix) obj; if (oldPrefix == null) { if (other.oldPrefix != null) return false; } else if (!oldPrefix.equals(other.oldPrefix)) return false; return true; } @Override
public void accept(final CustomOntologyChangeVisitor visitor) {
utapyngo/owl2vcs
src/main/java/owl2vcs/changes/AddPrefix.java
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // }
import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor;
package owl2vcs.changes; public class AddPrefix extends PrefixChange { public AddPrefix(final OWLOntology ont, final String prefixName, final String prefix) { super(ont, prefixName, prefix); } @Override public int hashCode() { final int prime = 2; return prime * super.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof AddPrefix)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ADD PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
// Path: src/main/java/owl2vcs/changeset/CustomOntologyChangeVisitor.java // public interface CustomOntologyChangeVisitor extends OWLOntologyChangeVisitor { // // void visit(SetOntologyFormat change); // // void visit(AddPrefix change); // // void visit(RemovePrefix change); // // void visit(ModifyPrefix change); // // void visit(RenamePrefix change); // } // Path: src/main/java/owl2vcs/changes/AddPrefix.java import org.semanticweb.owlapi.model.OWLOntology; import owl2vcs.changeset.CustomOntologyChangeVisitor; package owl2vcs.changes; public class AddPrefix extends PrefixChange { public AddPrefix(final OWLOntology ont, final String prefixName, final String prefix) { super(ont, prefixName, prefix); } @Override public int hashCode() { final int prime = 2; return prime * super.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof AddPrefix)) return false; return true; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ADD PREFIX: "); sb.append(getPrefixName().toString() + "=" + getPrefix().toString()); return sb.toString(); } @Override
public void accept(final CustomOntologyChangeVisitor visitor) {
Talon876/RSIRCBot
src/org/nolat/rsircbot/data/HiscoreData.java
// Path: src/org/nolat/rsircbot/tools/Calculate.java // public class Calculate { // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // public static int levelFromXp(int xp) { // for (int i = 1; i <= 120; i++) { // if (xpForLevel(i) > xp) { // return i - 1; // } // } // return -1; // } // // public static int xpUntilLevelUp(int xp) { // int level = levelFromXp(xp); // int xpForNextLevel = xpForLevel(level + 1); // return xpForNextLevel - xp; // } // // public static int combatLevelRounded(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // return (int) combatLevel(atk, str, def, prayer, range, magic, hp); // } // // public static double combatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import org.nolat.rsircbot.tools.Calculate;
if (tokens.length == 3) { RankLevelXp rlx = new RankLevelXp(tokens[0], tokens[1], tokens[2]); if (c <= skillNames.length) { hiscores.put(skillNames[c], rlx); } c++; } } } catch (IOException ex) { ex.printStackTrace(); } finally { if (in != null) { in.close(); } } } public RankLevelXp getDataForSkill(String skill) { return hiscores.get(skill.toLowerCase()); } public double getCombatLevel() { int atk = hiscores.get("attack").getLevel(); int str = hiscores.get("strength").getLevel(); int def = hiscores.get("defence").getLevel(); int prayer = hiscores.get("prayer").getLevel(); int range = hiscores.get("ranged").getLevel(); int magic = hiscores.get("magic").getLevel(); int hp = hiscores.get("hitpoints").getLevel();
// Path: src/org/nolat/rsircbot/tools/Calculate.java // public class Calculate { // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // public static int levelFromXp(int xp) { // for (int i = 1; i <= 120; i++) { // if (xpForLevel(i) > xp) { // return i - 1; // } // } // return -1; // } // // public static int xpUntilLevelUp(int xp) { // int level = levelFromXp(xp); // int xpForNextLevel = xpForLevel(level + 1); // return xpForNextLevel - xp; // } // // public static int combatLevelRounded(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // return (int) combatLevel(atk, str, def, prayer, range, magic, hp); // } // // public static double combatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // } // Path: src/org/nolat/rsircbot/data/HiscoreData.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import org.nolat.rsircbot.tools.Calculate; if (tokens.length == 3) { RankLevelXp rlx = new RankLevelXp(tokens[0], tokens[1], tokens[2]); if (c <= skillNames.length) { hiscores.put(skillNames[c], rlx); } c++; } } } catch (IOException ex) { ex.printStackTrace(); } finally { if (in != null) { in.close(); } } } public RankLevelXp getDataForSkill(String skill) { return hiscores.get(skill.toLowerCase()); } public double getCombatLevel() { int atk = hiscores.get("attack").getLevel(); int str = hiscores.get("strength").getLevel(); int def = hiscores.get("defence").getLevel(); int prayer = hiscores.get("prayer").getLevel(); int range = hiscores.get("ranged").getLevel(); int magic = hiscores.get("magic").getLevel(); int hp = hiscores.get("hitpoints").getLevel();
return Calculate.combatLevel(atk, str, def, prayer, range, magic, hp);
Talon876/RSIRCBot
src/org/nolat/rsircbot/tools/WitQuery.java
// Path: src/org/nolat/rsircbot/tools/json/WitResponse.java // public class WitResponse { // // @SerializedName("msg_id") // private String msgId; // // @SerializedName("msg_body") // private String msgBody; // // @SerializedName("outcome") // private WitOutcome outcome; // // public class WitOutcome { // // @SerializedName("intent") // private String intent; // // @SerializedName("confidence") // private double confidence; // // @SerializedName("entities") // private Map<String, JsonObject> entities; // // public String getIntent() { // // return intent; // } // public double getConfidence() { // return confidence; // } // // public Map<String, JsonObject> getEntities() { // return entities; // } // // public JsonObject getEntity(String entity) { // return entities.get(entity); // } // // public String getFirstEntityValueOr(String entity, String defaultValue) { // // JsonObject ent = entities.get(entity); // if(ent == null) { // return defaultValue; // } // // if(ent.getAsJsonObject() == null) { // System.out.println("json entity object was null"); // } // if(ent.getAsJsonArray() == null) { // System.out.println("json entity array was null"); // } // // return ent.get("value").getAsString(); // } // // @Override // public String toString() { // return "Intent: [" + getIntent() + "]"; // } // // // // /** // // * Get the value of an entity or return a default value // // * @param entity the key to check the entities for // // * @param otherwise if the key doesn't have a value, use this as the default // // * @return entities[entity] or otherwise if null // // */ // // public String getEntityValueOr(int idx, String entity, String otherwise) { // // Entity ent = getEntity(entity).get(idx); // // if(ent == null) { // // return otherwise; // // } else { // // return ent.getValue(); // // } // // } // // // // public String getFirstEntityValueOr(String entity, String otherwise) { // // return getEntityValueOr(0, entity, otherwise); // // } // // // // public List<Entity> getEntity(String entity) { // // return entities.get(entity); // // } // // // // public Entity getFirstEntity(String entity) { // // return entities.get(entity).get(0); // // } // // } // // // public class Entity { // // public int end; // // public int start; // // public String value; // // public String body; // // // // public int getEnd() { // // return end; // // } // // // // public int getStart() { // // return start; // // } // // // // public String getValue() { // // return value; // // } // // // // public String getBody() { // // return body; // // } // // // // @Override // // public String toString() { // // return "{" + body + " as " + value + "}"; // // } // // } // // public String getMsgId() { // return msgId; // } // // public String getMsgBody() { // return msgBody; // } // // public WitOutcome getOutcome() { // return outcome; // } // // }
import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import org.apache.commons.io.IOUtils; import org.nolat.rsircbot.tools.json.WitResponse; import com.google.gson.Gson;
package org.nolat.rsircbot.tools; public class WitQuery { private final String WIT_URL = "https://api.wit.ai/message?q="; private final String AUTHORIZATION_HEADER = "Authorization"; private final String BEARER_FORMAT = "Bearer %s"; private final String witToken; private final String query; private final String rawOutput;
// Path: src/org/nolat/rsircbot/tools/json/WitResponse.java // public class WitResponse { // // @SerializedName("msg_id") // private String msgId; // // @SerializedName("msg_body") // private String msgBody; // // @SerializedName("outcome") // private WitOutcome outcome; // // public class WitOutcome { // // @SerializedName("intent") // private String intent; // // @SerializedName("confidence") // private double confidence; // // @SerializedName("entities") // private Map<String, JsonObject> entities; // // public String getIntent() { // // return intent; // } // public double getConfidence() { // return confidence; // } // // public Map<String, JsonObject> getEntities() { // return entities; // } // // public JsonObject getEntity(String entity) { // return entities.get(entity); // } // // public String getFirstEntityValueOr(String entity, String defaultValue) { // // JsonObject ent = entities.get(entity); // if(ent == null) { // return defaultValue; // } // // if(ent.getAsJsonObject() == null) { // System.out.println("json entity object was null"); // } // if(ent.getAsJsonArray() == null) { // System.out.println("json entity array was null"); // } // // return ent.get("value").getAsString(); // } // // @Override // public String toString() { // return "Intent: [" + getIntent() + "]"; // } // // // // /** // // * Get the value of an entity or return a default value // // * @param entity the key to check the entities for // // * @param otherwise if the key doesn't have a value, use this as the default // // * @return entities[entity] or otherwise if null // // */ // // public String getEntityValueOr(int idx, String entity, String otherwise) { // // Entity ent = getEntity(entity).get(idx); // // if(ent == null) { // // return otherwise; // // } else { // // return ent.getValue(); // // } // // } // // // // public String getFirstEntityValueOr(String entity, String otherwise) { // // return getEntityValueOr(0, entity, otherwise); // // } // // // // public List<Entity> getEntity(String entity) { // // return entities.get(entity); // // } // // // // public Entity getFirstEntity(String entity) { // // return entities.get(entity).get(0); // // } // // } // // // public class Entity { // // public int end; // // public int start; // // public String value; // // public String body; // // // // public int getEnd() { // // return end; // // } // // // // public int getStart() { // // return start; // // } // // // // public String getValue() { // // return value; // // } // // // // public String getBody() { // // return body; // // } // // // // @Override // // public String toString() { // // return "{" + body + " as " + value + "}"; // // } // // } // // public String getMsgId() { // return msgId; // } // // public String getMsgBody() { // return msgBody; // } // // public WitOutcome getOutcome() { // return outcome; // } // // } // Path: src/org/nolat/rsircbot/tools/WitQuery.java import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import org.apache.commons.io.IOUtils; import org.nolat.rsircbot.tools.json.WitResponse; import com.google.gson.Gson; package org.nolat.rsircbot.tools; public class WitQuery { private final String WIT_URL = "https://api.wit.ai/message?q="; private final String AUTHORIZATION_HEADER = "Authorization"; private final String BEARER_FORMAT = "Bearer %s"; private final String witToken; private final String query; private final String rawOutput;
private final WitResponse witResponse;
Talon876/RSIRCBot
src/org/nolat/rsircbot/data/ItemSearch.java
// Path: src/org/nolat/rsircbot/data/json/ItemData.java // public class ItemData { // String average; // String high_alch; // List<HistoryData> history; // String id; // String image; // String name; // List<OfferData> offers; // String recent_high; // String recent_low; // // public int getHighAlchValue() { // return Integer.parseInt(high_alch); // } // // public String getHighAlchString() { // return RSFormatter.format(high_alch); // } // // public String getPriceString() { // return RSFormatter.format(average); // } // // public int getPriceValue() { // return (int) Double.parseDouble(average); // } // // public List<HistoryData> getHistory() { // return history; // } // // public String getName() { // return name; // } // // public List<OfferData> getOffers() { // return offers; // } // // public List<OfferData> getRecentOffers(int hours) { // List<OfferData> recentOffers = new ArrayList<OfferData>(); // for (OfferData od : getOffers()) { // if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) { // recentOffers.add(od); // } // } // return recentOffers; // } // // public List<OfferData> getRecentBuyers(int hours) { // List<OfferData> buyers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (!od.isSelling()) { // buyers.add(od); // } // } // return buyers; // } // // public List<OfferData> getRecentSellers(int hours) { // List<OfferData> sellers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (od.isSelling()) { // sellers.add(od); // } // } // return sellers; // } // // public String getRecentHighString() { // return RSFormatter.format(recent_high); // } // // public String getRecentLowString() { // return RSFormatter.format(recent_low); // } // } // // Path: src/org/nolat/rsircbot/tools/URLReader.java // public class URLReader { // // public static String readUrl(String urlString) throws Exception { // BufferedReader reader = null; // StringBuffer buffer = new StringBuffer(); // try { // URL url = new URL(urlString); // URLConnection connection = url.openConnection(); // connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " + // "AppleWebKit/537.11 (KHTML, like Gecko) " + // "Chrome/23.0.1271.95 " + // "Safari/537.11"); // // reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while ((line = reader.readLine()) != null) { // buffer.append(line); // } // // } finally { // if (reader != null) { // reader.close(); // } // } // // return buffer.toString(); // } // }
import java.util.HashMap; import org.nolat.rsircbot.data.json.ItemData; import org.nolat.rsircbot.tools.URLReader; import com.google.gson.Gson;
package org.nolat.rsircbot.data; public class ItemSearch { private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/"; private String item;
// Path: src/org/nolat/rsircbot/data/json/ItemData.java // public class ItemData { // String average; // String high_alch; // List<HistoryData> history; // String id; // String image; // String name; // List<OfferData> offers; // String recent_high; // String recent_low; // // public int getHighAlchValue() { // return Integer.parseInt(high_alch); // } // // public String getHighAlchString() { // return RSFormatter.format(high_alch); // } // // public String getPriceString() { // return RSFormatter.format(average); // } // // public int getPriceValue() { // return (int) Double.parseDouble(average); // } // // public List<HistoryData> getHistory() { // return history; // } // // public String getName() { // return name; // } // // public List<OfferData> getOffers() { // return offers; // } // // public List<OfferData> getRecentOffers(int hours) { // List<OfferData> recentOffers = new ArrayList<OfferData>(); // for (OfferData od : getOffers()) { // if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) { // recentOffers.add(od); // } // } // return recentOffers; // } // // public List<OfferData> getRecentBuyers(int hours) { // List<OfferData> buyers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (!od.isSelling()) { // buyers.add(od); // } // } // return buyers; // } // // public List<OfferData> getRecentSellers(int hours) { // List<OfferData> sellers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (od.isSelling()) { // sellers.add(od); // } // } // return sellers; // } // // public String getRecentHighString() { // return RSFormatter.format(recent_high); // } // // public String getRecentLowString() { // return RSFormatter.format(recent_low); // } // } // // Path: src/org/nolat/rsircbot/tools/URLReader.java // public class URLReader { // // public static String readUrl(String urlString) throws Exception { // BufferedReader reader = null; // StringBuffer buffer = new StringBuffer(); // try { // URL url = new URL(urlString); // URLConnection connection = url.openConnection(); // connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " + // "AppleWebKit/537.11 (KHTML, like Gecko) " + // "Chrome/23.0.1271.95 " + // "Safari/537.11"); // // reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while ((line = reader.readLine()) != null) { // buffer.append(line); // } // // } finally { // if (reader != null) { // reader.close(); // } // } // // return buffer.toString(); // } // } // Path: src/org/nolat/rsircbot/data/ItemSearch.java import java.util.HashMap; import org.nolat.rsircbot.data.json.ItemData; import org.nolat.rsircbot.tools.URLReader; import com.google.gson.Gson; package org.nolat.rsircbot.data; public class ItemSearch { private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/"; private String item;
ItemData[] results;
Talon876/RSIRCBot
src/org/nolat/rsircbot/data/ItemSearch.java
// Path: src/org/nolat/rsircbot/data/json/ItemData.java // public class ItemData { // String average; // String high_alch; // List<HistoryData> history; // String id; // String image; // String name; // List<OfferData> offers; // String recent_high; // String recent_low; // // public int getHighAlchValue() { // return Integer.parseInt(high_alch); // } // // public String getHighAlchString() { // return RSFormatter.format(high_alch); // } // // public String getPriceString() { // return RSFormatter.format(average); // } // // public int getPriceValue() { // return (int) Double.parseDouble(average); // } // // public List<HistoryData> getHistory() { // return history; // } // // public String getName() { // return name; // } // // public List<OfferData> getOffers() { // return offers; // } // // public List<OfferData> getRecentOffers(int hours) { // List<OfferData> recentOffers = new ArrayList<OfferData>(); // for (OfferData od : getOffers()) { // if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) { // recentOffers.add(od); // } // } // return recentOffers; // } // // public List<OfferData> getRecentBuyers(int hours) { // List<OfferData> buyers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (!od.isSelling()) { // buyers.add(od); // } // } // return buyers; // } // // public List<OfferData> getRecentSellers(int hours) { // List<OfferData> sellers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (od.isSelling()) { // sellers.add(od); // } // } // return sellers; // } // // public String getRecentHighString() { // return RSFormatter.format(recent_high); // } // // public String getRecentLowString() { // return RSFormatter.format(recent_low); // } // } // // Path: src/org/nolat/rsircbot/tools/URLReader.java // public class URLReader { // // public static String readUrl(String urlString) throws Exception { // BufferedReader reader = null; // StringBuffer buffer = new StringBuffer(); // try { // URL url = new URL(urlString); // URLConnection connection = url.openConnection(); // connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " + // "AppleWebKit/537.11 (KHTML, like Gecko) " + // "Chrome/23.0.1271.95 " + // "Safari/537.11"); // // reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while ((line = reader.readLine()) != null) { // buffer.append(line); // } // // } finally { // if (reader != null) { // reader.close(); // } // } // // return buffer.toString(); // } // }
import java.util.HashMap; import org.nolat.rsircbot.data.json.ItemData; import org.nolat.rsircbot.tools.URLReader; import com.google.gson.Gson;
package org.nolat.rsircbot.data; public class ItemSearch { private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/"; private String item; ItemData[] results; public ItemSearch(String item) throws LookupException { this.item = item.replaceAll(" ", "_").replaceAll("'", "_"); refreshData(); } public void refreshData() throws LookupException { String jsonData = null; boolean failed = false; try {
// Path: src/org/nolat/rsircbot/data/json/ItemData.java // public class ItemData { // String average; // String high_alch; // List<HistoryData> history; // String id; // String image; // String name; // List<OfferData> offers; // String recent_high; // String recent_low; // // public int getHighAlchValue() { // return Integer.parseInt(high_alch); // } // // public String getHighAlchString() { // return RSFormatter.format(high_alch); // } // // public String getPriceString() { // return RSFormatter.format(average); // } // // public int getPriceValue() { // return (int) Double.parseDouble(average); // } // // public List<HistoryData> getHistory() { // return history; // } // // public String getName() { // return name; // } // // public List<OfferData> getOffers() { // return offers; // } // // public List<OfferData> getRecentOffers(int hours) { // List<OfferData> recentOffers = new ArrayList<OfferData>(); // for (OfferData od : getOffers()) { // if (od.msSincePosted() <= TimeUtils.ONE_HOUR * hours) { // recentOffers.add(od); // } // } // return recentOffers; // } // // public List<OfferData> getRecentBuyers(int hours) { // List<OfferData> buyers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (!od.isSelling()) { // buyers.add(od); // } // } // return buyers; // } // // public List<OfferData> getRecentSellers(int hours) { // List<OfferData> sellers = new ArrayList<OfferData>(); // for (OfferData od : getRecentOffers(hours)) { // if (od.isSelling()) { // sellers.add(od); // } // } // return sellers; // } // // public String getRecentHighString() { // return RSFormatter.format(recent_high); // } // // public String getRecentLowString() { // return RSFormatter.format(recent_low); // } // } // // Path: src/org/nolat/rsircbot/tools/URLReader.java // public class URLReader { // // public static String readUrl(String urlString) throws Exception { // BufferedReader reader = null; // StringBuffer buffer = new StringBuffer(); // try { // URL url = new URL(urlString); // URLConnection connection = url.openConnection(); // connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) " + // "AppleWebKit/537.11 (KHTML, like Gecko) " + // "Chrome/23.0.1271.95 " + // "Safari/537.11"); // // reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while ((line = reader.readLine()) != null) { // buffer.append(line); // } // // } finally { // if (reader != null) { // reader.close(); // } // } // // return buffer.toString(); // } // } // Path: src/org/nolat/rsircbot/data/ItemSearch.java import java.util.HashMap; import org.nolat.rsircbot.data.json.ItemData; import org.nolat.rsircbot.tools.URLReader; import com.google.gson.Gson; package org.nolat.rsircbot.data; public class ItemSearch { private static final String baseUrl = "http://forums.zybez.net/runescape-2007-prices/api/"; private String item; ItemData[] results; public ItemSearch(String item) throws LookupException { this.item = item.replaceAll(" ", "_").replaceAll("'", "_"); refreshData(); } public void refreshData() throws LookupException { String jsonData = null; boolean failed = false; try {
jsonData = URLReader.readUrl(baseUrl + item);
Talon876/RSIRCBot
src/org/nolat/rsircbot/data/RankLevelXp.java
// Path: src/org/nolat/rsircbot/tools/RSFormatter.java // public class RSFormatter { // public static final DecimalFormat formatter = new DecimalFormat("#,###"); // // public static String format(int num) { // return formatter.format(num); // } // // public static String format(double num) { // return formatter.format(num); // } // // public static String format(String string) { // return format(Float.parseFloat(string)); // } // }
import org.nolat.rsircbot.tools.RSFormatter;
package org.nolat.rsircbot.data; public class RankLevelXp { private String rank; private String level; private String xp; public RankLevelXp(String rank, String level, String xp) { this.rank = rank; this.level = level; this.xp = xp; } public int getRank() { return Integer.parseInt(rank); } public int getLevel() { return Integer.parseInt(level); } public int getXp() { return Integer.parseInt(xp); } public String getRankString() {
// Path: src/org/nolat/rsircbot/tools/RSFormatter.java // public class RSFormatter { // public static final DecimalFormat formatter = new DecimalFormat("#,###"); // // public static String format(int num) { // return formatter.format(num); // } // // public static String format(double num) { // return formatter.format(num); // } // // public static String format(String string) { // return format(Float.parseFloat(string)); // } // } // Path: src/org/nolat/rsircbot/data/RankLevelXp.java import org.nolat.rsircbot.tools.RSFormatter; package org.nolat.rsircbot.data; public class RankLevelXp { private String rank; private String level; private String xp; public RankLevelXp(String rank, String level, String xp) { this.rank = rank; this.level = level; this.xp = xp; } public int getRank() { return Integer.parseInt(rank); } public int getLevel() { return Integer.parseInt(level); } public int getXp() { return Integer.parseInt(xp); } public String getRankString() {
return RSFormatter.format(getRank());