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
Sch3lp/ProductivityWithShortcuts
src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // }
import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository;
package be.swsb.productivity.chapter2.mud.service; public class BallServiceImpl implements BallService { private BallRepository ballRepository; private BallTOAssembler ballTOAssembler; public BallServiceImpl(BallRepository ballRepository) { this.ballRepository = ballRepository; } @Override public BallTO findBall(String id) {
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; package be.swsb.productivity.chapter2.mud.service; public class BallServiceImpl implements BallService { private BallRepository ballRepository; private BallTOAssembler ballTOAssembler; public BallServiceImpl(BallRepository ballRepository) { this.ballRepository = ballRepository; } @Override public BallTO findBall(String id) {
Ball ball = ballRepository.lookupById(id);
Sch3lp/ProductivityWithShortcuts
src/main/java/be/swsb/productivity/chapter1/indentation/Fugly.java
// Path: src/main/java/be/swsb/productivity/common/FaceTestBuilder.java // public static FaceTestBuilder face(){ // return new FaceTestBuilder(); // } // // Path: src/main/java/be/swsb/productivity/common/FuglyTestBuilder.java // public static FuglyTestBuilder fugly(){ // return new FuglyTestBuilder(); // }
import static be.swsb.productivity.common.FaceTestBuilder.face; import static be.swsb.productivity.common.FuglyTestBuilder.fugly;
package be.swsb.productivity.chapter1.indentation; public class Fugly { public static void indentMeProperlyPlease() {
// Path: src/main/java/be/swsb/productivity/common/FaceTestBuilder.java // public static FaceTestBuilder face(){ // return new FaceTestBuilder(); // } // // Path: src/main/java/be/swsb/productivity/common/FuglyTestBuilder.java // public static FuglyTestBuilder fugly(){ // return new FuglyTestBuilder(); // } // Path: src/main/java/be/swsb/productivity/chapter1/indentation/Fugly.java import static be.swsb.productivity.common.FaceTestBuilder.face; import static be.swsb.productivity.common.FuglyTestBuilder.fugly; package be.swsb.productivity.chapter1.indentation; public class Fugly { public static void indentMeProperlyPlease() {
System.out.println(fugly().withEff("f").withYew("u").withGee("g").withEll("l").withYew("y").withFace(face().withEyes(1).withColor("poop-brown").withNosewidth(500).build()).build().toString());
Sch3lp/ProductivityWithShortcuts
src/main/java/be/swsb/productivity/chapter1/indentation/Fugly.java
// Path: src/main/java/be/swsb/productivity/common/FaceTestBuilder.java // public static FaceTestBuilder face(){ // return new FaceTestBuilder(); // } // // Path: src/main/java/be/swsb/productivity/common/FuglyTestBuilder.java // public static FuglyTestBuilder fugly(){ // return new FuglyTestBuilder(); // }
import static be.swsb.productivity.common.FaceTestBuilder.face; import static be.swsb.productivity.common.FuglyTestBuilder.fugly;
package be.swsb.productivity.chapter1.indentation; public class Fugly { public static void indentMeProperlyPlease() {
// Path: src/main/java/be/swsb/productivity/common/FaceTestBuilder.java // public static FaceTestBuilder face(){ // return new FaceTestBuilder(); // } // // Path: src/main/java/be/swsb/productivity/common/FuglyTestBuilder.java // public static FuglyTestBuilder fugly(){ // return new FuglyTestBuilder(); // } // Path: src/main/java/be/swsb/productivity/chapter1/indentation/Fugly.java import static be.swsb.productivity.common.FaceTestBuilder.face; import static be.swsb.productivity.common.FuglyTestBuilder.fugly; package be.swsb.productivity.chapter1.indentation; public class Fugly { public static void indentMeProperlyPlease() {
System.out.println(fugly().withEff("f").withYew("u").withGee("g").withEll("l").withYew("y").withFace(face().withEyes(1).withColor("poop-brown").withNosewidth(500).build()).build().toString());
Sch3lp/ProductivityWithShortcuts
src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // }
import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays;
package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception {
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // } // Path: src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays; package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception {
new BallScreen(new BallServiceImpl(new BallRepository())).render();
Sch3lp/ProductivityWithShortcuts
src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // }
import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays;
package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception {
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // } // Path: src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays; package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception {
new BallScreen(new BallServiceImpl(new BallRepository())).render();
Sch3lp/ProductivityWithShortcuts
src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // }
import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays;
package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception { new BallScreen(new BallServiceImpl(new BallRepository())).render(); } @Test public void compareTest() throws Exception {
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // } // Path: src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays; package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception { new BallScreen(new BallServiceImpl(new BallRepository())).render(); } @Test public void compareTest() throws Exception {
Arrays.asList(new Ball("1", 100), new RealBall("1",100));
Sch3lp/ProductivityWithShortcuts
src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // }
import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays;
package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception { new BallScreen(new BallServiceImpl(new BallRepository())).render(); } @Test public void compareTest() throws Exception {
// Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/Ball.java // public class Ball { // private final String id; // private final int size; // // public Ball(String id, int size) { // this.id = id; // this.size = size; // } // // public String getId() { // return id; // } // // public int getSize() { // return size; // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Ball ball = (Ball) o; // // if (size != ball.size) return false; // return id != null ? id.equals(ball.id) : ball.id == null; // // } // // @Override // public int hashCode() { // int result = id != null ? id.hashCode() : 0; // result = 31 * result + size; // return result; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/BallRepository.java // public class BallRepository { // // public Ball lookupById(String id) { // // return new Ball(id, 10); // return null; // } // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/domain/RealBall.java // public class RealBall extends Ball { // // public RealBall(String id, int size) { // super(id, size); // } // // public void bounce(){ // System.out.println("bounce"); // } // // public void smash(){ // System.out.println("smash"); // } // // public void hit(){ // System.out.println("hit"); // } // // public void dribble(){ // System.out.println("dribble"); // } // // public void kick(){ // System.out.println("kick"); // } // // public void shoot(){ // System.out.println("shoot"); // } // // public void throwww(){ // System.out.println("throwww"); // } // // public void squeeze(){ // System.out.println("squeeze"); // } // // public void roll(){ // System.out.println("roll"); // } // // public void destroy(){ // System.out.println("destroy"); // } // // public void collect(){ // System.out.println("collect"); // } // // public void launch(){ // System.out.println("launch"); // } // // public void drizzle(){ // System.out.println("drizzle"); // } // // public void hoop(){ // System.out.println("hoop"); // } // // public void net(){ // System.out.println("net"); // } // // public void score(){ // System.out.println("score"); // } // // public void supersmash(){ // System.out.println("supersmash"); // } // // public void assemble(){ // System.out.println("assemble"); // } // // public void complete(){ // System.out.println("complete"); // } // // } // // Path: src/main/java/be/swsb/productivity/chapter2/mud/service/BallServiceImpl.java // public class BallServiceImpl implements BallService { // // private BallRepository ballRepository; // private BallTOAssembler ballTOAssembler; // // public BallServiceImpl(BallRepository ballRepository) { // this.ballRepository = ballRepository; // } // // @Override // public BallTO findBall(String id) { // Ball ball = ballRepository.lookupById(id); // return ballTOAssembler.assembleTOFrom(ball); // } // } // Path: src/test/java/be/swsb/productivity/chapter2/mud/ui/BallScreenTest.java import be.swsb.productivity.chapter2.mud.domain.Ball; import be.swsb.productivity.chapter2.mud.domain.BallRepository; import be.swsb.productivity.chapter2.mud.domain.RealBall; import be.swsb.productivity.chapter2.mud.service.BallServiceImpl; import org.junit.Test; import java.util.Arrays; package be.swsb.productivity.chapter2.mud.ui; public class BallScreenTest { @Test public void screenCallsStuffToGenerateStackTrace() throws Exception { new BallScreen(new BallServiceImpl(new BallRepository())).render(); } @Test public void compareTest() throws Exception {
Arrays.asList(new Ball("1", 100), new RealBall("1",100));
Sch3lp/ProductivityWithShortcuts
src/test/java/be/swsb/productivity/chapter8/listasserts/StatusTest.java
// Path: src/main/java/be/swsb/productivity/chapter8/listasserts/Status.java // enum Status { // // READY(NOT_REALLY), // DONE(YA_REALLY), // WAITING(O_REALLY), // SOMEWHAT_READY(NOT_REALLY), // DUNNO(YA_REALLY), // NOT_READY(NOT_REALLY), // WHATEVER(YA_REALLY), // NOT_READY_AT_ALL(NOT_REALLY), // ; // // private SubStatus subStatus; // // Status(SubStatus subStatus) { // this.subStatus = subStatus; // } // // public static List<Status> oReallyStatuses() { // return Stream.of(values()).filter(Status::isOReally).collect(Collectors.toList()); // } // // public static List<Status> yaReallyStatuses() { // return Stream.of(values()).filter(Status::isYaReally).collect(Collectors.toList()); // } // // public static List<Status> notReallyStatuses() { // return Stream.of(values()).filter(Status::isNotReally).collect(Collectors.toList()); // } // // public SubStatus getSubStatus() { // return subStatus; // } // // private boolean isOReally() { // return SubStatus.O_REALLY.equals(getSubStatus()); // } // private boolean isYaReally() { // return SubStatus.YA_REALLY.equals(getSubStatus()); // } // // private boolean isNotReally() { // return SubStatus.NOT_REALLY.equals(getSubStatus()); // } // // enum SubStatus { // NOT_REALLY, // O_REALLY, // YA_REALLY // } // }
import org.junit.Test; import static be.swsb.productivity.chapter8.listasserts.Status.*; import static org.assertj.core.api.Assertions.assertThat;
package be.swsb.productivity.chapter8.listasserts; public class StatusTest { @Test public void oReallyStatuses_ContainsOnlyWAITING() throws Exception {
// Path: src/main/java/be/swsb/productivity/chapter8/listasserts/Status.java // enum Status { // // READY(NOT_REALLY), // DONE(YA_REALLY), // WAITING(O_REALLY), // SOMEWHAT_READY(NOT_REALLY), // DUNNO(YA_REALLY), // NOT_READY(NOT_REALLY), // WHATEVER(YA_REALLY), // NOT_READY_AT_ALL(NOT_REALLY), // ; // // private SubStatus subStatus; // // Status(SubStatus subStatus) { // this.subStatus = subStatus; // } // // public static List<Status> oReallyStatuses() { // return Stream.of(values()).filter(Status::isOReally).collect(Collectors.toList()); // } // // public static List<Status> yaReallyStatuses() { // return Stream.of(values()).filter(Status::isYaReally).collect(Collectors.toList()); // } // // public static List<Status> notReallyStatuses() { // return Stream.of(values()).filter(Status::isNotReally).collect(Collectors.toList()); // } // // public SubStatus getSubStatus() { // return subStatus; // } // // private boolean isOReally() { // return SubStatus.O_REALLY.equals(getSubStatus()); // } // private boolean isYaReally() { // return SubStatus.YA_REALLY.equals(getSubStatus()); // } // // private boolean isNotReally() { // return SubStatus.NOT_REALLY.equals(getSubStatus()); // } // // enum SubStatus { // NOT_REALLY, // O_REALLY, // YA_REALLY // } // } // Path: src/test/java/be/swsb/productivity/chapter8/listasserts/StatusTest.java import org.junit.Test; import static be.swsb.productivity.chapter8.listasserts.Status.*; import static org.assertj.core.api.Assertions.assertThat; package be.swsb.productivity.chapter8.listasserts; public class StatusTest { @Test public void oReallyStatuses_ContainsOnlyWAITING() throws Exception {
assertThat(Status.oReallyStatuses()).containsExactly(WAITING);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/PhialPageBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // }
import android.app.Activity; import com.mindcoders.phial.internal.util.CollectionUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set;
package com.mindcoders.phial; /** * Created by rost on 11/15/17. */ public class PhialPageBuilder { private final String id; private final int iconResourceId; private final CharSequence title; private final Page.PageViewFactory pageViewFactory; private final Set<TargetScreen> screens = new HashSet<>(); public PhialPageBuilder(String id, int iconResourceId, CharSequence title, Page.PageViewFactory pageViewFactory) { this.id = id; this.iconResourceId = iconResourceId; this.title = title; this.pageViewFactory = pageViewFactory; } /** * Sets activities on which the page should be visible. * @return the same instance of {@link PhialPageBuilder} */ public PhialPageBuilder visibleOnActivities(Class<? extends Activity>... activities) { return this.visibleOnActivities(Arrays.asList(activities)); } /** * @see PhialPageBuilder#visibleOnActivities */ public PhialPageBuilder visibleOnActivities(List<Class<? extends Activity>> activities) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/PhialPageBuilder.java import android.app.Activity; import com.mindcoders.phial.internal.util.CollectionUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; package com.mindcoders.phial; /** * Created by rost on 11/15/17. */ public class PhialPageBuilder { private final String id; private final int iconResourceId; private final CharSequence title; private final Page.PageViewFactory pageViewFactory; private final Set<TargetScreen> screens = new HashSet<>(); public PhialPageBuilder(String id, int iconResourceId, CharSequence title, Page.PageViewFactory pageViewFactory) { this.id = id; this.iconResourceId = iconResourceId; this.title = title; this.pageViewFactory = pageViewFactory; } /** * Sets activities on which the page should be visible. * @return the same instance of {@link PhialPageBuilder} */ public PhialPageBuilder visibleOnActivities(Class<? extends Activity>... activities) { return this.visibleOnActivities(Arrays.asList(activities)); } /** * @see PhialPageBuilder#visibleOnActivities */ public PhialPageBuilder visibleOnActivities(List<Class<? extends Activity>> activities) {
final ArrayList<TargetScreen> screensToAdd = CollectionUtils.map(activities,
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/support/ContextCompat.java // public final class ContextCompat { // private ContextCompat() { // //to hide // } // // @SuppressWarnings("deprecation") // public static Drawable getDrawable(Context context, @DrawableRes int id) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // return context.getDrawable(id); // } // // return context.getResources().getDrawable(id); // } // }
import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import com.mindcoders.phial.internal.util.support.ContextCompat;
package com.mindcoders.phial; /** * Description of share option that is shown under Share section of Phial. * Should contain icon and title * <p> * see {@link Shareable} */ public class ShareDescription { private final Drawable drawable; private final CharSequence label; /** * @param drawable icon that will be displayed with share option * @param label label for share option */ public ShareDescription(Drawable drawable, CharSequence label) { this.drawable = drawable; this.label = label; } /** * @param context android context that will be used to load icon and title * @param drawableRes drawableId that will be displayed with share option * @param label labelId for share option */ public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/support/ContextCompat.java // public final class ContextCompat { // private ContextCompat() { // //to hide // } // // @SuppressWarnings("deprecation") // public static Drawable getDrawable(Context context, @DrawableRes int id) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // return context.getDrawable(id); // } // // return context.getResources().getDrawable(id); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java import android.content.Context; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import com.mindcoders.phial.internal.util.support.ContextCompat; package com.mindcoders.phial; /** * Description of share option that is shown under Share section of Phial. * Should contain icon and title * <p> * see {@link Shareable} */ public class ShareDescription { private final Drawable drawable; private final CharSequence label; /** * @param drawable icon that will be displayed with share option * @param label label for share option */ public ShareDescription(Drawable drawable, CharSequence label) { this.drawable = drawable; this.label = label; } /** * @param context android context that will be used to load icon and title * @param drawableRes drawableId that will be displayed with share option * @param label labelId for share option */ public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) {
this(ContextCompat.getDrawable(context, drawableRes), context.getString(label));
roshakorost/Phial
phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ @SuppressWarnings("checkstyle:JavadocMethod") public class JiraShareableBuilder { private final Context context;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ @SuppressWarnings("checkstyle:JavadocMethod") public class JiraShareableBuilder { private final Context context;
private ShareDescription shareDescription;
roshakorost/Phial
phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ @SuppressWarnings("checkstyle:JavadocMethod") public class JiraShareableBuilder { private final Context context; private ShareDescription shareDescription; private String baseUrl; private String projectKey; private final Map<String, Object> extraProperties = new HashMap<>(); public JiraShareableBuilder(Context context) { this.context = context; shareDescription = new ShareDescription( context.getResources().getDrawable(R.drawable.ic_jira), context.getString(R.string.jira_name) ); } /** * Set the URL of Jira. * <p> * Required * * @param baseUrl jira base url * @return same instance of builder */ public JiraShareableBuilder setBaseUrl(String baseUrl) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ @SuppressWarnings("checkstyle:JavadocMethod") public class JiraShareableBuilder { private final Context context; private ShareDescription shareDescription; private String baseUrl; private String projectKey; private final Map<String, Object> extraProperties = new HashMap<>(); public JiraShareableBuilder(Context context) { this.context = context; shareDescription = new ShareDescription( context.getResources().getDrawable(R.drawable.ic_jira), context.getString(R.string.jira_name) ); } /** * Set the URL of Jira. * <p> * Required * * @param baseUrl jira base url * @return same instance of builder */ public JiraShareableBuilder setBaseUrl(String baseUrl) {
Precondition.notNull(baseUrl, "baseUrl should not be null");
roshakorost/Phial
phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
for (String version : versions) { Map versionObj = Collections.singletonMap("name", version); objects.add(versionObj); } return setCustomField("fixVersions", objects); } /** * Sets fixVersions for create issue * <p> * Optioanl * * @param versions valid Jira versions * @return same instance of builder */ public JiraShareableBuilder setAffectsVersions(String... versions) { final List<Map> objects = new ArrayList<>(versions.length); for (String version : versions) { Map versionObj = Collections.singletonMap("name", version); objects.add(versionObj); } return setCustomField("versions", objects); } /** * Creates Shareable that should be included in PhialOverlay * {@link com.mindcoders.phial.PhialBuilder#addShareable(Shareable)} * * @return Sharable that provides Jira share option */
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareableBuilder.java import android.content.Context; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; for (String version : versions) { Map versionObj = Collections.singletonMap("name", version); objects.add(versionObj); } return setCustomField("fixVersions", objects); } /** * Sets fixVersions for create issue * <p> * Optioanl * * @param versions valid Jira versions * @return same instance of builder */ public JiraShareableBuilder setAffectsVersions(String... versions) { final List<Map> objects = new ArrayList<>(versions.length); for (String version : versions) { Map versionObj = Collections.singletonMap("name", version); objects.add(versionObj); } return setCustomField("versions", objects); } /** * Creates Shareable that should be included in PhialOverlay * {@link com.mindcoders.phial.PhialBuilder#addShareable(Shareable)} * * @return Sharable that provides Jira share option */
public Shareable build() {
roshakorost/Phial
sample/src/main/java/com/mindcoders/phial/sample/HomeActivity.java
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // }
import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StringRes; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.transition.Slide; import android.transition.Transition; import android.transition.TransitionInflater; import android.util.Pair; import android.util.SparseArray; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import com.mindcoders.phial.keyvalue.Phial; import java.util.ArrayList; import java.util.List;
package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ShareElementManager { private static final SparseArray<Class<? extends Fragment>> FRAGMENTS = new SparseArray<>(); private static final int DEFAULT_FRAGMENT = R.id.main; private List<Pair<View, String>> sharedElements; static { FRAGMENTS.put(R.id.main, MainFragment.class); FRAGMENTS.put(R.id.auto_fill, AutoFillFragment.class); } private DrawerLayout drawer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { sharedElements = new ArrayList<>(); super.onCreate(savedInstanceState);
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // } // Path: sample/src/main/java/com/mindcoders/phial/sample/HomeActivity.java import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StringRes; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.transition.Slide; import android.transition.Transition; import android.transition.TransitionInflater; import android.util.Pair; import android.util.SparseArray; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import com.mindcoders.phial.keyvalue.Phial; import java.util.ArrayList; import java.util.List; package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, ShareElementManager { private static final SparseArray<Class<? extends Fragment>> FRAGMENTS = new SparseArray<>(); private static final int DEFAULT_FRAGMENT = R.id.main; private List<Pair<View, String>> sharedElements; static { FRAGMENTS.put(R.id.main, MainFragment.class); FRAGMENTS.put(R.id.auto_fill, AutoFillFragment.class); } private DrawerLayout drawer; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { sharedElements = new ArrayList<>(); super.onCreate(savedInstanceState);
Phial.setKey("currentActivity", getClass().getSimpleName());
roshakorost/Phial
phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareManager.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import com.mindcoders.phial.internal.util.Precondition; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import okhttp3.Credentials; import okhttp3.OkHttpClient;
package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ class JiraShareManager { interface ResultCallback { void onSuccess(String issueName); void onFail(Throwable th); } private final CredentialStore credentialStore; private final OkHttpFactory okHttpFactory; private final String baseUrl; private final String projectKey; private final Map<String, Object> extrtaProperties; private final ExecutorService executor = Executors.newSingleThreadExecutor(); JiraShareManager(CredentialStore credentialStore, OkHttpFactory okHttpFactory, String baseUrl, String projectKey, Map<String, Object> extraProperties) { this.credentialStore = credentialStore; this.okHttpFactory = okHttpFactory; this.baseUrl = baseUrl; this.projectKey = projectKey; this.extrtaProperties = extraProperties; } boolean isAuthorized() { return credentialStore.hasCredentials(); } void share(File attachment, String message, ResultCallback resultCallback) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareManager.java import com.mindcoders.phial.internal.util.Precondition; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import okhttp3.Credentials; import okhttp3.OkHttpClient; package com.mindcoders.phial.jira; /** * Created by rost on 10/29/17. */ class JiraShareManager { interface ResultCallback { void onSuccess(String issueName); void onFail(Throwable th); } private final CredentialStore credentialStore; private final OkHttpFactory okHttpFactory; private final String baseUrl; private final String projectKey; private final Map<String, Object> extrtaProperties; private final ExecutorService executor = Executors.newSingleThreadExecutor(); JiraShareManager(CredentialStore credentialStore, OkHttpFactory okHttpFactory, String baseUrl, String projectKey, Map<String, Object> extraProperties) { this.credentialStore = credentialStore; this.okHttpFactory = okHttpFactory; this.baseUrl = baseUrl; this.projectKey = projectKey; this.extrtaProperties = extraProperties; } boolean isAuthorized() { return credentialStore.hasCredentials(); } void share(File attachment, String message, ResultCallback resultCallback) {
Precondition.isTrue(isAuthorized(), "call of share when not authorized");
roshakorost/Phial
phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillPageFactory.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // }
import android.content.Context; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.Page;
package com.mindcoders.phial.autofill; /** * Created by rost on 11/4/17. */ class AutoFillPageFactory implements Page.PageViewFactory<FillView> { private final FillConfig config; AutoFillPageFactory(FillConfig config) { this.config = config; } @Override
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // Path: phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillPageFactory.java import android.content.Context; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.Page; package com.mindcoders.phial.autofill; /** * Created by rost on 11/4/17. */ class AutoFillPageFactory implements Page.PageViewFactory<FillView> { private final FillConfig config; AutoFillPageFactory(FillConfig config) { this.config = config; } @Override
public FillView createPageView(Context context, OverlayCallback overlayCallback) {
roshakorost/Phial
phial-autofill/src/main/java/com/mindcoders/phial/autofill/FillView.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleTextWatcher.java // public class SimpleTextWatcher implements TextWatcher { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // //optional // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // //optional // } // // @Override // public void afterTextChanged(Editable s) { // //optional // } // }
import android.content.Context; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.PageView; import com.mindcoders.phial.internal.util.Precondition; import com.mindcoders.phial.internal.util.SimpleTextWatcher; import java.util.ArrayList; import java.util.List;
package com.mindcoders.phial.autofill; /** * Created by rost on 11/3/17. */ class FillView extends FrameLayout implements PageView, Adapter.OnItemClickedListener { private final OverlayCallback overlayCallback; private final Adapter adapter; private final ConfigManager manager; FillView(@NonNull Context context) { super(context);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleTextWatcher.java // public class SimpleTextWatcher implements TextWatcher { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // //optional // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // //optional // } // // @Override // public void afterTextChanged(Editable s) { // //optional // } // } // Path: phial-autofill/src/main/java/com/mindcoders/phial/autofill/FillView.java import android.content.Context; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.PageView; import com.mindcoders.phial.internal.util.Precondition; import com.mindcoders.phial.internal.util.SimpleTextWatcher; import java.util.ArrayList; import java.util.List; package com.mindcoders.phial.autofill; /** * Created by rost on 11/3/17. */ class FillView extends FrameLayout implements PageView, Adapter.OnItemClickedListener { private final OverlayCallback overlayCallback; private final Adapter adapter; private final ConfigManager manager; FillView(@NonNull Context context) { super(context);
Precondition.calledFromTools(this);
roshakorost/Phial
phial-autofill/src/main/java/com/mindcoders/phial/autofill/FillView.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleTextWatcher.java // public class SimpleTextWatcher implements TextWatcher { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // //optional // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // //optional // } // // @Override // public void afterTextChanged(Editable s) { // //optional // } // }
import android.content.Context; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.PageView; import com.mindcoders.phial.internal.util.Precondition; import com.mindcoders.phial.internal.util.SimpleTextWatcher; import java.util.ArrayList; import java.util.List;
((TextView) view).setText(dataToFill.get(i)); } } overlayCallback.finish(); } private void saveOption(String optionName) { if (optionName.isEmpty()) { return; } final List<Integer> ids = manager.getTargetIds(); final List<String> values = new ArrayList<>(ids.size()); for (int i = 0; i < ids.size(); i++) { final View view = overlayCallback.findViewById(ids.get(i)); final String value = readValueOrDefault(view); values.add(value); } manager.saveOption(optionName, values); } private String readValueOrDefault(View view) { if (!(view instanceof TextView)) { return AutoFiller.EMPTY_FIELD; } return ((TextView) view).getText().toString(); }
// Path: phial-overlay/src/main/java/com/mindcoders/phial/OverlayCallback.java // public interface OverlayCallback { // // /** // * Called to close phial debug window // */ // void finish(); // // // /** // * Finds view in application view hierarchy // * // * @param id view id. // * @return view or null if view is missing // */ // @Nullable // View findViewById(int id); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleTextWatcher.java // public class SimpleTextWatcher implements TextWatcher { // @Override // public void beforeTextChanged(CharSequence s, int start, int count, int after) { // //optional // } // // @Override // public void onTextChanged(CharSequence s, int start, int before, int count) { // //optional // } // // @Override // public void afterTextChanged(Editable s) { // //optional // } // } // Path: phial-autofill/src/main/java/com/mindcoders/phial/autofill/FillView.java import android.content.Context; import android.support.annotation.NonNull; import android.text.Editable; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.mindcoders.phial.OverlayCallback; import com.mindcoders.phial.PageView; import com.mindcoders.phial.internal.util.Precondition; import com.mindcoders.phial.internal.util.SimpleTextWatcher; import java.util.ArrayList; import java.util.List; ((TextView) view).setText(dataToFill.get(i)); } } overlayCallback.finish(); } private void saveOption(String optionName) { if (optionName.isEmpty()) { return; } final List<Integer> ids = manager.getTargetIds(); final List<String> values = new ArrayList<>(ids.size()); for (int i = 0; i < ids.size(); i++) { final View view = overlayCallback.findViewById(ids.get(i)); final String value = readValueOrDefault(view); values.add(value); } manager.saveOption(optionName, values); } private String readValueOrDefault(View view) { if (!(view instanceof TextView)) { return AutoFiller.EMPTY_FIELD; } return ((TextView) view).getText().toString(); }
private static class ButtonEnabler extends SimpleTextWatcher {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareItem.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // }
import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE;
package com.mindcoders.phial.internal.share; /** * Created by rost on 10/23/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public abstract class ShareItem {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareItem.java import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE; package com.mindcoders.phial.internal.share; /** * Created by rost on 10/23/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public abstract class ShareItem {
private final ShareDescription description;
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareItem.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // }
import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE;
package com.mindcoders.phial.internal.share; /** * Created by rost on 10/23/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public abstract class ShareItem { private final ShareDescription description;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareItem.java import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE; package com.mindcoders.phial.internal.share; /** * Created by rost on 10/23/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public abstract class ShareItem { private final ShareDescription description;
static ShareItem create(Shareable shareable) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // }
import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil;
} void animateFromDefaultPosition(Runnable endAction) { disposable.dispose(); disposable = LayoutHelper.onLayout(() -> animateFromDefaultToInitial(false, endAction)); } void animateToDefaultPosition(Runnable endAction) { disposable.dispose(); disposable = LayoutHelper.onLayout(() -> animateFromDefaultToInitial(true, endAction)); } private void animateFromDefaultToInitial(boolean reversed, Runnable endAction) { initParentRect(); animator.cancel(); final int paddingValue = view.getResources().getDimensionPixelSize(paddingRes); final int startX = parent.right - paddingValue; final int startY = parent.top + paddingValue; final PositionStorage.Position position = positionStorage.getPosition(DEFAULT_X, DEFAULT_Y); final int targetX = (int) (parent.left + parent.width() * position.x); final int targetY = (int) (parent.top + parent.height() * position.y); if (reversed) { animator = createMoveAnimator(view, targetX, targetY, startX, startY); } else { animator = createMoveAnimator(view, startX, startY, targetX, targetY); } if (endAction != null) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil; } void animateFromDefaultPosition(Runnable endAction) { disposable.dispose(); disposable = LayoutHelper.onLayout(() -> animateFromDefaultToInitial(false, endAction)); } void animateToDefaultPosition(Runnable endAction) { disposable.dispose(); disposable = LayoutHelper.onLayout(() -> animateFromDefaultToInitial(true, endAction)); } private void animateFromDefaultToInitial(boolean reversed, Runnable endAction) { initParentRect(); animator.cancel(); final int paddingValue = view.getResources().getDimensionPixelSize(paddingRes); final int startX = parent.right - paddingValue; final int startY = parent.top + paddingValue; final PositionStorage.Position position = positionStorage.getPosition(DEFAULT_X, DEFAULT_Y); final int targetX = (int) (parent.left + parent.width() * position.x); final int targetY = (int) (parent.top + parent.height() * position.y); if (reversed) { animator = createMoveAnimator(view, targetX, targetY, startX, startY); } else { animator = createMoveAnimator(view, startX, startY, targetX, targetY); } if (endAction != null) {
animator.addListener(SimpleAnimatorListener.createEndListener(endAction));
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // }
import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil;
}); return animator; } private boolean onTouch(View v, MotionEvent event) { if (parent.isEmpty()) { return false; } animator.cancel(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: initialTouchX = event.getRawX(); initialTouchY = event.getRawY(); startTimeMS = event.getEventTime(); onMoveStart(v); v.setPressed(true); return true; case MotionEvent.ACTION_MOVE: animator.cancel(); onMove(v, event.getRawX() - initialTouchX, event.getRawY() - initialTouchY); return true; case MotionEvent.ACTION_UP: v.setPressed(false); onMoveEnd(v); final long downTimeMS = event.getEventTime() - startTimeMS; final float halfButtonSize = Math.min(v.getHeight(), v.getWidth()) / 2f; final boolean wasClicked = downTimeMS < CLICK_MAX_DURATION_MS
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil; }); return animator; } private boolean onTouch(View v, MotionEvent event) { if (parent.isEmpty()) { return false; } animator.cancel(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: initialTouchX = event.getRawX(); initialTouchY = event.getRawY(); startTimeMS = event.getEventTime(); onMoveStart(v); v.setPressed(true); return true; case MotionEvent.ACTION_MOVE: animator.cancel(); onMove(v, event.getRawX() - initialTouchX, event.getRawY() - initialTouchY); return true; case MotionEvent.ACTION_UP: v.setPressed(false); onMoveEnd(v); final long downTimeMS = event.getEventTime() - startTimeMS; final float halfButtonSize = Math.min(v.getHeight(), v.getWidth()) / 2f; final boolean wasClicked = downTimeMS < CLICK_MAX_DURATION_MS
&& ViewUtil.distance(initialTouchX, initialTouchY, event.getRawX(), event.getRawY()) < halfButtonSize;
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // }
import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil;
onMoveStart(v); v.setPressed(true); return true; case MotionEvent.ACTION_MOVE: animator.cancel(); onMove(v, event.getRawX() - initialTouchX, event.getRawY() - initialTouchY); return true; case MotionEvent.ACTION_UP: v.setPressed(false); onMoveEnd(v); final long downTimeMS = event.getEventTime() - startTimeMS; final float halfButtonSize = Math.min(v.getHeight(), v.getWidth()) / 2f; final boolean wasClicked = downTimeMS < CLICK_MAX_DURATION_MS && ViewUtil.distance(initialTouchX, initialTouchY, event.getRawX(), event.getRawY()) < halfButtonSize; if (wasClicked) { v.performClick(); } return true; default: return true; } } private void onMoveStart(View view) { final LayoutParams lp = (LayoutParams) view.getLayoutParams(); initialX = lp.x; initialY = lp.y; } private void onMove(View view, float dx, float dy) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/NumberUtil.java // public final class NumberUtil { // private NumberUtil() { // //to hide // } // // public static float clipTo(float value, float min, float max) { // if (value < min) { // return min; // } // // if (value > max) { // return max; // } // // return value; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleAnimatorListener.java // public class SimpleAnimatorListener implements Animator.AnimatorListener { // // @Override // public void onAnimationStart(Animator animation) { // //optional // } // // @Override // public void onAnimationEnd(Animator animation) { // //optional // } // // @Override // public void onAnimationCancel(Animator animation) { // //optional // } // // @Override // public void onAnimationRepeat(Animator animation) { // //optional // } // // public static Animator.AnimatorListener createEndListener(@NonNull Runnable runnable) { // return new SimpleAnimatorListener() { // @Override // public void onAnimationEnd(Animator animation) { // runnable.run(); // } // }; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ViewUtil.java // public final class ViewUtil { // private ViewUtil() { // //to hide // } // // public static float distance(float x1, float y1, float x2, float y2) { // final float dx = x1 - x2; // final float dy = y1 - y2; // return (float) Math.sqrt(dx * dx + dy * dy); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/DragHelper.java import android.animation.ValueAnimator; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import android.view.animation.AccelerateDecelerateInterpolator; import com.mindcoders.phial.internal.util.NumberUtil; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import com.mindcoders.phial.internal.util.ViewUtil; onMoveStart(v); v.setPressed(true); return true; case MotionEvent.ACTION_MOVE: animator.cancel(); onMove(v, event.getRawX() - initialTouchX, event.getRawY() - initialTouchY); return true; case MotionEvent.ACTION_UP: v.setPressed(false); onMoveEnd(v); final long downTimeMS = event.getEventTime() - startTimeMS; final float halfButtonSize = Math.min(v.getHeight(), v.getWidth()) / 2f; final boolean wasClicked = downTimeMS < CLICK_MAX_DURATION_MS && ViewUtil.distance(initialTouchX, initialTouchY, event.getRawX(), event.getRawY()) < halfButtonSize; if (wasClicked) { v.performClick(); } return true; default: return true; } } private void onMoveStart(View view) { final LayoutParams lp = (LayoutParams) view.getLayoutParams(); initialX = lp.x; initialY = lp.y; } private void onMove(View view, float dx, float dy) {
final int newX = (int) NumberUtil.clipTo(initialX + dx, parent.left, parent.right);
roshakorost/Phial
phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareable.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareContext.java // public interface ShareContext { // /** // * @return Android Context in which Phial works // */ // Context getAndroidContext(); // // /** // * Should be called if successfully shared // */ // void onSuccess(); // // /** // * Should be called in case of error during share. // * // * @param message that will be presented to user // */ // void onFailed(String message); // // /** // * Should be called in case user cancel share // */ // void onCancel(); // // /** // * Presents custom view that will be shown to user // * // * @param view view to present // */ // void presentView(View view); // // /** // * Shows or hides progress bar to user // * // * @param isVisible true will show progressbar false will hide // */ // void setProgressBarVisibility(boolean isVisible); // // /** // * Creates view using provided layoutId. Created view will not be presented. // * Should {@link #presentView(View)} in order to show to user // * // * @param layoutId Android layout resource // * @return created view // */ // View inflate(@LayoutRes int layoutId); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // }
import android.content.Context; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.mindcoders.phial.ShareContext; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import java.io.File;
package com.mindcoders.phial.jira; /** * Created by rost on 10/27/17. */ class JiraShareable implements Shareable { private final ShareDescription description; private final JiraShareManager shareManager; JiraShareable(ShareDescription description, JiraShareManager shareManager) { this.description = description; this.shareManager = shareManager; } @Override
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareContext.java // public interface ShareContext { // /** // * @return Android Context in which Phial works // */ // Context getAndroidContext(); // // /** // * Should be called if successfully shared // */ // void onSuccess(); // // /** // * Should be called in case of error during share. // * // * @param message that will be presented to user // */ // void onFailed(String message); // // /** // * Should be called in case user cancel share // */ // void onCancel(); // // /** // * Presents custom view that will be shown to user // * // * @param view view to present // */ // void presentView(View view); // // /** // * Shows or hides progress bar to user // * // * @param isVisible true will show progressbar false will hide // */ // void setProgressBarVisibility(boolean isVisible); // // /** // * Creates view using provided layoutId. Created view will not be presented. // * Should {@link #presentView(View)} in order to show to user // * // * @param layoutId Android layout resource // * @return created view // */ // View inflate(@LayoutRes int layoutId); // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // Path: phial-jira/src/main/java/com/mindcoders/phial/jira/JiraShareable.java import android.content.Context; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.mindcoders.phial.ShareContext; import com.mindcoders.phial.ShareDescription; import com.mindcoders.phial.Shareable; import java.io.File; package com.mindcoders.phial.jira; /** * Created by rost on 10/27/17. */ class JiraShareable implements Shareable { private final ShareDescription description; private final JiraShareManager shareManager; JiraShareable(ShareDescription description, JiraShareManager shareManager) { this.description = description; this.shareManager = shareManager; } @Override
public void share(final ShareContext shareContext, File zippedAttachment, String message) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/OverlayView.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // }
import android.app.Activity; import android.content.Context; import android.graphics.PixelFormat; import android.support.annotation.Nullable; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import com.mindcoders.phial.Page; import com.mindcoders.phial.R; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND; import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView) { this.dragHelper = dragHelper; this.expandedView = expandedView; this.context = context; expandedView.setCallback(this); } void setPresenter(OverlayPresenter presenter) { this.presenter = presenter; } void showButton(Activity activity, boolean animated) { WindowManager windowManager = activity.getWindowManager(); final View button = createButton(); buttons.put(activity, button); final LayoutParams wrap = wrap(BUTTON_PARAMS); windowManager.addView(button, wrap); dragHelper.manage(windowManager, button); if (animated) { dragHelper.animateFromDefaultPosition(button, null); } } void removeButton(Activity activity) { final View button = buttons.remove(activity); dragHelper.unmanage(button); activity.getWindowManager().removeView(button); }
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/OverlayView.java import android.app.Activity; import android.content.Context; import android.graphics.PixelFormat; import android.support.annotation.Nullable; import android.view.View; import android.view.WindowManager; import android.view.WindowManager.LayoutParams; import com.mindcoders.phial.Page; import com.mindcoders.phial.R; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND; import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION; OverlayView(Context context, DragHelper dragHelper, ExpandedView expandedView) { this.dragHelper = dragHelper; this.expandedView = expandedView; this.context = context; expandedView.setCallback(this); } void setPresenter(OverlayPresenter presenter) { this.presenter = presenter; } void showButton(Activity activity, boolean animated) { WindowManager windowManager = activity.getWindowManager(); final View button = createButton(); buttons.put(activity, button); final LayoutParams wrap = wrap(BUTTON_PARAMS); windowManager.addView(button, wrap); dragHelper.manage(windowManager, button); if (animated) { dragHelper.animateFromDefaultPosition(button, null); } } void removeButton(Activity activity) { final View button = buttons.remove(activity); dragHelper.unmanage(button); activity.getWindowManager().removeView(button); }
void showExpandedView(Activity activity, List<Page> pages, Page selected, boolean animated) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // }
import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/22/17. */ class KVJsonSerializer { @VisibleForTesting static final int INDENT_SPACES = 2; @VisibleForTesting static final String NAME_KEY = "name"; @VisibleForTesting static final String VALUE_KEY = "value"; @VisibleForTesting static final String ENTRIES_KEY = "entries";
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/22/17. */ class KVJsonSerializer { @VisibleForTesting static final int INDENT_SPACES = 2; @VisibleForTesting static final String NAME_KEY = "name"; @VisibleForTesting static final String VALUE_KEY = "value"; @VisibleForTesting static final String ENTRIES_KEY = "entries";
String serializeToString(List<KVCategory> categories) throws JSONException {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // }
import android.content.Context; import com.mindcoders.phial.keyvalue.Category; import com.mindcoders.phial.keyvalue.Phial;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public abstract class InfoWriter { private final Category category; private final Context context; public InfoWriter(Context context, String categoryName) {
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java import android.content.Context; import com.mindcoders.phial.keyvalue.Category; import com.mindcoders.phial.keyvalue.Phial; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public abstract class InfoWriter { private final Category category; private final Context context; public InfoWriter(Context context, String categoryName) {
this.category = Phial.category(categoryName);
roshakorost/Phial
sample/src/main/java/com/mindcoders/phial/sample/MainFragment.java
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.mindcoders.phial.keyvalue.Phial; import timber.log.Timber;
public void onClick(View v) { clickCount++; sp.edit().putInt(CLICKED_KEY, clickCount).apply(); showClickCount(button, clickCount); } }); } @Override public void onResume() { super.onResume(); Timber.d("onResume"); } @Override public void onPause() { super.onPause(); Timber.d("onPause"); } @Override public void onDestroy() { super.onDestroy(); Timber.d("onDestroy"); } private void showClickCount(Button view, int count) { // in log you will see log entry every time button is clicked Timber.d("showClickCount %d", count); // only last value will be associated with key. Every time these method is called value will be updated.
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // } // Path: sample/src/main/java/com/mindcoders/phial/sample/MainFragment.java import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.mindcoders.phial.keyvalue.Phial; import timber.log.Timber; public void onClick(View v) { clickCount++; sp.edit().putInt(CLICKED_KEY, clickCount).apply(); showClickCount(button, clickCount); } }); } @Override public void onResume() { super.onResume(); Timber.d("onResume"); } @Override public void onPause() { super.onPause(); Timber.d("onPause"); } @Override public void onDestroy() { super.onDestroy(); Timber.d("onDestroy"); } private void showClickCount(Button view, int count) { // in log you will see log entry every time button is clicked Timber.d("showClickCount %d", count); // only last value will be associated with key. Every time these method is called value will be updated.
Phial.category("Button").setKey("clicked", count);
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/ScreenTrackerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java // public interface ScreenListener { // void onScreenChanged(Screen screen); // }
import android.app.Activity; import android.view.View; import com.mindcoders.phial.internal.ScreenTracker.ScreenListener; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.mindcoders.phial.internal; public class ScreenTrackerTest { private ScreenTracker screenTracker; @Before public void setUp() throws Exception { screenTracker = new ScreenTracker(); } @Test public void onActivityResumed() throws Exception {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java // public interface ScreenListener { // void onScreenChanged(Screen screen); // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/ScreenTrackerTest.java import android.app.Activity; import android.view.View; import com.mindcoders.phial.internal.ScreenTracker.ScreenListener; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.mindcoders.phial.internal; public class ScreenTrackerTest { private ScreenTracker screenTracker; @Before public void setUp() throws Exception { screenTracker = new ScreenTracker(); } @Test public void onActivityResumed() throws Exception {
ScreenListener listener = mock(ScreenListener.class);
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/OverlayViewTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // }
import android.app.Activity; import android.content.Context; import android.view.View; import android.view.WindowManager; import com.mindcoders.phial.Page; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
final ArgumentCaptor<View> viewArgumentCaptor = ArgumentCaptor.forClass(View.class); verify(windowManager).addView(viewArgumentCaptor.capture(), any()); verify(dragHelper).animateFromDefaultPosition(eq(viewArgumentCaptor.getValue()), any()); view.removeButton(activity); verify(windowManager).removeView(viewArgumentCaptor.getValue()); } @Test public void show_and_remove_button_several_activities() { final ArgumentCaptor<View> viewArgumentCaptor = ArgumentCaptor.forClass(View.class); final WindowManager windowManager1 = mock(WindowManager.class); final Activity activity1 = mockActivity(windowManager1); final ArgumentCaptor<View> viewArgumentCaptor1 = ArgumentCaptor.forClass(View.class); view.showButton(activity, false); verify(windowManager).addView(viewArgumentCaptor.capture(), any()); view.showButton(activity1, false); verify(windowManager1).addView(viewArgumentCaptor1.capture(), any()); view.removeButton(activity); verify(windowManager).removeView(viewArgumentCaptor.getValue()); view.removeButton(activity1); verify(windowManager1).removeView(viewArgumentCaptor1.getValue()); } @Test public void showExpandedView() {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/OverlayViewTest.java import android.app.Activity; import android.content.Context; import android.view.View; import android.view.WindowManager; import com.mindcoders.phial.Page; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; final ArgumentCaptor<View> viewArgumentCaptor = ArgumentCaptor.forClass(View.class); verify(windowManager).addView(viewArgumentCaptor.capture(), any()); verify(dragHelper).animateFromDefaultPosition(eq(viewArgumentCaptor.getValue()), any()); view.removeButton(activity); verify(windowManager).removeView(viewArgumentCaptor.getValue()); } @Test public void show_and_remove_button_several_activities() { final ArgumentCaptor<View> viewArgumentCaptor = ArgumentCaptor.forClass(View.class); final WindowManager windowManager1 = mock(WindowManager.class); final Activity activity1 = mockActivity(windowManager1); final ArgumentCaptor<View> viewArgumentCaptor1 = ArgumentCaptor.forClass(View.class); view.showButton(activity, false); verify(windowManager).addView(viewArgumentCaptor.capture(), any()); view.showButton(activity1, false); verify(windowManager1).addView(viewArgumentCaptor1.capture(), any()); view.removeButton(activity); verify(windowManager).removeView(viewArgumentCaptor.getValue()); view.removeButton(activity1); verify(windowManager1).removeView(viewArgumentCaptor1.getValue()); } @Test public void showExpandedView() {
final List<Page> pages = IntStream.range(0, 5).mapToObj(this::createPage).collect(Collectors.toList());
roshakorost/Phial
sample/src/main/java/com/mindcoders/phial/sample/AutoFillFragment.java
// Path: phial-scope/src/main/java/com/mindcoders/phial/PhialScope.java // public final class PhialScope extends PhialScopeNotifier { // // /** // * Enter a new scope. // * @param scopeName scopeName // */ // public static void enterScope(String scopeName) { // fireEnterScope(scopeName, null); // } // // /** // * Enter a new scope if scope is not in the activity {@link android.view.Window}. // * For example, in case of {@link android.app.DialogFragment}. // * @param scopeName scopeName // * @param view view of current scope // */ // public static void enterScope(String scopeName, View view) { // fireEnterScope(scopeName, view); // } // // /** // * Exit the existing scope. // * @param scopeName scopeName // */ // public static void exitScope(String scopeName) { // fireExitScope(scopeName); // } // // }
import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.mindcoders.phial.PhialScope;
package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class AutoFillFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_auto_fill, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final Button button = view.findViewById(R.id.button_login); ((ShareElementManager) getActivity()).addSharedElement(button, R.string.transition_button); view.findViewById(R.id.go_auto_fill).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(), AutoFillActivity.class)); } }); } @Override public void onResume() { super.onResume();
// Path: phial-scope/src/main/java/com/mindcoders/phial/PhialScope.java // public final class PhialScope extends PhialScopeNotifier { // // /** // * Enter a new scope. // * @param scopeName scopeName // */ // public static void enterScope(String scopeName) { // fireEnterScope(scopeName, null); // } // // /** // * Enter a new scope if scope is not in the activity {@link android.view.Window}. // * For example, in case of {@link android.app.DialogFragment}. // * @param scopeName scopeName // * @param view view of current scope // */ // public static void enterScope(String scopeName, View view) { // fireEnterScope(scopeName, view); // } // // /** // * Exit the existing scope. // * @param scopeName scopeName // */ // public static void exitScope(String scopeName) { // fireExitScope(scopeName); // } // // } // Path: sample/src/main/java/com/mindcoders/phial/sample/AutoFillFragment.java import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.mindcoders.phial.PhialScope; package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class AutoFillFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_auto_fill, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final Button button = view.findViewById(R.id.button_login); ((ShareElementManager) getActivity()).addSharedElement(button, R.string.transition_button); view.findViewById(R.id.go_auto_fill).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getContext(), AutoFillActivity.class)); } }); } @Override public void onResume() { super.onResume();
PhialScope.enterScope("Login");
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // }
import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true;
private InfoWriter systemInfoWriter;
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // }
import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true; private InfoWriter systemInfoWriter; private InfoWriter buildInfoWriter; private boolean enableKeyValueView = true; private boolean enableShareView = true; private String shareDataFilePattern = "'data_M'MM'D'dd_'H'HH_mm_ss"; public PhialBuilder(Application application) { this.application = application;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true; private InfoWriter systemInfoWriter; private InfoWriter buildInfoWriter; private boolean enableKeyValueView = true; private boolean enableShareView = true; private String shareDataFilePattern = "'data_M'MM'D'dd_'H'HH_mm_ss"; public PhialBuilder(Application application) { this.application = application;
this.systemInfoWriter = new SystemInfoWriter(application);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // }
import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true; private InfoWriter systemInfoWriter; private InfoWriter buildInfoWriter; private boolean enableKeyValueView = true; private boolean enableShareView = true; private String shareDataFilePattern = "'data_M'MM'D'dd_'H'HH_mm_ss"; public PhialBuilder(Application application) { this.application = application; this.systemInfoWriter = new SystemInfoWriter(application);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java // public final class BuildInfoWriter extends InfoWriter { // private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; // @Nullable // private final Long buildTime; // @Nullable // private final String buildCommit; // // public BuildInfoWriter(Context context) { // this(context, null, null); // } // // public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { // super(context, "Build"); // this.buildTime = buildTime; // this.buildCommit = buildCommit; // } // // @Override // protected void writeInfo(Category category) { // final String packageName = getContext().getPackageName(); // category.setKey("Package", packageName); // // try { // final PackageInfo packageInfo = getContext().getPackageManager() // .getPackageInfo(packageName, PackageManager.GET_META_DATA); // category.setKey("Version", packageInfo.versionName); // } catch (PackageManager.NameNotFoundException e) { // PhialErrorPlugins.onError(e); // } // // if (buildTime != null) { // category.setKey("BuildTime", getBuildTime(buildTime)); // } // // if (buildCommit != null) { // category.setKey("BuildCommit", buildCommit); // } // } // // // private static String getBuildTime(long buildTime) { // final Date buildDate = new Date(buildTime); // return new SimpleDateFormat(DATE_FORMAT, Locale.US).format(buildDate); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/InfoWriter.java // public abstract class InfoWriter { // private final Category category; // private final Context context; // // public InfoWriter(Context context, String categoryName) { // this.category = Phial.category(categoryName); // this.context = context; // } // // public final void writeInfo() { // writeInfo(category); // } // // protected abstract void writeInfo(Category category); // // protected final Context getContext() { // return context; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java // public final class SystemInfoWriter extends InfoWriter { // public SystemInfoWriter(Context context) { // super(context, "System"); // } // // @Override // protected void writeInfo(Category saver) { // saver.setKey("Board", Build.BOARD); // saver.setKey("Brand", Build.BRAND); // saver.setKey("Device", Build.DEVICE); // saver.setKey("Model", Build.MODEL); // saver.setKey("Manufacturer", MANUFACTURER); // saver.setKey("Product", Build.PRODUCT); // saver.setKey("SDK", Build.VERSION.SDK_INT); // saver.setKey("OS Version", System.getProperty("os.version") + " (" + Build.VERSION.INCREMENTAL + ")"); // saver.setKey("SDCard state", Environment.getExternalStorageState()); // // final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics(); // saver.setKey("Density", displayMetrics.density); // saver.setKey("Width", displayMetrics.widthPixels); // saver.setKey("Height", displayMetrics.heightPixels); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/attachment/AttacherAdaptor.java // public class AttacherAdaptor implements ListAttacher { // private final Attacher attacher; // // public AttacherAdaptor(Attacher attacher) { // this.attacher = attacher; // } // // public static ListAttacher adapt(Attacher attacher) { // return new AttacherAdaptor(attacher); // } // // @Override // public List<File> provideAttachment() throws Exception { // final File file = attacher.provideAttachment(); // if (file != null) { // return Collections.singletonList(file); // } else { // return Collections.emptyList(); // } // } // // @Override // public void onPreDebugWindowCreated() { // attacher.onPreDebugWindowCreated(); // } // // @Override // public void onAttachmentNotNeeded() { // attacher.onAttachmentNotNeeded(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // AttacherAdaptor that = (AttacherAdaptor) o; // // return attacher.equals(that.attacher); // // } // // @Override // public int hashCode() { // return attacher.hashCode(); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/PhialBuilder.java import android.app.Application; import com.mindcoders.phial.internal.keyvalue.BuildInfoWriter; import com.mindcoders.phial.internal.keyvalue.InfoWriter; import com.mindcoders.phial.internal.keyvalue.SystemInfoWriter; import com.mindcoders.phial.internal.share.attachment.AttacherAdaptor; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; package com.mindcoders.phial; /** * Creates and configures phial overlay pages */ public class PhialBuilder { private final Application application; private final List<Shareable> shareables = new ArrayList<>(); private final List<ListAttacher> attachers = new ArrayList<>(); private final List<Page> pages = new ArrayList<>(); private boolean attachScreenshots = true; private boolean attachKeyValues = true; private InfoWriter systemInfoWriter; private InfoWriter buildInfoWriter; private boolean enableKeyValueView = true; private boolean enableShareView = true; private String shareDataFilePattern = "'data_M'MM'D'dd_'H'HH_mm_ss"; public PhialBuilder(Application application) { this.application = application; this.systemInfoWriter = new SystemInfoWriter(application);
this.buildInfoWriter = new BuildInfoWriter(application);
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings;
package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception {
View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class));
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings;
package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class));
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class));
List<Page> pages = ImmutableList.of(
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings;
package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class)); List<Page> pages = ImmutableList.of( new Page("page1", R.drawable.ic_share, "page1", (context, overlayCallback) -> pageView1), new Page("page2", R.drawable.ic_share, "page2", (context, overlayCallback) -> pageView2) ); Page selectedPage = pages.get(0); view.displayPages(pages, selectedPage, false); ViewGroup iconHolder = view.findViewById(R.id.tab_icons_holder); assertEquals(pages.size() + 1, iconHolder.getChildCount()); for (int i = 0; i < iconHolder.getChildCount(); i++) { View child = iconHolder.getChildAt(i);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Page.java // public final class Page { // // /** // * Factory that is used to create views when page is selected // * // * @param <T> view to display // */ // public interface PageViewFactory<T extends View & PageView> { // // /** // * @param context android application context // * @param overlayCallback interface for communication with Phial // * @return view to display // */ // T createPageView(Context context, OverlayCallback overlayCallback); // // } // // private final String id; // private final int iconResourceId; // private final CharSequence title; // private final PageViewFactory pageViewFactory; // private final Set<TargetScreen> targetScreens; // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory // ) { // this(id, iconResourceId, title, pageViewFactory, Collections.<TargetScreen>emptySet()); // } // // /** // * @param id unique pageId // * @param iconResourceId page icon // * @param title page title // * @param pageViewFactory factory that will create view when page is selected // * @param targetScreens screens to present this page on. Page will be present on all screens if this is empty. // */ // public Page( // String id, // int iconResourceId, // CharSequence title, // PageViewFactory pageViewFactory, // Set<TargetScreen> targetScreens // ) { // this.id = id; // this.iconResourceId = iconResourceId; // this.title = title; // this.pageViewFactory = pageViewFactory; // this.targetScreens = Collections.unmodifiableSet(targetScreens); // } // // public String getId() { // return id; // } // // public int getIconResourceId() { // return iconResourceId; // } // // public CharSequence getTitle() { // return title; // } // // public PageViewFactory getPageViewFactory() { // return pageViewFactory; // } // // public Set<TargetScreen> getTargetScreens() { // return targetScreens; // } // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/overlay/ExpandedViewTest.java import android.app.Activity; import android.view.View; import android.view.ViewGroup; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.Page; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.ObjectUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.android.controller.ActivityController; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.withSettings; package com.mindcoders.phial.internal.overlay; @RunWith(RobolectricTestRunner.class) public class ExpandedViewTest { private ExpandedView view; private ActivityController<Activity> activityController; @Before public void setUp() throws Exception { activityController = Robolectric.buildActivity(Activity.class); activityController.create(); view = new ExpandedView(activityController.get()); activityController.get().setContentView(view); } @Test public void displayPages() throws Exception { View pageView1 = mock(View.class, withSettings().extraInterfaces(PageView.class)); View pageView2 = mock(View.class, withSettings().extraInterfaces(PageView.class)); List<Page> pages = ImmutableList.of( new Page("page1", R.drawable.ic_share, "page1", (context, overlayCallback) -> pageView1), new Page("page2", R.drawable.ic_share, "page2", (context, overlayCallback) -> pageView2) ); Page selectedPage = pages.get(0); view.displayPages(pages, selectedPage, false); ViewGroup iconHolder = view.findViewById(R.id.tab_icons_holder); assertEquals(pages.size() + 1, iconHolder.getChildCount()); for (int i = 0; i < iconHolder.getChildCount(); i++) { View child = iconHolder.getChildAt(i);
assertTrue(child.isSelected() == ObjectUtil.equals(child.getTag(), selectedPage.getId()));
roshakorost/Phial
phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillerBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.text.TextUtils; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package com.mindcoders.phial.autofill; public class AutoFillerBuilder { private final TargetScreen targetScreen; private List<Integer> targetIds; private List<FillOption> options = new ArrayList<>(); AutoFillerBuilder(TargetScreen targetScreen) { this.targetScreen = targetScreen; } /** * Sets view ids to fill. * * @param ids identifiers of views to be filled. Cannot be empty. */ public AutoFillerBuilder fill(int... ids) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillerBuilder.java import android.text.TextUtils; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package com.mindcoders.phial.autofill; public class AutoFillerBuilder { private final TargetScreen targetScreen; private List<Integer> targetIds; private List<FillOption> options = new ArrayList<>(); AutoFillerBuilder(TargetScreen targetScreen) { this.targetScreen = targetScreen; } /** * Sets view ids to fill. * * @param ids identifiers of views to be filled. Cannot be empty. */ public AutoFillerBuilder fill(int... ids) {
Precondition.notEmpty(ids, "ids should not be empty");
roshakorost/Phial
phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillerBuilder.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.text.TextUtils; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package com.mindcoders.phial.autofill; public class AutoFillerBuilder { private final TargetScreen targetScreen; private List<Integer> targetIds; private List<FillOption> options = new ArrayList<>(); AutoFillerBuilder(TargetScreen targetScreen) { this.targetScreen = targetScreen; } /** * Sets view ids to fill. * * @param ids identifiers of views to be filled. Cannot be empty. */ public AutoFillerBuilder fill(int... ids) { Precondition.notEmpty(ids, "ids should not be empty");
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-autofill/src/main/java/com/mindcoders/phial/autofill/AutoFillerBuilder.java import android.text.TextUtils; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.Precondition; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package com.mindcoders.phial.autofill; public class AutoFillerBuilder { private final TargetScreen targetScreen; private List<Integer> targetIds; private List<FillOption> options = new ArrayList<>(); AutoFillerBuilder(TargetScreen targetScreen) { this.targetScreen = targetScreen; } /** * Sets view ids to fill. * * @param ids identifiers of views to be filled. Cannot be empty. */ public AutoFillerBuilder fill(int... ids) { Precondition.notEmpty(ids, "ids should not be empty");
this.targetIds = CollectionUtils.asList(ids);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/share/SystemShareItem.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // }
import android.content.ComponentName; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE;
package com.mindcoders.phial.internal.share; /** * Created by rost on 11/28/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public class SystemShareItem extends ShareItem { private final ComponentName componentName;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/SystemShareItem.java import android.content.ComponentName; import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.ShareDescription; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE; package com.mindcoders.phial.internal.share; /** * Created by rost on 11/28/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public class SystemShareItem extends ShareItem { private final ComponentName componentName;
SystemShareItem(ShareDescription shareDescription, ComponentName componentName) {
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value";
import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value"; // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory);
assertEquals("cat", category.getString(NAME_KEY));
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value";
import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory); assertEquals("cat", category.getString(NAME_KEY));
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value"; // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory); assertEquals("cat", category.getString(NAME_KEY));
final JSONArray entries = category.getJSONArray(ENTRIES_KEY);
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value";
import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory); assertEquals("cat", category.getString(NAME_KEY)); final JSONArray entries = category.getJSONArray(ENTRIES_KEY); assertEquals(2, entries.length()); assertEquals("k1", entries.getJSONObject(0).getString(NAME_KEY));
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String ENTRIES_KEY = "entries"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String NAME_KEY = "name"; // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializer.java // @VisibleForTesting // static final String VALUE_KEY = "value"; // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/keyvalue/KVJsonSerializerTest.java import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.ENTRIES_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.NAME_KEY; import static com.mindcoders.phial.internal.keyvalue.KVJsonSerializer.VALUE_KEY; import static org.junit.Assert.assertEquals; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 11/14/17. */ // need to work with jsonObject @RunWith(RobolectricTestRunner.class) public class KVJsonSerializerTest { private KVJsonSerializer serializer; @Before public void setUp() throws Exception { serializer = new KVJsonSerializer(); } @Test public void createCategoryObject() throws Exception { final KVSaver.KVCategory testCategory = new KVSaver.KVCategory("cat", Arrays.asList( new KVSaver.KVEntry("k1", "v1"), new KVSaver.KVEntry("k2", "v2") )); final JSONObject category = serializer.createCategoryObject(testCategory); assertEquals("cat", category.getString(NAME_KEY)); final JSONArray entries = category.getJSONArray(ENTRIES_KEY); assertEquals(2, entries.length()); assertEquals("k1", entries.getJSONObject(0).getString(NAME_KEY));
assertEquals("v1", entries.getJSONObject(0).getString(VALUE_KEY));
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/PhialErrorPlugins.java // public class PhialErrorPlugins { // public interface ErrorHandler { // void onError(Throwable throwable); // } // // private static ErrorHandler handler; // // public static void setHandler(ErrorHandler handler) { // PhialErrorPlugins.handler = handler; // } // // public static void onError(Throwable throwable) { // if (handler != null) { // handler.onError(throwable); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // }
import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; import com.mindcoders.phial.internal.PhialErrorPlugins; import com.mindcoders.phial.keyvalue.Category; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public final class BuildInfoWriter extends InfoWriter { private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; @Nullable private final Long buildTime; @Nullable private final String buildCommit; public BuildInfoWriter(Context context) { this(context, null, null); } public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { super(context, "Build"); this.buildTime = buildTime; this.buildCommit = buildCommit; } @Override
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/PhialErrorPlugins.java // public class PhialErrorPlugins { // public interface ErrorHandler { // void onError(Throwable throwable); // } // // private static ErrorHandler handler; // // public static void setHandler(ErrorHandler handler) { // PhialErrorPlugins.handler = handler; // } // // public static void onError(Throwable throwable) { // if (handler != null) { // handler.onError(throwable); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; import com.mindcoders.phial.internal.PhialErrorPlugins; import com.mindcoders.phial.keyvalue.Category; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public final class BuildInfoWriter extends InfoWriter { private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; @Nullable private final Long buildTime; @Nullable private final String buildCommit; public BuildInfoWriter(Context context) { this(context, null, null); } public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { super(context, "Build"); this.buildTime = buildTime; this.buildCommit = buildCommit; } @Override
protected void writeInfo(Category category) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/PhialErrorPlugins.java // public class PhialErrorPlugins { // public interface ErrorHandler { // void onError(Throwable throwable); // } // // private static ErrorHandler handler; // // public static void setHandler(ErrorHandler handler) { // PhialErrorPlugins.handler = handler; // } // // public static void onError(Throwable throwable) { // if (handler != null) { // handler.onError(throwable); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // }
import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; import com.mindcoders.phial.internal.PhialErrorPlugins; import com.mindcoders.phial.keyvalue.Category; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public final class BuildInfoWriter extends InfoWriter { private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; @Nullable private final Long buildTime; @Nullable private final String buildCommit; public BuildInfoWriter(Context context) { this(context, null, null); } public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { super(context, "Build"); this.buildTime = buildTime; this.buildCommit = buildCommit; } @Override protected void writeInfo(Category category) { final String packageName = getContext().getPackageName(); category.setKey("Package", packageName); try { final PackageInfo packageInfo = getContext().getPackageManager() .getPackageInfo(packageName, PackageManager.GET_META_DATA); category.setKey("Version", packageInfo.versionName); } catch (PackageManager.NameNotFoundException e) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/PhialErrorPlugins.java // public class PhialErrorPlugins { // public interface ErrorHandler { // void onError(Throwable throwable); // } // // private static ErrorHandler handler; // // public static void setHandler(ErrorHandler handler) { // PhialErrorPlugins.handler = handler; // } // // public static void onError(Throwable throwable) { // if (handler != null) { // handler.onError(throwable); // } // } // } // // Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/BuildInfoWriter.java import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.support.annotation.Nullable; import com.mindcoders.phial.internal.PhialErrorPlugins; import com.mindcoders.phial.keyvalue.Category; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/30/17. */ public final class BuildInfoWriter extends InfoWriter { private final static String DATE_FORMAT = "d MMM yyyy HH:mm Z"; @Nullable private final Long buildTime; @Nullable private final String buildCommit; public BuildInfoWriter(Context context) { this(context, null, null); } public BuildInfoWriter(Context context, @Nullable Long buildTime, @Nullable String buildCommit) { super(context, "Build"); this.buildTime = buildTime; this.buildCommit = buildCommit; } @Override protected void writeInfo(Category category) { final String packageName = getContext().getPackageName(); category.setKey("Package", packageName); try { final PackageInfo packageInfo = getContext().getPackageManager() .getPackageInfo(packageName, PackageManager.GET_META_DATA); category.setKey("Version", packageInfo.versionName); } catch (PackageManager.NameNotFoundException e) {
PhialErrorPlugins.onError(e);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // }
import android.content.Context; import android.os.Build; import android.os.Environment; import android.util.DisplayMetrics; import com.mindcoders.phial.keyvalue.Category; import static android.os.Build.MANUFACTURER;
package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/22/17. */ public final class SystemInfoWriter extends InfoWriter { public SystemInfoWriter(Context context) { super(context, "System"); } @Override
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Category.java // public class Category { // private final String name; // private final List<Saver> savers; // // Category(String name, List<Saver> savers) { // this.name = name; // this.savers = savers; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, String value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, value); // } // return this; // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be under the category set via {@link Phial#category(String)} // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public Category setKey(@NonNull String key, Object value) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.save(name, key, String.valueOf(value)); // } // return this; // } // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from the category set via {@link Phial#category(String)} // * // * @param key to be removed. // */ // public Category removeKey(@NonNull String key) { // verifyKeyIsNotNull(key); // for (Saver saver : savers) { // saver.remove(name, key); // } // return this; // } // // /** // * Clears all the keys associated with this category. // */ // public void clear() { // for (Saver saver : savers) { // saver.remove(name); // } // } // // private void verifyKeyIsNotNull(String key) { // if (key == null) { // throw new IllegalArgumentException("key should not be null."); // } // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/SystemInfoWriter.java import android.content.Context; import android.os.Build; import android.os.Environment; import android.util.DisplayMetrics; import com.mindcoders.phial.keyvalue.Category; import static android.os.Build.MANUFACTURER; package com.mindcoders.phial.internal.keyvalue; /** * Created by rost on 10/22/17. */ public final class SystemInfoWriter extends InfoWriter { public SystemInfoWriter(Context context) { super(context, "System"); } @Override
protected void writeInfo(Category saver) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueAdapter.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVEntry { // private final String name; // private final String value; // // KVEntry(String name, String value) { // this.name = name; // this.value = value; // } // // String getName() { // return name; // } // // String getValue() { // return value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVEntry kvEntry = (KVEntry) o; // // if (name != null ? !name.equals(kvEntry.name) : kvEntry.name != null) return false; // return value != null ? value.equals(kvEntry.value) : kvEntry.value == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // }
import com.mindcoders.phial.R; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVEntry; import java.util.ArrayList; import java.util.List; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView;
package com.mindcoders.phial.internal.keyvalue; final class KeyValueAdapter extends BaseAdapter implements ExpandableListAdapter { private final LayoutInflater layoutInflater;
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVEntry { // private final String name; // private final String value; // // KVEntry(String name, String value) { // this.name = name; // this.value = value; // } // // String getName() { // return name; // } // // String getValue() { // return value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVEntry kvEntry = (KVEntry) o; // // if (name != null ? !name.equals(kvEntry.name) : kvEntry.name != null) return false; // return value != null ? value.equals(kvEntry.value) : kvEntry.value == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueAdapter.java import com.mindcoders.phial.R; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVEntry; import java.util.ArrayList; import java.util.List; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView; package com.mindcoders.phial.internal.keyvalue; final class KeyValueAdapter extends BaseAdapter implements ExpandableListAdapter { private final LayoutInflater layoutInflater;
private final List<KVCategory> items = new ArrayList<>();
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueAdapter.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVEntry { // private final String name; // private final String value; // // KVEntry(String name, String value) { // this.name = name; // this.value = value; // } // // String getName() { // return name; // } // // String getValue() { // return value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVEntry kvEntry = (KVEntry) o; // // if (name != null ? !name.equals(kvEntry.name) : kvEntry.name != null) return false; // return value != null ? value.equals(kvEntry.value) : kvEntry.value == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // }
import com.mindcoders.phial.R; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVEntry; import java.util.ArrayList; import java.util.List; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView;
return items.get(position).getName().hashCode(); } @Override public View getView(int position, View convertView, ViewGroup parent) { return convertView; } public void swapData(List<KVCategory> items) { this.items.clear(); this.items.addAll(items); notifyDataSetChanged(); } @Override public int getGroupCount() { return items.size(); } @Override public int getChildrenCount(int groupPosition) { return getGroup(groupPosition).entries().size(); } @Override public KVCategory getGroup(int groupPosition) { return items.get(groupPosition); } @Override
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVCategory { // private final String name; // private final List<KVEntry> entries; // // KVCategory(String name, List<KVEntry> entries) { // this.name = name; // this.entries = entries; // } // // String getName() { // return name; // } // // List<KVEntry> entries() { // return entries; // } // // boolean isEmpty() { // return entries.isEmpty(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVCategory that = (KVCategory) o; // // if (name != null ? !name.equals(that.name) : that.name != null) return false; // return entries != null ? entries.equals(that.entries) : that.entries == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (entries != null ? entries.hashCode() : 0); // return result; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KVSaver.java // static class KVEntry { // private final String name; // private final String value; // // KVEntry(String name, String value) { // this.name = name; // this.value = value; // } // // String getName() { // return name; // } // // String getValue() { // return value; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // KVEntry kvEntry = (KVEntry) o; // // if (name != null ? !name.equals(kvEntry.name) : kvEntry.name != null) return false; // return value != null ? value.equals(kvEntry.value) : kvEntry.value == null; // } // // @Override // public int hashCode() { // int result = name != null ? name.hashCode() : 0; // result = 31 * result + (value != null ? value.hashCode() : 0); // return result; // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueAdapter.java import com.mindcoders.phial.R; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVCategory; import com.mindcoders.phial.internal.keyvalue.KVSaver.KVEntry; import java.util.ArrayList; import java.util.List; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ExpandableListAdapter; import android.widget.TextView; return items.get(position).getName().hashCode(); } @Override public View getView(int position, View convertView, ViewGroup parent) { return convertView; } public void swapData(List<KVCategory> items) { this.items.clear(); this.items.addAll(items); notifyDataSetChanged(); } @Override public int getGroupCount() { return items.size(); } @Override public int getChildrenCount(int groupPosition) { return getGroup(groupPosition).entries().size(); } @Override public KVCategory getGroup(int groupPosition) { return items.get(groupPosition); } @Override
public KVEntry getChild(int groupPosition, int childPosition) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueView.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // }
import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.view.LayoutInflater; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.FrameLayout; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.Precondition; import java.util.List; import java.util.Observable; import java.util.Observer;
package com.mindcoders.phial.internal.keyvalue; public final class KeyValueView extends FrameLayout implements Observer, PageView { private final KeyValueAdapter adapter; private final KVSaver kvSaver; private ExpandableListView listView; private boolean expandFirst = false; //only for Android Studio tests @VisibleForTesting public KeyValueView(@NonNull Context context) { super(context);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/PageView.java // public interface PageView { // // /** // * Called when device back button has been pressed // * @return true if the event was consumed; false otherwise. // */ // boolean onBackPressed(); // // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/Precondition.java // public final class Precondition { // private Precondition() { // //to hide- // } // // public static <T> T notNull(T item, String message) { // if (item == null) { // throw new IllegalArgumentException(message); // } // // return item; // } // // public static void calledFromTools(View view) { // if (!view.isInEditMode()) { // throw new IllegalArgumentException("should be called only from AndroidStudioTools"); // } // } // // public static void notImplemented(String what, Context context) { // Toast.makeText(context, what + " is NOT Implemented yet", Toast.LENGTH_SHORT).show(); // } // // public static void isTrue(boolean condition, String message) { // if (!condition) { // throw new IllegalArgumentException(message); // } // } // // public static <T> void notEmpty(T[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // // public static void notEmpty(int[] array, String message) { // if (array == null || array.length == 0) { // throw new IllegalArgumentException(message); // } // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/keyvalue/KeyValueView.java import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.view.LayoutInflater; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.FrameLayout; import com.mindcoders.phial.PageView; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.Precondition; import java.util.List; import java.util.Observable; import java.util.Observer; package com.mindcoders.phial.internal.keyvalue; public final class KeyValueView extends FrameLayout implements Observer, PageView { private final KeyValueAdapter adapter; private final KVSaver kvSaver; private ExpandableListView listView; private boolean expandFirst = false; //only for Android Studio tests @VisibleForTesting public KeyValueView(@NonNull Context context) { super(context);
Precondition.calledFromTools(this);
roshakorost/Phial
phial-overlay/src/test/java/com/mindcoders/phial/internal/ScreenTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // }
import android.app.Activity; import android.view.View; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.TargetScreen; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import java.util.Collection; import java.util.Collections; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
package com.mindcoders.phial.internal; @RunWith(RobolectricTestRunner.class) public class ScreenTest { private Screen screen; @Before public void setUp() throws Exception { screen = Screen.empty(); } @Test public void matches_activity() throws Exception {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // Path: phial-overlay/src/test/java/com/mindcoders/phial/internal/ScreenTest.java import android.app.Activity; import android.view.View; import com.google.common.collect.ImmutableList; import com.mindcoders.phial.TargetScreen; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import java.util.Collection; import java.util.Collections; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; package com.mindcoders.phial.internal; @RunWith(RobolectricTestRunner.class) public class ScreenTest { private Screen screen; @Before public void setUp() throws Exception { screen = Screen.empty(); } @Test public void matches_activity() throws Exception {
TargetScreen targetScreen = TargetScreen.forActivity(ActivityA.class);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareAdapter.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // }
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.mindcoders.phial.R; import com.mindcoders.phial.ShareDescription; import java.util.List;
public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView != null) { viewHolder = (ViewHolder) convertView.getTag(); } else { convertView = inflater.inflate(R.layout.listitem_share, parent, false); viewHolder = ViewHolder.create(convertView); convertView.setTag(viewHolder); } viewHolder.bind(getItem(position)); return convertView; } private static class ViewHolder { private final ImageView icon; private final TextView name; ViewHolder(ImageView icon, TextView name) { this.icon = icon; this.name = name; } static ViewHolder create(View convertView) { TextView name = convertView.findViewById(R.id.name); ImageView icon = convertView.findViewById(R.id.icon); return new ViewHolder(icon, name); } void bind(ShareItem shareItem) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/ShareDescription.java // public class ShareDescription { // private final Drawable drawable; // private final CharSequence label; // // /** // * @param drawable icon that will be displayed with share option // * @param label label for share option // */ // public ShareDescription(Drawable drawable, CharSequence label) { // this.drawable = drawable; // this.label = label; // } // // /** // * @param context android context that will be used to load icon and title // * @param drawableRes drawableId that will be displayed with share option // * @param label labelId for share option // */ // public ShareDescription(Context context, @DrawableRes int drawableRes, @StringRes int label) { // this(ContextCompat.getDrawable(context, drawableRes), context.getString(label)); // } // // public Drawable getDrawable() { // return drawable; // } // // public CharSequence getLabel() { // return label; // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/ShareAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.mindcoders.phial.R; import com.mindcoders.phial.ShareDescription; import java.util.List; public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView != null) { viewHolder = (ViewHolder) convertView.getTag(); } else { convertView = inflater.inflate(R.layout.listitem_share, parent, false); viewHolder = ViewHolder.create(convertView); convertView.setTag(viewHolder); } viewHolder.bind(getItem(position)); return convertView; } private static class ViewHolder { private final ImageView icon; private final TextView name; ViewHolder(ImageView icon, TextView name) { this.icon = icon; this.name = name; } static ViewHolder create(View convertView) { TextView name = convertView.findViewById(R.id.name); ImageView icon = convertView.findViewById(R.id.icon); return new ViewHolder(icon, name); } void bind(ShareItem shareItem) {
final ShareDescription description = shareItem.getDescription();
roshakorost/Phial
sample/src/main/java/com/mindcoders/phial/sample/AutoFillActivity.java
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.mindcoders.phial.keyvalue.Phial;
package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class AutoFillActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: phial-key-value/src/main/java/com/mindcoders/phial/keyvalue/Phial.java // public class Phial { // private static final List<Saver> SAVERS = new CopyOnWriteArrayList<>(); // private static final String DEFAULT_CATEGORY_NAME = "Default"; // private static final Category DEFAULT_CATEGORY = new Category(DEFAULT_CATEGORY_NAME, SAVERS); // private static final ConcurrentMap<String, Category> CATEGORIES = new ConcurrentHashMap<>(); // // static { // CATEGORIES.put(DEFAULT_CATEGORY_NAME, DEFAULT_CATEGORY); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(String key, String value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // /** // * Sets a value to be associated with your debug data. // * Entry will be set under default category. // * <p> // * Note: setKey(key, null) will set associated value to null. In order to remove entry use {@link Phial#removeKey(String)} // * // * @param key of the debug data // * @param value associated value // */ // public static void setKey(@NonNull String key, @Nullable Object value) { // DEFAULT_CATEGORY.setKey(key, value); // } // // // /** // * Removes entry with given key from debug data. // * <p> // * Note: Entry would be removed only from default category. // * // * @param key to be removed. // */ // public static void removeKey(String key) { // DEFAULT_CATEGORY.removeKey(key); // } // // /** // * Creates category that can be used for adding key values // */ // public static Category category(String name) { // CATEGORIES.putIfAbsent(name, new Category(name, SAVERS)); // return CATEGORIES.get(name); // } // // /** // * Removes category and associated keys. // */ // public static void removeCategory(String name) { // Category category = CATEGORIES.remove(name); // category.clear(); // } // // /** // * Add a new saver. // */ // public static void addSaver(Saver saver) { // SAVERS.add(saver); // } // // // /** // * Remove previously added saver // */ // public static void removeSaver(Saver saver) { // SAVERS.remove(saver); // } // // @VisibleForTesting // static void cleanSavers() { // SAVERS.clear(); // } // } // Path: sample/src/main/java/com/mindcoders/phial/sample/AutoFillActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.mindcoders.phial.keyvalue.Phial; package com.mindcoders.phial.sample; /** * Created by rost on 11/8/17. */ public class AutoFillActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Phial.setKey("currentActivity", getClass().getSimpleName());
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/PhialButton.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/support/ContextCompat.java // public final class ContextCompat { // private ContextCompat() { // //to hide // } // // @SuppressWarnings("deprecation") // public static Drawable getDrawable(Context context, @DrawableRes int id) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // return context.getDrawable(id); // } // // return context.getResources().getDrawable(id); // } // }
import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.util.AttributeSet; import android.view.View; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.support.ContextCompat;
if (!isInEditMode()) { setLayerType(LAYER_TYPE_SOFTWARE, bgPaint); } setupColors(); } public void setIcon(Drawable drawable) { if (drawable != null) { icon = drawable.mutate(); } else { icon = null; } refreshDrawableState(); invalidate(); } public void setIcon(Bitmap bitmap) { if (bitmap != null) { setIcon(new BitmapDrawable(getResources(), bitmap)); } else { setIcon((Drawable) null); } } public Drawable getIcon() { return icon; } public void setIcon(@DrawableRes int iconId) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/support/ContextCompat.java // public final class ContextCompat { // private ContextCompat() { // //to hide // } // // @SuppressWarnings("deprecation") // public static Drawable getDrawable(Context context, @DrawableRes int id) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // return context.getDrawable(id); // } // // return context.getResources().getDrawable(id); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/overlay/PhialButton.java import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.util.AttributeSet; import android.view.View; import com.mindcoders.phial.R; import com.mindcoders.phial.internal.util.support.ContextCompat; if (!isInEditMode()) { setLayerType(LAYER_TYPE_SOFTWARE, bgPaint); } setupColors(); } public void setIcon(Drawable drawable) { if (drawable != null) { icon = drawable.mutate(); } else { icon = null; } refreshDrawableState(); invalidate(); } public void setIcon(Bitmap bitmap) { if (bitmap != null) { setIcon(new BitmapDrawable(getResources(), bitmap)); } else { setIcon((Drawable) null); } } public Drawable getIcon() { return icon; } public void setIcon(@DrawableRes int iconId) {
setIcon(ContextCompat.getDrawable(getContext(), iconId));
roshakorost/Phial
phial-autofill/src/test/java/com/mindcoders/phial/autofill/ConfigManagerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // }
import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.mindcoders.phial.autofill; /** * Created by rost on 11/16/17. */ public class ConfigManagerTest { private Store store; private FillConfig config; private ConfigManager configManager; @Before public void setUp() throws Exception { store = mock(Store.class);
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // Path: phial-autofill/src/test/java/com/mindcoders/phial/autofill/ConfigManagerTest.java import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.mindcoders.phial.autofill; /** * Created by rost on 11/16/17. */ public class ConfigManagerTest { private Store store; private FillConfig config; private ConfigManager configManager; @Before public void setUp() throws Exception { store = mock(Store.class);
final List<Integer> ids = CollectionUtils.asList(-2, -1);
roshakorost/Phial
phial-autofill/src/test/java/com/mindcoders/phial/autofill/ConfigManagerTest.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // }
import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package com.mindcoders.phial.autofill; /** * Created by rost on 11/16/17. */ public class ConfigManagerTest { private Store store; private FillConfig config; private ConfigManager configManager; @Before public void setUp() throws Exception { store = mock(Store.class); final List<Integer> ids = CollectionUtils.asList(-2, -1); final List<FillOption> options = simpleOptions("opt1", "opt2");
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // Path: phial-autofill/src/test/java/com/mindcoders/phial/autofill/ConfigManagerTest.java import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package com.mindcoders.phial.autofill; /** * Created by rost on 11/16/17. */ public class ConfigManagerTest { private Store store; private FillConfig config; private ConfigManager configManager; @Before public void setUp() throws Exception { store = mock(Store.class); final List<Integer> ids = CollectionUtils.asList(-2, -1); final List<FillOption> options = simpleOptions("opt1", "opt2");
config = new FillConfig(mock(TargetScreen.class), options, ids);
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.mindcoders.phial.internal; public class Screen { private Activity activity; private Map<String, WeakReference<View>> scopes = Collections.synchronizedMap(new HashMap<String, WeakReference<View>>()); Screen(Activity activity, String scopeName) { this.activity = activity; } static Screen empty() { return new Screen(null, null); } void enterScope(String scopeName, View view) { this.scopes.put(scopeName, new WeakReference<>(view)); } void exitScope(String scopeName) { this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; }
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.mindcoders.phial.internal; public class Screen { private Activity activity; private Map<String, WeakReference<View>> scopes = Collections.synchronizedMap(new HashMap<String, WeakReference<View>>()); Screen(Activity activity, String scopeName) { this.activity = activity; } static Screen empty() { return new Screen(null, null); } void enterScope(String scopeName, View view) { this.scopes.put(scopeName, new WeakReference<>(view)); } void exitScope(String scopeName) { this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; }
public boolean matches(TargetScreen screen) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map;
package com.mindcoders.phial.internal; public class Screen { private Activity activity; private Map<String, WeakReference<View>> scopes = Collections.synchronizedMap(new HashMap<String, WeakReference<View>>()); Screen(Activity activity, String scopeName) { this.activity = activity; } static Screen empty() { return new Screen(null, null); } void enterScope(String scopeName, View view) { this.scopes.put(scopeName, new WeakReference<>(view)); } void exitScope(String scopeName) { this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; } public boolean matches(TargetScreen screen) { if (activity == null) { return false; } if (screen.getScopeName() != null) { final boolean sameScope = scopes.containsKey(screen.getScopeName()); if (!sameScope) { return false; } } if (screen.getTargetActivity() != null) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; package com.mindcoders.phial.internal; public class Screen { private Activity activity; private Map<String, WeakReference<View>> scopes = Collections.synchronizedMap(new HashMap<String, WeakReference<View>>()); Screen(Activity activity, String scopeName) { this.activity = activity; } static Screen empty() { return new Screen(null, null); } void enterScope(String scopeName, View view) { this.scopes.put(scopeName, new WeakReference<>(view)); } void exitScope(String scopeName) { this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; } public boolean matches(TargetScreen screen) { if (activity == null) { return false; } if (screen.getScopeName() != null) { final boolean sameScope = scopes.containsKey(screen.getScopeName()); if (!sameScope) { return false; } } if (screen.getTargetActivity() != null) {
final boolean activityMatches = ObjectUtil.equals(screen.getTargetActivity(), activity.getClass());
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // }
import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map;
this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; } public boolean matches(TargetScreen screen) { if (activity == null) { return false; } if (screen.getScopeName() != null) { final boolean sameScope = scopes.containsKey(screen.getScopeName()); if (!sameScope) { return false; } } if (screen.getTargetActivity() != null) { final boolean activityMatches = ObjectUtil.equals(screen.getTargetActivity(), activity.getClass()); if (!activityMatches) { return false; } } return true; } public boolean matchesAny(Collection<TargetScreen> screens) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/CollectionUtils.java // public final class CollectionUtils { // // private CollectionUtils() { // // hide // } // // // public interface Predicate<T> { // boolean apply(T type); // } // // public interface Function1<T, G> { // T call(G value); // } // // public static <L> ArrayList<L> filter(List<L> list, Predicate<L> predicate) { // ArrayList<L> result = new ArrayList<L>(); // for (L element : list) { // if (predicate.apply(element)) { // result.add(element); // } // } // return result; // } // // public static <T, G> ArrayList<T> map(List<G> input, Function1<T, G> function) { // ArrayList<T> result = new ArrayList<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static <T, G> Set<T> map(Set<G> input, Function1<T, G> function) { // Set<T> result = new HashSet<T>(input.size()); // for (G item : input) { // result.add(function.call(item)); // } // return result; // } // // public static boolean isNullOrEmpty(Collection<?> input) { // return input == null || input.isEmpty(); // } // // public static List<Integer> asList(int... ids) { // final List<Integer> result = new ArrayList<>(ids.length); // for (int id : ids) { // result.add(id); // } // return result; // } // // public static <T> Set<T> asSet(T... items) { // final HashSet<T> result = new HashSet<>(items.length); // result.addAll(Arrays.asList(items)); // return Collections.unmodifiableSet(result); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/Screen.java import android.app.Activity; import android.support.annotation.Nullable; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.CollectionUtils; import com.mindcoders.phial.internal.util.ObjectUtil; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; this.scopes.remove(scopeName); } void clearActivity() { this.activity = null; } public boolean matches(TargetScreen screen) { if (activity == null) { return false; } if (screen.getScopeName() != null) { final boolean sameScope = scopes.containsKey(screen.getScopeName()); if (!sameScope) { return false; } } if (screen.getTargetActivity() != null) { final boolean activityMatches = ObjectUtil.equals(screen.getTargetActivity(), activity.getClass()); if (!activityMatches) { return false; } } return true; } public boolean matchesAny(Collection<TargetScreen> screens) {
if (CollectionUtils.isNullOrEmpty(screens)) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/share/UserShareItem.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // }
import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE;
package com.mindcoders.phial.internal.share; /** * Created by rost on 11/28/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public class UserShareItem extends ShareItem {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/Shareable.java // public interface Shareable { // /** // * Is called when user selects provided share option. // * <p> // * At the end of share should notify Phial about result of sharing by calling one of // * {@link ShareContext#onSuccess()} // * {@link ShareContext#onFailed(String)} // * {@link ShareContext#onCancel()} // * <p> // * ShareContext can be used in order to show your custom view or progress when user selected your share option // * see {@link ShareContext} // * // * @param shareContext used in order to communicate with Phial // * @param zippedAttachment file that should be shared // * @param message message provided by user // */ // void share(ShareContext shareContext, File zippedAttachment, String message); // // /** // * Sets icon and title for ShareOption // * // * @return ShareDescription with icon and title // */ // ShareDescription getDescription(); // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/share/UserShareItem.java import android.support.annotation.VisibleForTesting; import com.mindcoders.phial.Shareable; import static android.support.annotation.VisibleForTesting.PACKAGE_PRIVATE; package com.mindcoders.phial.internal.share; /** * Created by rost on 11/28/17. */ @VisibleForTesting(otherwise = PACKAGE_PRIVATE) public class UserShareItem extends ShareItem {
private final Shareable shareable;
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleActivityLifecycleCallbacks.java // public class SimpleActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // //optional // } // // @Override // public void onActivityStarted(Activity activity) { // //optional // } // // @Override // public void onActivityResumed(Activity activity) { // //optional // } // // @Override // public void onActivityPaused(Activity activity) { // //optional // } // // @Override // public void onActivityStopped(Activity activity) { // //optional // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // //optional // } // // @Override // public void onActivityDestroyed(Activity activity) { // //optional // } // }
import android.app.Activity; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.ObjectUtil; import com.mindcoders.phial.internal.util.SimpleActivityLifecycleCallbacks; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList;
package com.mindcoders.phial.internal; /** * Created by rost on 11/3/17. */ public class ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { public interface ScreenListener { void onScreenChanged(Screen screen); } private final Screen currentScreen = Screen.empty(); private final List<ScreenListener> listeners = new CopyOnWriteArrayList<>(); public void addListener(ScreenListener listener) { listeners.add(listener); } public void removeListener(ScreenListener listener) { listeners.remove(listener); } public Screen getCurrentScreen() { return currentScreen; } @Override public void onActivityResumed(Activity activity) { currentScreen.setActivity(activity); fireOnScreenChanged(); } @Override public void onActivityPaused(Activity activity) {
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleActivityLifecycleCallbacks.java // public class SimpleActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // //optional // } // // @Override // public void onActivityStarted(Activity activity) { // //optional // } // // @Override // public void onActivityResumed(Activity activity) { // //optional // } // // @Override // public void onActivityPaused(Activity activity) { // //optional // } // // @Override // public void onActivityStopped(Activity activity) { // //optional // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // //optional // } // // @Override // public void onActivityDestroyed(Activity activity) { // //optional // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java import android.app.Activity; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.ObjectUtil; import com.mindcoders.phial.internal.util.SimpleActivityLifecycleCallbacks; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; package com.mindcoders.phial.internal; /** * Created by rost on 11/3/17. */ public class ScreenTracker extends SimpleActivityLifecycleCallbacks implements PhialScopeNotifier.OnScopeChangedListener { public interface ScreenListener { void onScreenChanged(Screen screen); } private final Screen currentScreen = Screen.empty(); private final List<ScreenListener> listeners = new CopyOnWriteArrayList<>(); public void addListener(ScreenListener listener) { listeners.add(listener); } public void removeListener(ScreenListener listener) { listeners.remove(listener); } public Screen getCurrentScreen() { return currentScreen; } @Override public void onActivityResumed(Activity activity) { currentScreen.setActivity(activity); fireOnScreenChanged(); } @Override public void onActivityPaused(Activity activity) {
if (ObjectUtil.equals(activity, currentScreen.getActivity())) {
roshakorost/Phial
phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleActivityLifecycleCallbacks.java // public class SimpleActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // //optional // } // // @Override // public void onActivityStarted(Activity activity) { // //optional // } // // @Override // public void onActivityResumed(Activity activity) { // //optional // } // // @Override // public void onActivityPaused(Activity activity) { // //optional // } // // @Override // public void onActivityStopped(Activity activity) { // //optional // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // //optional // } // // @Override // public void onActivityDestroyed(Activity activity) { // //optional // } // }
import android.app.Activity; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.ObjectUtil; import com.mindcoders.phial.internal.util.SimpleActivityLifecycleCallbacks; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList;
public void onActivityPaused(Activity activity) { if (ObjectUtil.equals(activity, currentScreen.getActivity())) { currentScreen.clearActivity(); fireOnScreenChanged(); } } private void fireOnScreenChanged() { for (ScreenListener listener : listeners) { listener.onScreenChanged(currentScreen); } } @Override public void onEnterScope(String scopeName, View view) { currentScreen.enterScope(scopeName, view); fireOnScreenChanged(); } @Override public void onExitScope(String scopeName) { currentScreen.exitScope(scopeName); fireOnScreenChanged(); } void destroy() { listeners.clear(); currentScreen.clearActivity(); }
// Path: phial-overlay/src/main/java/com/mindcoders/phial/TargetScreen.java // public class TargetScreen { // private final Class<? extends Activity> target; // private final String scope; // // // TargetScreen(Class<? extends Activity> target, String scope) { // this.target = target; // this.scope = scope; // } // // /** // * Creates a {@link TargetScreen} with activity as a target. // * @param target activity. // */ // public static TargetScreen forActivity(Class<? extends Activity> target) { // return new TargetScreen(target, null); // } // // /** // * Creates a {@link TargetScreen} with custom scope as a target. // * @param scope scope name. // */ // public static TargetScreen forScope(String scope) { // return new TargetScreen(null, scope); // } // // public Class<? extends Activity> getTargetActivity() { // return target; // } // // public String getScopeName() { // return scope; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TargetScreen that = (TargetScreen) o; // // if (target != null ? !target.equals(that.target) : that.target != null) return false; // return scope != null ? scope.equals(that.scope) : that.scope == null; // } // // @Override // public int hashCode() { // int result = target != null ? target.hashCode() : 0; // result = 31 * result + (scope != null ? scope.hashCode() : 0); // return result; // } // // /** // * Returns either activity name or custom scope name. // * @return target name. // */ // public String getName() { // if (target != null) { // return target.getSimpleName(); // } // // return scope; // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/ObjectUtil.java // public final class ObjectUtil { // private ObjectUtil() { // //to hide // } // // public static <T> boolean equals(T a, T b) { // return (a == b) || (a != null && a.equals(b)); // } // } // // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/util/SimpleActivityLifecycleCallbacks.java // public class SimpleActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // //optional // } // // @Override // public void onActivityStarted(Activity activity) { // //optional // } // // @Override // public void onActivityResumed(Activity activity) { // //optional // } // // @Override // public void onActivityPaused(Activity activity) { // //optional // } // // @Override // public void onActivityStopped(Activity activity) { // //optional // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // //optional // } // // @Override // public void onActivityDestroyed(Activity activity) { // //optional // } // } // Path: phial-overlay/src/main/java/com/mindcoders/phial/internal/ScreenTracker.java import android.app.Activity; import android.view.View; import com.mindcoders.phial.TargetScreen; import com.mindcoders.phial.internal.util.ObjectUtil; import com.mindcoders.phial.internal.util.SimpleActivityLifecycleCallbacks; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; public void onActivityPaused(Activity activity) { if (ObjectUtil.equals(activity, currentScreen.getActivity())) { currentScreen.clearActivity(); fireOnScreenChanged(); } } private void fireOnScreenChanged() { for (ScreenListener listener : listeners) { listener.onScreenChanged(currentScreen); } } @Override public void onEnterScope(String scopeName, View view) { currentScreen.enterScope(scopeName, view); fireOnScreenChanged(); } @Override public void onExitScope(String scopeName) { currentScreen.exitScope(scopeName); fireOnScreenChanged(); } void destroy() { listeners.clear(); currentScreen.clearActivity(); }
public boolean matchesAny(Set<TargetScreen> targetScreen) {
bitwit/postcard-android
postcard/src/main/java/ca/bitwit/postcard/network/SocialActivity.java
// Path: postcard/src/main/java/ca/bitwit/postcard/MessageAttachment.java // public class MessageAttachment{ // // public Double progress; //note: an NSProgress in OBJC // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageLink.java // public class MessageLink extends MessageAttachment{ // // public String url; // public String title; // public String description; // public String imageLocation; // // private String originalUrlSubmitted; // private String contentType; // // private Dictionary metaMap; // // public MessageLink(){ // /* // self.metaMap = @{ // @"title" : @[ // @"og:title", // @"twitter:title" // ], // @"description" : @[ // @"og:description", // @"twitter:description" // ], // @"imageURL" : @[ // @"og:image", // @"twitter:image", // ] // }; // */ // } // // public void setMessageLinkUrl(String urlString){ // this.originalUrlSubmitted = urlString; // this.progress = 0.0; // this.url = urlString; //TODO: clean URL [PCURLMaker validURLStringForString:url withBaseURL:nil]; // this.setParseProgress(0.1); // this.parseUrlForMeta(); // } // // public String originalUrl(){ // return this.originalUrlSubmitted; // } // // public void parseUrlForMeta(){ // // } // // public void handleContentType(){ // // } // // public void parseHTMLPageForMeta(){ // // } // // public void setParseProgress(Double progress){ // // } // // public void completeLinkParsing(){ // // } // // public void downloadImage(){ // // } // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageMedia.java // public class MessageMedia extends MessageAttachment{ // // public String mimeType; // // public String imageLocation = null; // public ByteBuffer imageData; // // public String videoLocation; // public ByteBuffer videoData; // // public MessageMedia(){} // // public void setupWithContentUrl(String urlString){ // /* // self.progress = [NSProgress progressWithTotalUnitCount:100]; // NSURLRequest *request = [NSURLRequest requestWithURL:contentUrl]; // AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op, id responseObject) { // BWNetLog(@"Success"); // NSArray *imageTypes = @[ // @"jpg", // @"png", // @"gif", // ]; // // BOOL isImage = NO; // for(NSString *supportedType in imageTypes) { // if([supportedType caseInsensitiveCompare:contentUrl.pathExtension]) { // isImage = YES; // break; // } // } // // if (isImage) { // //its an image // self.imageData = op.responseData; // self.image = [UIImage imageWithData:_imageData]; // self.mimeType = [NSString stringWithFormat:@"image/%@", contentUrl.pathExtension]; // self.progress.completedUnitCount = 100; // } else { // self.videoData = op.responseData; // NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]]; //add our image to the path // [_videoData writeToFile:fullPath atomically:YES]; // // BWLog(@"Video path -> %@", fullPath); // AVURLAsset *avUrlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:fullPath] options:nil]; // BWLog(@"AV URL Asset -> %@", avUrlAsset); // // AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avUrlAsset]; // // NSArray *tracks = [avUrlAsset tracksWithMediaType:AVMediaTypeVideo]; // AVAssetTrack *track = [tracks objectAtIndex:0]; // // generator.maximumSize = track.naturalSize; // generator.appliesPreferredTrackTransform = YES; // [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]] // completionHandler:^(CMTime requestedTime, CGImageRef cgImage, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) { // if (result == AVAssetImageGeneratorSucceeded) { // UIImage *newImage = [UIImage imageWithCGImage:cgImage]; // self.image = newImage; // BWLog(@"Dropbox Video -- Image Asset created"); // self.progress.completedUnitCount = 100; // } // }]; // } // } failure:^(AFHTTPRequestOperation *op, NSError *error) { // BWNetLog(@"Failure -- %@", error.description); // }]; // // [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long int totalBytesRead, long long int totalBytesExpectedToRead) { // int completion = (int)(totalBytesExpectedToRead/totalBytesExpectedToRead * 90); //up to 90% of the completion // self.progress.completedUnitCount = completion; // }]; // [operation start]; // * */ // } // // public Integer length(){ // if (this.videoData != null){ // return this.videoData.capacity(); // } else { // return this.imageData.capacity(); // } // } // // }
import ca.bitwit.postcard.MessageAttachment; import ca.bitwit.postcard.MessageLink; import ca.bitwit.postcard.MessageMedia; import java.lang.Boolean; import java.lang.Integer; import java.util.ArrayList; import java.util.Dictionary; import java.io.File; import java.util.List;
package ca.bitwit.postcard.network; public class SocialActivity { public List<Network> networks; public String date; public String message; public String tags;
// Path: postcard/src/main/java/ca/bitwit/postcard/MessageAttachment.java // public class MessageAttachment{ // // public Double progress; //note: an NSProgress in OBJC // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageLink.java // public class MessageLink extends MessageAttachment{ // // public String url; // public String title; // public String description; // public String imageLocation; // // private String originalUrlSubmitted; // private String contentType; // // private Dictionary metaMap; // // public MessageLink(){ // /* // self.metaMap = @{ // @"title" : @[ // @"og:title", // @"twitter:title" // ], // @"description" : @[ // @"og:description", // @"twitter:description" // ], // @"imageURL" : @[ // @"og:image", // @"twitter:image", // ] // }; // */ // } // // public void setMessageLinkUrl(String urlString){ // this.originalUrlSubmitted = urlString; // this.progress = 0.0; // this.url = urlString; //TODO: clean URL [PCURLMaker validURLStringForString:url withBaseURL:nil]; // this.setParseProgress(0.1); // this.parseUrlForMeta(); // } // // public String originalUrl(){ // return this.originalUrlSubmitted; // } // // public void parseUrlForMeta(){ // // } // // public void handleContentType(){ // // } // // public void parseHTMLPageForMeta(){ // // } // // public void setParseProgress(Double progress){ // // } // // public void completeLinkParsing(){ // // } // // public void downloadImage(){ // // } // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageMedia.java // public class MessageMedia extends MessageAttachment{ // // public String mimeType; // // public String imageLocation = null; // public ByteBuffer imageData; // // public String videoLocation; // public ByteBuffer videoData; // // public MessageMedia(){} // // public void setupWithContentUrl(String urlString){ // /* // self.progress = [NSProgress progressWithTotalUnitCount:100]; // NSURLRequest *request = [NSURLRequest requestWithURL:contentUrl]; // AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op, id responseObject) { // BWNetLog(@"Success"); // NSArray *imageTypes = @[ // @"jpg", // @"png", // @"gif", // ]; // // BOOL isImage = NO; // for(NSString *supportedType in imageTypes) { // if([supportedType caseInsensitiveCompare:contentUrl.pathExtension]) { // isImage = YES; // break; // } // } // // if (isImage) { // //its an image // self.imageData = op.responseData; // self.image = [UIImage imageWithData:_imageData]; // self.mimeType = [NSString stringWithFormat:@"image/%@", contentUrl.pathExtension]; // self.progress.completedUnitCount = 100; // } else { // self.videoData = op.responseData; // NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]]; //add our image to the path // [_videoData writeToFile:fullPath atomically:YES]; // // BWLog(@"Video path -> %@", fullPath); // AVURLAsset *avUrlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:fullPath] options:nil]; // BWLog(@"AV URL Asset -> %@", avUrlAsset); // // AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avUrlAsset]; // // NSArray *tracks = [avUrlAsset tracksWithMediaType:AVMediaTypeVideo]; // AVAssetTrack *track = [tracks objectAtIndex:0]; // // generator.maximumSize = track.naturalSize; // generator.appliesPreferredTrackTransform = YES; // [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]] // completionHandler:^(CMTime requestedTime, CGImageRef cgImage, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) { // if (result == AVAssetImageGeneratorSucceeded) { // UIImage *newImage = [UIImage imageWithCGImage:cgImage]; // self.image = newImage; // BWLog(@"Dropbox Video -- Image Asset created"); // self.progress.completedUnitCount = 100; // } // }]; // } // } failure:^(AFHTTPRequestOperation *op, NSError *error) { // BWNetLog(@"Failure -- %@", error.description); // }]; // // [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long int totalBytesRead, long long int totalBytesExpectedToRead) { // int completion = (int)(totalBytesExpectedToRead/totalBytesExpectedToRead * 90); //up to 90% of the completion // self.progress.completedUnitCount = completion; // }]; // [operation start]; // * */ // } // // public Integer length(){ // if (this.videoData != null){ // return this.videoData.capacity(); // } else { // return this.imageData.capacity(); // } // } // // } // Path: postcard/src/main/java/ca/bitwit/postcard/network/SocialActivity.java import ca.bitwit.postcard.MessageAttachment; import ca.bitwit.postcard.MessageLink; import ca.bitwit.postcard.MessageMedia; import java.lang.Boolean; import java.lang.Integer; import java.util.ArrayList; import java.util.Dictionary; import java.io.File; import java.util.List; package ca.bitwit.postcard.network; public class SocialActivity { public List<Network> networks; public String date; public String message; public String tags;
public MessageLink messageLink;
bitwit/postcard-android
postcard/src/main/java/ca/bitwit/postcard/network/SocialActivity.java
// Path: postcard/src/main/java/ca/bitwit/postcard/MessageAttachment.java // public class MessageAttachment{ // // public Double progress; //note: an NSProgress in OBJC // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageLink.java // public class MessageLink extends MessageAttachment{ // // public String url; // public String title; // public String description; // public String imageLocation; // // private String originalUrlSubmitted; // private String contentType; // // private Dictionary metaMap; // // public MessageLink(){ // /* // self.metaMap = @{ // @"title" : @[ // @"og:title", // @"twitter:title" // ], // @"description" : @[ // @"og:description", // @"twitter:description" // ], // @"imageURL" : @[ // @"og:image", // @"twitter:image", // ] // }; // */ // } // // public void setMessageLinkUrl(String urlString){ // this.originalUrlSubmitted = urlString; // this.progress = 0.0; // this.url = urlString; //TODO: clean URL [PCURLMaker validURLStringForString:url withBaseURL:nil]; // this.setParseProgress(0.1); // this.parseUrlForMeta(); // } // // public String originalUrl(){ // return this.originalUrlSubmitted; // } // // public void parseUrlForMeta(){ // // } // // public void handleContentType(){ // // } // // public void parseHTMLPageForMeta(){ // // } // // public void setParseProgress(Double progress){ // // } // // public void completeLinkParsing(){ // // } // // public void downloadImage(){ // // } // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageMedia.java // public class MessageMedia extends MessageAttachment{ // // public String mimeType; // // public String imageLocation = null; // public ByteBuffer imageData; // // public String videoLocation; // public ByteBuffer videoData; // // public MessageMedia(){} // // public void setupWithContentUrl(String urlString){ // /* // self.progress = [NSProgress progressWithTotalUnitCount:100]; // NSURLRequest *request = [NSURLRequest requestWithURL:contentUrl]; // AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op, id responseObject) { // BWNetLog(@"Success"); // NSArray *imageTypes = @[ // @"jpg", // @"png", // @"gif", // ]; // // BOOL isImage = NO; // for(NSString *supportedType in imageTypes) { // if([supportedType caseInsensitiveCompare:contentUrl.pathExtension]) { // isImage = YES; // break; // } // } // // if (isImage) { // //its an image // self.imageData = op.responseData; // self.image = [UIImage imageWithData:_imageData]; // self.mimeType = [NSString stringWithFormat:@"image/%@", contentUrl.pathExtension]; // self.progress.completedUnitCount = 100; // } else { // self.videoData = op.responseData; // NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]]; //add our image to the path // [_videoData writeToFile:fullPath atomically:YES]; // // BWLog(@"Video path -> %@", fullPath); // AVURLAsset *avUrlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:fullPath] options:nil]; // BWLog(@"AV URL Asset -> %@", avUrlAsset); // // AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avUrlAsset]; // // NSArray *tracks = [avUrlAsset tracksWithMediaType:AVMediaTypeVideo]; // AVAssetTrack *track = [tracks objectAtIndex:0]; // // generator.maximumSize = track.naturalSize; // generator.appliesPreferredTrackTransform = YES; // [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]] // completionHandler:^(CMTime requestedTime, CGImageRef cgImage, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) { // if (result == AVAssetImageGeneratorSucceeded) { // UIImage *newImage = [UIImage imageWithCGImage:cgImage]; // self.image = newImage; // BWLog(@"Dropbox Video -- Image Asset created"); // self.progress.completedUnitCount = 100; // } // }]; // } // } failure:^(AFHTTPRequestOperation *op, NSError *error) { // BWNetLog(@"Failure -- %@", error.description); // }]; // // [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long int totalBytesRead, long long int totalBytesExpectedToRead) { // int completion = (int)(totalBytesExpectedToRead/totalBytesExpectedToRead * 90); //up to 90% of the completion // self.progress.completedUnitCount = completion; // }]; // [operation start]; // * */ // } // // public Integer length(){ // if (this.videoData != null){ // return this.videoData.capacity(); // } else { // return this.imageData.capacity(); // } // } // // }
import ca.bitwit.postcard.MessageAttachment; import ca.bitwit.postcard.MessageLink; import ca.bitwit.postcard.MessageMedia; import java.lang.Boolean; import java.lang.Integer; import java.util.ArrayList; import java.util.Dictionary; import java.io.File; import java.util.List;
package ca.bitwit.postcard.network; public class SocialActivity { public List<Network> networks; public String date; public String message; public String tags; public MessageLink messageLink;
// Path: postcard/src/main/java/ca/bitwit/postcard/MessageAttachment.java // public class MessageAttachment{ // // public Double progress; //note: an NSProgress in OBJC // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageLink.java // public class MessageLink extends MessageAttachment{ // // public String url; // public String title; // public String description; // public String imageLocation; // // private String originalUrlSubmitted; // private String contentType; // // private Dictionary metaMap; // // public MessageLink(){ // /* // self.metaMap = @{ // @"title" : @[ // @"og:title", // @"twitter:title" // ], // @"description" : @[ // @"og:description", // @"twitter:description" // ], // @"imageURL" : @[ // @"og:image", // @"twitter:image", // ] // }; // */ // } // // public void setMessageLinkUrl(String urlString){ // this.originalUrlSubmitted = urlString; // this.progress = 0.0; // this.url = urlString; //TODO: clean URL [PCURLMaker validURLStringForString:url withBaseURL:nil]; // this.setParseProgress(0.1); // this.parseUrlForMeta(); // } // // public String originalUrl(){ // return this.originalUrlSubmitted; // } // // public void parseUrlForMeta(){ // // } // // public void handleContentType(){ // // } // // public void parseHTMLPageForMeta(){ // // } // // public void setParseProgress(Double progress){ // // } // // public void completeLinkParsing(){ // // } // // public void downloadImage(){ // // } // // } // // Path: postcard/src/main/java/ca/bitwit/postcard/MessageMedia.java // public class MessageMedia extends MessageAttachment{ // // public String mimeType; // // public String imageLocation = null; // public ByteBuffer imageData; // // public String videoLocation; // public ByteBuffer videoData; // // public MessageMedia(){} // // public void setupWithContentUrl(String urlString){ // /* // self.progress = [NSProgress progressWithTotalUnitCount:100]; // NSURLRequest *request = [NSURLRequest requestWithURL:contentUrl]; // AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op, id responseObject) { // BWNetLog(@"Success"); // NSArray *imageTypes = @[ // @"jpg", // @"png", // @"gif", // ]; // // BOOL isImage = NO; // for(NSString *supportedType in imageTypes) { // if([supportedType caseInsensitiveCompare:contentUrl.pathExtension]) { // isImage = YES; // break; // } // } // // if (isImage) { // //its an image // self.imageData = op.responseData; // self.image = [UIImage imageWithData:_imageData]; // self.mimeType = [NSString stringWithFormat:@"image/%@", contentUrl.pathExtension]; // self.progress.completedUnitCount = 100; // } else { // self.videoData = op.responseData; // NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; // NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"video.mp4"]]; //add our image to the path // [_videoData writeToFile:fullPath atomically:YES]; // // BWLog(@"Video path -> %@", fullPath); // AVURLAsset *avUrlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:fullPath] options:nil]; // BWLog(@"AV URL Asset -> %@", avUrlAsset); // // AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:avUrlAsset]; // // NSArray *tracks = [avUrlAsset tracksWithMediaType:AVMediaTypeVideo]; // AVAssetTrack *track = [tracks objectAtIndex:0]; // // generator.maximumSize = track.naturalSize; // generator.appliesPreferredTrackTransform = YES; // [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]] // completionHandler:^(CMTime requestedTime, CGImageRef cgImage, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) { // if (result == AVAssetImageGeneratorSucceeded) { // UIImage *newImage = [UIImage imageWithCGImage:cgImage]; // self.image = newImage; // BWLog(@"Dropbox Video -- Image Asset created"); // self.progress.completedUnitCount = 100; // } // }]; // } // } failure:^(AFHTTPRequestOperation *op, NSError *error) { // BWNetLog(@"Failure -- %@", error.description); // }]; // // [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long int totalBytesRead, long long int totalBytesExpectedToRead) { // int completion = (int)(totalBytesExpectedToRead/totalBytesExpectedToRead * 90); //up to 90% of the completion // self.progress.completedUnitCount = completion; // }]; // [operation start]; // * */ // } // // public Integer length(){ // if (this.videoData != null){ // return this.videoData.capacity(); // } else { // return this.imageData.capacity(); // } // } // // } // Path: postcard/src/main/java/ca/bitwit/postcard/network/SocialActivity.java import ca.bitwit.postcard.MessageAttachment; import ca.bitwit.postcard.MessageLink; import ca.bitwit.postcard.MessageMedia; import java.lang.Boolean; import java.lang.Integer; import java.util.ArrayList; import java.util.Dictionary; import java.io.File; import java.util.List; package ca.bitwit.postcard.network; public class SocialActivity { public List<Network> networks; public String date; public String message; public String tags; public MessageLink messageLink;
public MessageMedia messageMedia = null;
bitwit/postcard-android
postcard/src/main/java/org/scribe/builder/api/BufferApi.java
// Path: postcard/src/main/java/org/scribe/oauth/OAuth20PostServiceImpl.java // public class OAuth20PostServiceImpl extends OAuth20ServiceImpl{ // // private static final String VERSION = "2.0"; // private final DefaultApi20 api; // private final OAuthConfig config; // // public OAuth20PostServiceImpl(DefaultApi20 api, OAuthConfig config) { // super(api, config); // this.api = api; // this.config = config; // } // // @Override // public Token getAccessToken(Token requestToken, Verifier verifier) // { // OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); // request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); // request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); // request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); // request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); // request.addBodyParameter("grant_type", "authorization_code"); // if(config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); // // Log.d("Oauth20PostImple", request.getBodyContents()); // // Response response = request.send(); // return api.getAccessTokenExtractor().extract(response.getBody()); // } // // }
import org.scribe.extractors.*; import org.scribe.model.*; import org.scribe.oauth.OAuth20PostServiceImpl; import org.scribe.oauth.OAuthService; import org.scribe.utils.*;
package org.scribe.builder.api; public class BufferApi extends DefaultApi20 { private static final String AUTHORIZE_URL = "https://bufferapp.com/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s"; private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s"; @Override public OAuthService createService(OAuthConfig config) {
// Path: postcard/src/main/java/org/scribe/oauth/OAuth20PostServiceImpl.java // public class OAuth20PostServiceImpl extends OAuth20ServiceImpl{ // // private static final String VERSION = "2.0"; // private final DefaultApi20 api; // private final OAuthConfig config; // // public OAuth20PostServiceImpl(DefaultApi20 api, OAuthConfig config) { // super(api, config); // this.api = api; // this.config = config; // } // // @Override // public Token getAccessToken(Token requestToken, Verifier verifier) // { // OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); // request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); // request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); // request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); // request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); // request.addBodyParameter("grant_type", "authorization_code"); // if(config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); // // Log.d("Oauth20PostImple", request.getBodyContents()); // // Response response = request.send(); // return api.getAccessTokenExtractor().extract(response.getBody()); // } // // } // Path: postcard/src/main/java/org/scribe/builder/api/BufferApi.java import org.scribe.extractors.*; import org.scribe.model.*; import org.scribe.oauth.OAuth20PostServiceImpl; import org.scribe.oauth.OAuthService; import org.scribe.utils.*; package org.scribe.builder.api; public class BufferApi extends DefaultApi20 { private static final String AUTHORIZE_URL = "https://bufferapp.com/oauth2/authorize?response_type=code&client_id=%s&redirect_uri=%s"; private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s"; @Override public OAuthService createService(OAuthConfig config) {
return new OAuth20PostServiceImpl(this, config);
bitwit/postcard-android
postcard/src/main/java/org/scribe/builder/api/LinkedIn20Api.java
// Path: postcard/src/main/java/org/scribe/oauth/OAuth20PostServiceImpl.java // public class OAuth20PostServiceImpl extends OAuth20ServiceImpl{ // // private static final String VERSION = "2.0"; // private final DefaultApi20 api; // private final OAuthConfig config; // // public OAuth20PostServiceImpl(DefaultApi20 api, OAuthConfig config) { // super(api, config); // this.api = api; // this.config = config; // } // // @Override // public Token getAccessToken(Token requestToken, Verifier verifier) // { // OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); // request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); // request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); // request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); // request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); // request.addBodyParameter("grant_type", "authorization_code"); // if(config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); // // Log.d("Oauth20PostImple", request.getBodyContents()); // // Response response = request.send(); // return api.getAccessTokenExtractor().extract(response.getBody()); // } // // }
import org.scribe.extractors.*; import org.scribe.model.*; import org.scribe.oauth.OAuth20PostServiceImpl; import org.scribe.oauth.OAuthService; import org.scribe.utils.*;
package org.scribe.builder.api; /** * String redirectUri = "http://www.postcardsocial.net"; String tokenUrl = "https://www.linkedin.com/uas/oauth2/"; String tokenPath = "accessToken"; String authorizationPath = "authorization"; String authUrl = tokenUrl + authorizationPath + "?response_type=code&client_id=" + LINKEDIN_CLIENT_ID + "&scope=" + "r_fullprofile%20r_network%20rw_nus" + "&state=" + state + "&redirect_uri=" + redirectUri; try { JSONObject tokenPostData = new JSONObject(); tokenPostData.put("client_id", LINKEDIN_CLIENT_ID); tokenPostData.put("client_secret", LINKEDIN_CLIENT_SECRET); tokenPostData.put("redirect_uri", redirectUri); tokenPostData.put("grant_type", "authorization_code"); JSONObject params = new JSONObject(); params.put("auth_url", authUrl); params.put("auth_type", "oauth2"); params.put("code_title", "code"); params.put("base_token_url", tokenUrl); params.put("token_path", tokenPath); params.put("token_method", "post"); params.put("token_data", tokenPostData); params.put("token_title", "access_token"); params.put("state", state); launchWebAuthActivity(params); } catch (JSONException ex) { ex.printStackTrace(); } * */ public class LinkedIn20Api extends DefaultApi20 { private static final String AUTHORIZE_URL = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%s&redirect_uri=%s&state=1234"; private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=r_fullprofile%20r_network%20rw_nus"; //+ "&scope=%s"; @Override public OAuthService createService(OAuthConfig config) {
// Path: postcard/src/main/java/org/scribe/oauth/OAuth20PostServiceImpl.java // public class OAuth20PostServiceImpl extends OAuth20ServiceImpl{ // // private static final String VERSION = "2.0"; // private final DefaultApi20 api; // private final OAuthConfig config; // // public OAuth20PostServiceImpl(DefaultApi20 api, OAuthConfig config) { // super(api, config); // this.api = api; // this.config = config; // } // // @Override // public Token getAccessToken(Token requestToken, Verifier verifier) // { // OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); // request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); // request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); // request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); // request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); // request.addBodyParameter("grant_type", "authorization_code"); // if(config.hasScope()) request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); // // Log.d("Oauth20PostImple", request.getBodyContents()); // // Response response = request.send(); // return api.getAccessTokenExtractor().extract(response.getBody()); // } // // } // Path: postcard/src/main/java/org/scribe/builder/api/LinkedIn20Api.java import org.scribe.extractors.*; import org.scribe.model.*; import org.scribe.oauth.OAuth20PostServiceImpl; import org.scribe.oauth.OAuthService; import org.scribe.utils.*; package org.scribe.builder.api; /** * String redirectUri = "http://www.postcardsocial.net"; String tokenUrl = "https://www.linkedin.com/uas/oauth2/"; String tokenPath = "accessToken"; String authorizationPath = "authorization"; String authUrl = tokenUrl + authorizationPath + "?response_type=code&client_id=" + LINKEDIN_CLIENT_ID + "&scope=" + "r_fullprofile%20r_network%20rw_nus" + "&state=" + state + "&redirect_uri=" + redirectUri; try { JSONObject tokenPostData = new JSONObject(); tokenPostData.put("client_id", LINKEDIN_CLIENT_ID); tokenPostData.put("client_secret", LINKEDIN_CLIENT_SECRET); tokenPostData.put("redirect_uri", redirectUri); tokenPostData.put("grant_type", "authorization_code"); JSONObject params = new JSONObject(); params.put("auth_url", authUrl); params.put("auth_type", "oauth2"); params.put("code_title", "code"); params.put("base_token_url", tokenUrl); params.put("token_path", tokenPath); params.put("token_method", "post"); params.put("token_data", tokenPostData); params.put("token_title", "access_token"); params.put("state", state); launchWebAuthActivity(params); } catch (JSONException ex) { ex.printStackTrace(); } * */ public class LinkedIn20Api extends DefaultApi20 { private static final String AUTHORIZE_URL = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%s&redirect_uri=%s&state=1234"; private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=r_fullprofile%20r_network%20rw_nus"; //+ "&scope=%s"; @Override public OAuthService createService(OAuthConfig config) {
return new OAuth20PostServiceImpl(this, config);
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dsl/ValidationFunction.java
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ValidationMode.java // public enum ValidationMode { // /** // * Enum value to identify the creation of a new entry // */ // CREATE, // /** // * Enum value to identify updating an existing entry // */ // EDIT // }
import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.ValidationMode;
package net.nextpulse.jadmin.dsl; /** * A functional interface that is used to provide user input validation methods. */ @FunctionalInterface public interface ValidationFunction { /** * Validation function that will be called by the JAdmin internals. The function may throw an InvalidInputException if * the provided FormPostEntry does not conform to the validation requirements. Additionally, the function may add or * change the data. * * @param validationMode validation mode, can be EDIT or NEW * @param formPostEntry user submitted post data * @throws InvalidInputException if the object could not be validated */
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ValidationMode.java // public enum ValidationMode { // /** // * Enum value to identify the creation of a new entry // */ // CREATE, // /** // * Enum value to identify updating an existing entry // */ // EDIT // } // Path: src/main/java/net/nextpulse/jadmin/dsl/ValidationFunction.java import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.ValidationMode; package net.nextpulse.jadmin.dsl; /** * A functional interface that is used to provide user input validation methods. */ @FunctionalInterface public interface ValidationFunction { /** * Validation function that will be called by the JAdmin internals. The function may throw an InvalidInputException if * the provided FormPostEntry does not conform to the validation requirements. Additionally, the function may add or * change the data. * * @param validationMode validation mode, can be EDIT or NEW * @param formPostEntry user submitted post data * @throws InvalidInputException if the object could not be validated */
void apply(ValidationMode validationMode, FormPostEntry formPostEntry) throws InvalidInputException;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dsl/ValidationFunction.java
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ValidationMode.java // public enum ValidationMode { // /** // * Enum value to identify the creation of a new entry // */ // CREATE, // /** // * Enum value to identify updating an existing entry // */ // EDIT // }
import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.ValidationMode;
package net.nextpulse.jadmin.dsl; /** * A functional interface that is used to provide user input validation methods. */ @FunctionalInterface public interface ValidationFunction { /** * Validation function that will be called by the JAdmin internals. The function may throw an InvalidInputException if * the provided FormPostEntry does not conform to the validation requirements. Additionally, the function may add or * change the data. * * @param validationMode validation mode, can be EDIT or NEW * @param formPostEntry user submitted post data * @throws InvalidInputException if the object could not be validated */
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ValidationMode.java // public enum ValidationMode { // /** // * Enum value to identify the creation of a new entry // */ // CREATE, // /** // * Enum value to identify updating an existing entry // */ // EDIT // } // Path: src/main/java/net/nextpulse/jadmin/dsl/ValidationFunction.java import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.ValidationMode; package net.nextpulse.jadmin.dsl; /** * A functional interface that is used to provide user input validation methods. */ @FunctionalInterface public interface ValidationFunction { /** * Validation function that will be called by the JAdmin internals. The function may throw an InvalidInputException if * the provided FormPostEntry does not conform to the validation requirements. Additionally, the function may add or * change the data. * * @param validationMode validation mode, can be EDIT or NEW * @param formPostEntry user submitted post data * @throws InvalidInputException if the object could not be validated */
void apply(ValidationMode validationMode, FormPostEntry formPostEntry) throws InvalidInputException;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/schema/ResourceSchemaProvider.java // public interface ResourceSchemaProvider { // // /** // * Returns the names of columns that make up the key identifying any resource instance. // * // * @return list of columns that make up the primary key, in the order in which they occur // * @throws DataAccessException if an error occurs while accessing the underlying data source // */ // default List<ColumnDefinition> getKeyColumns() throws DataAccessException { // return getColumnDefinitions().stream().filter(ColumnDefinition::isKeyColumn).collect(Collectors.toList()); // } // // /** // * Returns the full list of columns that make up the resource. // * // * @return list of column definitions // * @throws DataAccessException if an error occurs while accessing the underlying data source // */ // List<ColumnDefinition> getColumnDefinitions() throws DataAccessException; // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.schema.ResourceSchemaProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors;
package net.nextpulse.jadmin.dao; /** * Abstract parent class for a DAO class backing a specific Resource. The DAO class handles the retrieval * and updating of the resourceSchemaProvider instances. * * @author yholkamp */ public abstract class AbstractDAO { /** * Resource managed by this DAO instance. */ protected ResourceSchemaProvider resourceSchemaProvider;
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // // Path: src/main/java/net/nextpulse/jadmin/schema/ResourceSchemaProvider.java // public interface ResourceSchemaProvider { // // /** // * Returns the names of columns that make up the key identifying any resource instance. // * // * @return list of columns that make up the primary key, in the order in which they occur // * @throws DataAccessException if an error occurs while accessing the underlying data source // */ // default List<ColumnDefinition> getKeyColumns() throws DataAccessException { // return getColumnDefinitions().stream().filter(ColumnDefinition::isKeyColumn).collect(Collectors.toList()); // } // // /** // * Returns the full list of columns that make up the resource. // * // * @return list of column definitions // * @throws DataAccessException if an error occurs while accessing the underlying data source // */ // List<ColumnDefinition> getColumnDefinitions() throws DataAccessException; // } // Path: src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.FormPostEntry; import net.nextpulse.jadmin.schema.ResourceSchemaProvider; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; package net.nextpulse.jadmin.dao; /** * Abstract parent class for a DAO class backing a specific Resource. The DAO class handles the retrieval * and updating of the resourceSchemaProvider instances. * * @author yholkamp */ public abstract class AbstractDAO { /** * Resource managed by this DAO instance. */ protected ResourceSchemaProvider resourceSchemaProvider;
private Map<String, ColumnDefinition> columnDefinitionMap;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/ColumnDefinition.java
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // }
import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable;
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable;
private List<InputValidationRule> validationRules = new ArrayList<>();
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/ColumnDefinition.java
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // }
import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable; private List<InputValidationRule> validationRules = new ArrayList<>();
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable; private List<InputValidationRule> validationRules = new ArrayList<>();
private InputTransformer inputTransformer;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/ColumnDefinition.java
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // }
import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable; private List<InputValidationRule> validationRules = new ArrayList<>(); private InputTransformer inputTransformer;
// Path: src/main/java/net/nextpulse/jadmin/dsl/ColumnValueTransformer.java // @FunctionalInterface // public interface ColumnValueTransformer { // // /** // * Transforms the provided column value, for example show a friendly name instead of an enum value. // * // * @param value the column value // * @return transformed column value, i.e. the friendly name of an enum value // */ // String apply(Object value); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputTransformer.java // @FunctionalInterface // public interface InputTransformer { // // /** // * Transforms the provided user input, for example to hash a user provided password. // * // * @param input raw user input // * @return transformed user input, i.e. applying a hashing algorithm // */ // String apply(String input); // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java import net.nextpulse.jadmin.dsl.ColumnValueTransformer; import net.nextpulse.jadmin.dsl.InputTransformer; import net.nextpulse.jadmin.dsl.InputValidationRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.nextpulse.jadmin; /** * Object describing a single column of a table. * * @author yholkamp */ public class ColumnDefinition { /** * Column name, case sensitive */ private String name; /** * JAdmin-type of this column. */ private ColumnType type; /** * True if this column is part of the key identifying a row of the datasource containing this column. */ private boolean keyColumn; private boolean editable; private List<InputValidationRule> validationRules = new ArrayList<>(); private InputTransformer inputTransformer;
private ColumnValueTransformer columnValueTransformer;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/elements/FormInput.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // }
import net.nextpulse.jadmin.ColumnType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
package net.nextpulse.jadmin.elements; /** * Parent input field class that will be rendered as text field, checkbox, date picker or select field depending on the * configuration. */ public class FormInput implements PageElement { private static final Logger logger = LogManager.getLogger();
// Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // Path: src/main/java/net/nextpulse/jadmin/elements/FormInput.java import net.nextpulse.jadmin.ColumnType; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; package net.nextpulse.jadmin.elements; /** * Parent input field class that will be rendered as text field, checkbox, date picker or select field depending on the * configuration. */ public class FormInput implements PageElement { private static final Logger logger = LogManager.getLogger();
private ColumnType columnType;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // }
import net.nextpulse.jadmin.ColumnDefinition; import spark.utils.StringUtils; import java.util.function.Function; import java.util.function.Supplier;
package net.nextpulse.jadmin.dsl; /** * Functional interface that specifies a method that will validatePostData (and optionally transform) a user's input value. * If the user input is not valid, an exception is thrown, otherwise the (optionally transformed) user input is returned. * * @author yholkamp */ @SuppressWarnings("unused") @FunctionalInterface public interface InputValidationRule { /** * Validation rule that indicates a required field. */ Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { if (StringUtils.isBlank(userInput)) { throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); } }; /** * Validation rule that indicates a minimum length */ Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); } }; /** * Validation rule that indicates a minimum length or blank */ Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); } }; /** * Validation rule that indicates a minimum length */ Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { if (userInput.length() > maxLength) { throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); } }; /** * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an * exception is thrown, otherwise the (optionally transformed) user input is returned. * * @param columnDefinition * @param userInput raw (unsafe!) user data * @throws InvalidInputException if the user input is invalid */
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java import net.nextpulse.jadmin.ColumnDefinition; import spark.utils.StringUtils; import java.util.function.Function; import java.util.function.Supplier; package net.nextpulse.jadmin.dsl; /** * Functional interface that specifies a method that will validatePostData (and optionally transform) a user's input value. * If the user input is not valid, an exception is thrown, otherwise the (optionally transformed) user input is returned. * * @author yholkamp */ @SuppressWarnings("unused") @FunctionalInterface public interface InputValidationRule { /** * Validation rule that indicates a required field. */ Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { if (StringUtils.isBlank(userInput)) { throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); } }; /** * Validation rule that indicates a minimum length */ Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); } }; /** * Validation rule that indicates a minimum length or blank */ Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); } }; /** * Validation rule that indicates a minimum length */ Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { if (userInput.length() > maxLength) { throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); } }; /** * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an * exception is thrown, otherwise the (optionally transformed) user input is returned. * * @param columnDefinition * @param userInput raw (unsafe!) user data * @throws InvalidInputException if the user input is invalid */
void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/InputValidator.java
// Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InvalidInputException.java // public class InvalidInputException extends Exception { // // /** // * Creates a new input validation exception with the provided exception message being reported to the user as feedback. // * // * @param message message to show to the end user // */ // public InvalidInputException(String message) { // super(message); // } // }
import net.nextpulse.jadmin.dsl.InputValidationRule; import net.nextpulse.jadmin.dsl.InvalidInputException; import spark.utils.StringUtils;
package net.nextpulse.jadmin; /** * Input validation class that will check the user provided data against the configured input restrictions. * * @author yorick */ public class InputValidator { private InputValidator() { } /** * Ensures all entries of the FormPostEntry pass validation. * * @param postEntry entry to validatePostData * @param resource internal resource object * @param validationMode validation mode, either edit or create * @throws InvalidInputException if the user input does not pass validation */
// Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InvalidInputException.java // public class InvalidInputException extends Exception { // // /** // * Creates a new input validation exception with the provided exception message being reported to the user as feedback. // * // * @param message message to show to the end user // */ // public InvalidInputException(String message) { // super(message); // } // } // Path: src/main/java/net/nextpulse/jadmin/InputValidator.java import net.nextpulse.jadmin.dsl.InputValidationRule; import net.nextpulse.jadmin.dsl.InvalidInputException; import spark.utils.StringUtils; package net.nextpulse.jadmin; /** * Input validation class that will check the user provided data against the configured input restrictions. * * @author yorick */ public class InputValidator { private InputValidator() { } /** * Ensures all entries of the FormPostEntry pass validation. * * @param postEntry entry to validatePostData * @param resource internal resource object * @param validationMode validation mode, either edit or create * @throws InvalidInputException if the user input does not pass validation */
public static void validate(FormPostEntry postEntry, Resource resource, ValidationMode validationMode) throws InvalidInputException {
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/InputValidator.java
// Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InvalidInputException.java // public class InvalidInputException extends Exception { // // /** // * Creates a new input validation exception with the provided exception message being reported to the user as feedback. // * // * @param message message to show to the end user // */ // public InvalidInputException(String message) { // super(message); // } // }
import net.nextpulse.jadmin.dsl.InputValidationRule; import net.nextpulse.jadmin.dsl.InvalidInputException; import spark.utils.StringUtils;
* @param postEntry user provided data * @param validationMode validation mode * @throws InvalidInputException */ private static void validateColumn(ColumnDefinition columnDefinition, FormPostEntry postEntry, ValidationMode validationMode) throws InvalidInputException { if(columnDefinition.isKeyColumn()) { // skip the key presence requirement for new entries if(validationMode == ValidationMode.EDIT) { String input = postEntry.getKeyValues().get(columnDefinition.getName()); if(StringUtils.isBlank(input)) { throw new InvalidInputException("Key column " + columnDefinition.getName() + " is missing"); } } } else { String input = postEntry.getValues().get(columnDefinition.getName()); if(!columnDefinition.isEditable()) { throw new InvalidInputException("Column " + columnDefinition.getName() + " is not editable"); } // validate the actual input validateColumn(columnDefinition, input); } } /** * Validates the user input against the rules configured for the column * * @throws InvalidInputException if the user data does not pass input validation */ private static void validateColumn(ColumnDefinition columnDefinition, String userData) throws InvalidInputException {
// Path: src/main/java/net/nextpulse/jadmin/dsl/InputValidationRule.java // @SuppressWarnings("unused") // @FunctionalInterface // public interface InputValidationRule { // // /** // * Validation rule that indicates a required field. // */ // Supplier<InputValidationRule> REQUIRED = () -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput)) { // throw new InvalidInputException(String.format("%s is empty but is required", columnDefinition.getName())); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH = (minLength) -> (columnDefinition, userInput) -> { // if (StringUtils.isBlank(userInput) || userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length or blank // */ // Function<Integer, InputValidationRule> MINIMUM_LENGTH_OR_BLANK = (minLength) -> (columnDefinition, userInput) -> { // if (!StringUtils.isBlank(userInput) && userInput.length() < minLength) { // throw new InvalidInputException(String.format("%s is less than %d characters", columnDefinition.getName(), minLength)); // } // }; // // /** // * Validation rule that indicates a minimum length // */ // Function<Integer, InputValidationRule> MAXIMUM_LENGTH = (maxLength) -> (columnDefinition, userInput) -> { // if (userInput.length() > maxLength) { // throw new InvalidInputException(String.format("%s is more than %d characters long", columnDefinition.getName(), maxLength)); // } // }; // // /** // * Method that will validatePostData (and optionally transform) a user's input value. If the user input is not valid, an // * exception is thrown, otherwise the (optionally transformed) user input is returned. // * // * @param columnDefinition // * @param userInput raw (unsafe!) user data // * @throws InvalidInputException if the user input is invalid // */ // void validate(ColumnDefinition columnDefinition, String userInput) throws InvalidInputException; // } // // Path: src/main/java/net/nextpulse/jadmin/dsl/InvalidInputException.java // public class InvalidInputException extends Exception { // // /** // * Creates a new input validation exception with the provided exception message being reported to the user as feedback. // * // * @param message message to show to the end user // */ // public InvalidInputException(String message) { // super(message); // } // } // Path: src/main/java/net/nextpulse/jadmin/InputValidator.java import net.nextpulse.jadmin.dsl.InputValidationRule; import net.nextpulse.jadmin.dsl.InvalidInputException; import spark.utils.StringUtils; * @param postEntry user provided data * @param validationMode validation mode * @throws InvalidInputException */ private static void validateColumn(ColumnDefinition columnDefinition, FormPostEntry postEntry, ValidationMode validationMode) throws InvalidInputException { if(columnDefinition.isKeyColumn()) { // skip the key presence requirement for new entries if(validationMode == ValidationMode.EDIT) { String input = postEntry.getKeyValues().get(columnDefinition.getName()); if(StringUtils.isBlank(input)) { throw new InvalidInputException("Key column " + columnDefinition.getName() + " is missing"); } } } else { String input = postEntry.getValues().get(columnDefinition.getName()); if(!columnDefinition.isEditable()) { throw new InvalidInputException("Column " + columnDefinition.getName() + " is not editable"); } // validate the actual input validateColumn(columnDefinition, input); } } /** * Validates the user input against the rules configured for the column * * @throws InvalidInputException if the user data does not pass input validation */ private static void validateColumn(ColumnDefinition columnDefinition, String userData) throws InvalidInputException {
for(InputValidationRule rule : columnDefinition.getValidationRules()) {
yholkamp/jadmin
src/test/java/net/nextpulse/jadmin/CrudControllerTest.java
// Path: src/test/java/testhelpers/TestQueryParamsMap.java // public class TestQueryParamsMap extends QueryParamsMap { // // public TestQueryParamsMap(Map<String, String[]> params) { // super(params); // } // }
import com.google.common.collect.ImmutableMap; import testhelpers.TestQueryParamsMap; import org.junit.Test; import spark.Request; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package net.nextpulse.jadmin; /** * @author yholkamp */ public class CrudControllerTest { @Test public void extractFormPostEntry_additionalData() throws Exception { Request mockRequest = createMockRequest(null);
// Path: src/test/java/testhelpers/TestQueryParamsMap.java // public class TestQueryParamsMap extends QueryParamsMap { // // public TestQueryParamsMap(Map<String, String[]> params) { // super(params); // } // } // Path: src/test/java/net/nextpulse/jadmin/CrudControllerTest.java import com.google.common.collect.ImmutableMap; import testhelpers.TestQueryParamsMap; import org.junit.Test; import spark.Request; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package net.nextpulse.jadmin; /** * @author yholkamp */ public class CrudControllerTest { @Test public void extractFormPostEntry_additionalData() throws Exception { Request mockRequest = createMockRequest(null);
when(mockRequest.queryMap()).thenReturn(new TestQueryParamsMap(ImmutableMap.of(
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/elements/FormSelect.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/helpers/Tuple2.java // public class Tuple2<L, R> { // private final L left; // private final R right; // // public Tuple2(L left, R right) { // this.left = left; // this.right = right; // } // // public L getLeft() { // return left; // } // // public R getRight() { // return right; // } // }
import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.helpers.Tuple2; import java.util.List; import java.util.function.Supplier;
package net.nextpulse.jadmin.elements; /** * Element that will be rendered as a select tag in the template. Contains a supplier that will be called to * retrieve the list of values to show as option tags. * * @author yholkamp */ public class FormSelect extends FormInput { private final Supplier<List<Tuple2<String, String>>> optionProducer; /** * @param name internal name of this column * @param columnType type of this column * @param optionSupplier method that provides a list of tuples of (value, name) that will be used as selectable options. */
// Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/helpers/Tuple2.java // public class Tuple2<L, R> { // private final L left; // private final R right; // // public Tuple2(L left, R right) { // this.left = left; // this.right = right; // } // // public L getLeft() { // return left; // } // // public R getRight() { // return right; // } // } // Path: src/main/java/net/nextpulse/jadmin/elements/FormSelect.java import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.helpers.Tuple2; import java.util.List; import java.util.function.Supplier; package net.nextpulse.jadmin.elements; /** * Element that will be rendered as a select tag in the template. Contains a supplier that will be called to * retrieve the list of values to show as option tags. * * @author yholkamp */ public class FormSelect extends FormInput { private final Supplier<List<Tuple2<String, String>>> optionProducer; /** * @param name internal name of this column * @param columnType type of this column * @param optionSupplier method that provides a list of tuples of (value, name) that will be used as selectable options. */
public FormSelect(String name, ColumnType columnType, Supplier<List<Tuple2<String, String>>> optionSupplier) {
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
package net.nextpulse.jadmin.schema; /** * Generic implementation of the ResourceSchemaProvider interface, providing schema retrieval logic for SQL backed resources. * * @author yholkamp */ public class GenericSQLSchemaProvider implements ResourceSchemaProvider { private static final Logger logger = LogManager.getLogger(); private static final String COLUMN_NAME = "COLUMN_NAME"; private static final String TYPE_NAME = "TYPE_NAME"; private final DataSource dataSource; private final String tableName;
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // } // Path: src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; package net.nextpulse.jadmin.schema; /** * Generic implementation of the ResourceSchemaProvider interface, providing schema retrieval logic for SQL backed resources. * * @author yholkamp */ public class GenericSQLSchemaProvider implements ResourceSchemaProvider { private static final Logger logger = LogManager.getLogger(); private static final String COLUMN_NAME = "COLUMN_NAME"; private static final String TYPE_NAME = "TYPE_NAME"; private final DataSource dataSource; private final String tableName;
private List<ColumnDefinition> keyColumns = null;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
package net.nextpulse.jadmin.schema; /** * Generic implementation of the ResourceSchemaProvider interface, providing schema retrieval logic for SQL backed resources. * * @author yholkamp */ public class GenericSQLSchemaProvider implements ResourceSchemaProvider { private static final Logger logger = LogManager.getLogger(); private static final String COLUMN_NAME = "COLUMN_NAME"; private static final String TYPE_NAME = "TYPE_NAME"; private final DataSource dataSource; private final String tableName; private List<ColumnDefinition> keyColumns = null; private List<ColumnDefinition> columnDefinitions = null; public GenericSQLSchemaProvider(DataSource dataSource, String tableName) { this.dataSource = dataSource; this.tableName = tableName; } @Override
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // } // Path: src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; package net.nextpulse.jadmin.schema; /** * Generic implementation of the ResourceSchemaProvider interface, providing schema retrieval logic for SQL backed resources. * * @author yholkamp */ public class GenericSQLSchemaProvider implements ResourceSchemaProvider { private static final Logger logger = LogManager.getLogger(); private static final String COLUMN_NAME = "COLUMN_NAME"; private static final String TYPE_NAME = "TYPE_NAME"; private final DataSource dataSource; private final String tableName; private List<ColumnDefinition> keyColumns = null; private List<ColumnDefinition> columnDefinitions = null; public GenericSQLSchemaProvider(DataSource dataSource, String tableName) { this.dataSource = dataSource; this.tableName = tableName; } @Override
public List<ColumnDefinition> getKeyColumns() throws DataAccessException {
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
logger.trace("Retrieving key columns for {}", tableName); keyColumns = getColumnDefinitions().stream().filter(ColumnDefinition::isKeyColumn).collect(Collectors.toList()); } return keyColumns; } @Override public List<ColumnDefinition> getColumnDefinitions() throws DataAccessException { logger.trace("Retrieving column definitions for {}", tableName); // only retrieve the definitions if we haven't already done so if(columnDefinitions == null) { columnDefinitions = new ArrayList<>(); Set<String> primaryKeys = new HashSet<>(); try(Connection conn = dataSource.getConnection()) { // find the primary key columns ResultSet primaryKeyResultSet = conn.getMetaData().getPrimaryKeys(conn.getCatalog(), conn.getSchema(), tableName.toLowerCase()); while(primaryKeyResultSet.next()) { String columnName = primaryKeyResultSet.getString(COLUMN_NAME); primaryKeys.add(columnName); } // iterate over all columns and mark the primary key columns as such ResultSet rs = conn.getMetaData().getColumns(conn.getCatalog(), conn.getSchema(), tableName.toLowerCase(), "%"); while(rs.next()) { ColumnDefinition columnDefinition = new ColumnDefinition(); String columnName = rs.getString(COLUMN_NAME); String typeName = rs.getString(TYPE_NAME).toLowerCase(); columnDefinition.setName(columnName);
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/dao/DataAccessException.java // public class DataAccessException extends Exception { // public DataAccessException(Exception cause) { // super(cause); // } // // public DataAccessException(String message) { // super(message); // } // // public DataAccessException(String message, Exception cause) { // super(message, cause); // } // } // Path: src/main/java/net/nextpulse/jadmin/schema/GenericSQLSchemaProvider.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.dao.DataAccessException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; logger.trace("Retrieving key columns for {}", tableName); keyColumns = getColumnDefinitions().stream().filter(ColumnDefinition::isKeyColumn).collect(Collectors.toList()); } return keyColumns; } @Override public List<ColumnDefinition> getColumnDefinitions() throws DataAccessException { logger.trace("Retrieving column definitions for {}", tableName); // only retrieve the definitions if we haven't already done so if(columnDefinitions == null) { columnDefinitions = new ArrayList<>(); Set<String> primaryKeys = new HashSet<>(); try(Connection conn = dataSource.getConnection()) { // find the primary key columns ResultSet primaryKeyResultSet = conn.getMetaData().getPrimaryKeys(conn.getCatalog(), conn.getSchema(), tableName.toLowerCase()); while(primaryKeyResultSet.next()) { String columnName = primaryKeyResultSet.getString(COLUMN_NAME); primaryKeys.add(columnName); } // iterate over all columns and mark the primary key columns as such ResultSet rs = conn.getMetaData().getColumns(conn.getCatalog(), conn.getSchema(), tableName.toLowerCase(), "%"); while(rs.next()) { ColumnDefinition columnDefinition = new ColumnDefinition(); String columnName = rs.getString(COLUMN_NAME); String typeName = rs.getString(TYPE_NAME).toLowerCase(); columnDefinition.setName(columnName);
ColumnType columnType = sqlTypeToColumnType(typeName);
yholkamp/jadmin
src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao;
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // Path: src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao;
private ColumnDefinition keyColumn1;
yholkamp/jadmin
src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao; private ColumnDefinition keyColumn1; private ColumnDefinition keyColumn2; private ColumnDefinition valueColumn;
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // Path: src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao; private ColumnDefinition keyColumn1; private ColumnDefinition keyColumn2; private ColumnDefinition valueColumn;
private FormPostEntry formEntry2;
yholkamp/jadmin
src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // }
import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao; private ColumnDefinition keyColumn1; private ColumnDefinition keyColumn2; private ColumnDefinition valueColumn; private FormPostEntry formEntry2; private FormPostEntry formEntry; @Before public void setUp() throws Exception { dao = new InMemoryDAO();
// Path: src/main/java/net/nextpulse/jadmin/ColumnDefinition.java // public class ColumnDefinition { // // /** // * Column name, case sensitive // */ // private String name; // /** // * JAdmin-type of this column. // */ // private ColumnType type; // // /** // * True if this column is part of the key identifying a row of the datasource containing this column. // */ // private boolean keyColumn; // private boolean editable; // private List<InputValidationRule> validationRules = new ArrayList<>(); // private InputTransformer inputTransformer; // private ColumnValueTransformer columnValueTransformer; // // public ColumnDefinition() { // } // // public ColumnDefinition(String name, ColumnType type) { // this.name = name; // this.type = type; // } // // public ColumnDefinition(String name, ColumnType type, boolean keyColumn, boolean editable) { // this.name = name; // this.type = type; // this.keyColumn = keyColumn; // this.editable = editable; // } // // public String getName() { // return name; // } // // public ColumnDefinition setName(String name) { // this.name = name; // return this; // } // // public ColumnType getType() { // return type; // } // // public void setType(ColumnType type) { // this.type = type; // } // // public boolean isKeyColumn() { // return keyColumn; // } // // public ColumnDefinition setKeyColumn(boolean keyColumn) { // this.keyColumn = keyColumn; // return this; // } // // public boolean isEditable() { // return editable; // } // // public ColumnDefinition setEditable(boolean editable) { // this.editable = editable; // return this; // } // // /** // * Adds the provided input validation rule to the list of rules. // * // * @param inputValidationRules rule(s) that should be active for this column // */ // public ColumnDefinition addValidationRules(InputValidationRule... inputValidationRules) { // validationRules.addAll(Arrays.asList(inputValidationRules)); // return this; // } // // /** // * @return the configured validation rules // */ // public List<InputValidationRule> getValidationRules() { // return validationRules; // } // // public InputTransformer getInputTransformer() { // return inputTransformer; // } // // public ColumnDefinition setInputTransformer(InputTransformer inputTransformer) { // this.inputTransformer = inputTransformer; // return this; // } // // public ColumnValueTransformer getColumnValueTransformer() { // return columnValueTransformer; // } // // public ColumnDefinition setColumnValueTransformer(ColumnValueTransformer columnValueTransformer) { // this.columnValueTransformer = columnValueTransformer; // return this; // } // } // // Path: src/main/java/net/nextpulse/jadmin/ColumnType.java // public enum ColumnType { // string, // text, // integer, // bool, // datetime; // // } // // Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // Path: src/test/java/net/nextpulse/jadmin/dao/InMemoryDAOTest.java import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.ColumnType; import net.nextpulse.jadmin.FormPostEntry; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package net.nextpulse.jadmin.dao; /** * @author yholkamp */ public class InMemoryDAOTest { private InMemoryDAO dao; private ColumnDefinition keyColumn1; private ColumnDefinition keyColumn2; private ColumnDefinition valueColumn; private FormPostEntry formEntry2; private FormPostEntry formEntry; @Before public void setUp() throws Exception { dao = new InMemoryDAO();
keyColumn1 = new ColumnDefinition("key1_column", ColumnType.string);
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/helpers/templatemethods/I18nTranslate.java
// Path: src/main/java/net/nextpulse/jadmin/helpers/I18n.java // public class I18n { // private static final Logger logger = LogManager.getLogger(); // /** // * Location where translation files are expected to be. // */ // private static final String I18N_OVERRIDE_PATH = "/jadmin/i18n"; // private static final String DEFAULT_I18N_PATH = "/net/nextpulse/jadmin/i18n"; // /** // * Currently loaded configuration // */ // protected static Properties configuration = null; // /** // * Configured language identifier // */ // private static String language = "en"; // // /** // * Given the key, returns the translation string or the provided key if the string was not found. // * // * @param key translation key // * @param params optional list of parameters to apply to the translation file, using String.format // * @return translation string or key if the string is not available // */ // public static String get(String key, Object... params) { // return getOptional(key, params).orElse(key); // } // // /** // * Given the key, returns an option containing either nothing or the translation string. // * // * @param key translation key // * @param params optional list of parameters to apply to the translation file, using String.format // * @return optional containing nothing or the translation string // */ // public static Optional<String> getOptional(String key, Object... params) { // if(configuration == null) { // loadProperties(); // } // // if(configuration.containsKey(key)) { // try { // return Optional.of(String.format((String) configuration.get(key), (Object[]) params)); // } catch(IllegalFormatException e) { // logger.error("Could not process the specified format for key {}", key, e); // } // } // // return Optional.empty(); // } // // /** // * Sets the language when translating strings. // * // * @param language language string, defaults to "en" and should correspond to the file name of the i18n file, i.e. resources/jadmin/i18n/{{language}}.properties // */ // public static void setLanguage(String language) { // I18n.language = language; // loadProperties(); // } // // /** // * Loads the default translation file as well as the properties file for the configured language. // */ // private static void loadProperties() { // configuration = new Properties(); // loadFile(DEFAULT_I18N_PATH, "base"); // loadFile(DEFAULT_I18N_PATH, language); // loadFile(I18N_OVERRIDE_PATH, language); // } // // /** // * Loads the provided properties file name, assuming it exists // * // * @param path // * @param filename // */ // private static void loadFile(String path, String filename) { // try(InputStream in = I18n.class.getResourceAsStream(path + "/" + filename + ".properties")) { // configuration.load(in); // } catch(NullPointerException e) { // logger.error("Translation file " + path + "/{}.properties does not exist in the class path", I18n.language); // } catch(IOException e) { // logger.error("Translation file " + path + "/{}.properties could not be loaded from the class path", I18n.language, e); // } // } // }
import freemarker.template.*; import freemarker.template.utility.DeepUnwrap; import net.nextpulse.jadmin.helpers.I18n; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.math.BigDecimal; import java.util.List; import java.util.Optional;
package net.nextpulse.jadmin.helpers.templatemethods; /** * Freemarker method that facilitates translating template strings. * * @author yholkamp */ public class I18nTranslate implements TemplateMethodModelEx { private static final Logger logger = LogManager.getLogger(); /** * Translation method that takes a translation key and optionally a list of parameters and returns the translation * string. * * @param arguments arguments, at least the translation string key * @return the translated string * @throws TemplateModelException if no translation key was provided */ @Override public Object exec(List arguments) throws TemplateModelException { logger.trace("I18n template method called with {}", arguments); if(arguments.isEmpty()) { throw new TemplateModelException("At least the translation key should be provided."); } Object translationKey = getTranslationKey(arguments); Optional<String> translationOpt = getTranslation((String) translationKey, arguments); // either return the translation string or the translation string return new SimpleScalar(translationOpt.orElse((String) translationKey)); } /** * Retrieves the translation key, the first argument, or throws an error. * * @param arguments list of arguments * @return translation key * @throws TemplateModelException if no valid argument was provided */ Object getTranslationKey(List arguments) throws TemplateModelException { Object translationKey = DeepUnwrap.unwrap((TemplateModel) arguments.get(0)); if(!(translationKey instanceof String)) { throw new TemplateModelException("The translation key should be a string."); } return translationKey; } /** * Retrieves the translation for the provided key and arguments. * * @param translationKey translation key * @param arguments optional list of arguments to pass to the translation string * @return translated string */ Optional<String> getTranslation(String translationKey, List arguments) { Object[] params = new Object[0]; if(arguments.size() > 1) { params = arguments.stream().skip(1).map(this::runtimeThrowingUnwrap).toArray(); }
// Path: src/main/java/net/nextpulse/jadmin/helpers/I18n.java // public class I18n { // private static final Logger logger = LogManager.getLogger(); // /** // * Location where translation files are expected to be. // */ // private static final String I18N_OVERRIDE_PATH = "/jadmin/i18n"; // private static final String DEFAULT_I18N_PATH = "/net/nextpulse/jadmin/i18n"; // /** // * Currently loaded configuration // */ // protected static Properties configuration = null; // /** // * Configured language identifier // */ // private static String language = "en"; // // /** // * Given the key, returns the translation string or the provided key if the string was not found. // * // * @param key translation key // * @param params optional list of parameters to apply to the translation file, using String.format // * @return translation string or key if the string is not available // */ // public static String get(String key, Object... params) { // return getOptional(key, params).orElse(key); // } // // /** // * Given the key, returns an option containing either nothing or the translation string. // * // * @param key translation key // * @param params optional list of parameters to apply to the translation file, using String.format // * @return optional containing nothing or the translation string // */ // public static Optional<String> getOptional(String key, Object... params) { // if(configuration == null) { // loadProperties(); // } // // if(configuration.containsKey(key)) { // try { // return Optional.of(String.format((String) configuration.get(key), (Object[]) params)); // } catch(IllegalFormatException e) { // logger.error("Could not process the specified format for key {}", key, e); // } // } // // return Optional.empty(); // } // // /** // * Sets the language when translating strings. // * // * @param language language string, defaults to "en" and should correspond to the file name of the i18n file, i.e. resources/jadmin/i18n/{{language}}.properties // */ // public static void setLanguage(String language) { // I18n.language = language; // loadProperties(); // } // // /** // * Loads the default translation file as well as the properties file for the configured language. // */ // private static void loadProperties() { // configuration = new Properties(); // loadFile(DEFAULT_I18N_PATH, "base"); // loadFile(DEFAULT_I18N_PATH, language); // loadFile(I18N_OVERRIDE_PATH, language); // } // // /** // * Loads the provided properties file name, assuming it exists // * // * @param path // * @param filename // */ // private static void loadFile(String path, String filename) { // try(InputStream in = I18n.class.getResourceAsStream(path + "/" + filename + ".properties")) { // configuration.load(in); // } catch(NullPointerException e) { // logger.error("Translation file " + path + "/{}.properties does not exist in the class path", I18n.language); // } catch(IOException e) { // logger.error("Translation file " + path + "/{}.properties could not be loaded from the class path", I18n.language, e); // } // } // } // Path: src/main/java/net/nextpulse/jadmin/helpers/templatemethods/I18nTranslate.java import freemarker.template.*; import freemarker.template.utility.DeepUnwrap; import net.nextpulse.jadmin.helpers.I18n; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.math.BigDecimal; import java.util.List; import java.util.Optional; package net.nextpulse.jadmin.helpers.templatemethods; /** * Freemarker method that facilitates translating template strings. * * @author yholkamp */ public class I18nTranslate implements TemplateMethodModelEx { private static final Logger logger = LogManager.getLogger(); /** * Translation method that takes a translation key and optionally a list of parameters and returns the translation * string. * * @param arguments arguments, at least the translation string key * @return the translated string * @throws TemplateModelException if no translation key was provided */ @Override public Object exec(List arguments) throws TemplateModelException { logger.trace("I18n template method called with {}", arguments); if(arguments.isEmpty()) { throw new TemplateModelException("At least the translation key should be provided."); } Object translationKey = getTranslationKey(arguments); Optional<String> translationOpt = getTranslation((String) translationKey, arguments); // either return the translation string or the translation string return new SimpleScalar(translationOpt.orElse((String) translationKey)); } /** * Retrieves the translation key, the first argument, or throws an error. * * @param arguments list of arguments * @return translation key * @throws TemplateModelException if no valid argument was provided */ Object getTranslationKey(List arguments) throws TemplateModelException { Object translationKey = DeepUnwrap.unwrap((TemplateModel) arguments.get(0)); if(!(translationKey instanceof String)) { throw new TemplateModelException("The translation key should be a string."); } return translationKey; } /** * Retrieves the translation for the provided key and arguments. * * @param translationKey translation key * @param arguments optional list of arguments to pass to the translation string * @return translated string */ Optional<String> getTranslation(String translationKey, List arguments) { Object[] params = new Object[0]; if(arguments.size() > 1) { params = arguments.stream().skip(1).map(this::runtimeThrowingUnwrap).toArray(); }
return I18n.getOptional(translationKey, params);
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/Resource.java
// Path: src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java // public abstract class AbstractDAO { // // /** // * Resource managed by this DAO instance. // */ // protected ResourceSchemaProvider resourceSchemaProvider; // private Map<String, ColumnDefinition> columnDefinitionMap; // // /** // * Initializer invoked before any other methods are called by the application. // * // * @param resourceSchemaProvider class that provides schema information about this resource. // */ // public void initialize(ResourceSchemaProvider resourceSchemaProvider) { // this.resourceSchemaProvider = resourceSchemaProvider; // } // // /** // * Retrieves a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @return either an empty optional object or the object represented by the provided keys. // * @throws DataAccessException if an error occurred while retrieving the object or the provided keys are invalid. // */ // public abstract Optional<DatabaseEntry> selectOne(Object... keys) throws DataAccessException; // // /** // * Retrieves multiple DatabaseEntry objects from the data store, optionally sorting by the provided column and in the provided direction. // * // * @param offset number of objects to skip // * @param count number of objects to retrieve // * @param sortColumn name of the column to sort by, may not be implemented // * @param sortDirection false for ascending, true for descending, may not be implemented // * @return list of results // * @throws DataAccessException if an error occurred while retrieving the objects // */ // public abstract List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException; // // /** // * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void insert(FormPostEntry postData) throws DataAccessException; // // /** // * Updates a single resourceSchemaProvider instance in the database using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void update(FormPostEntry postData) throws DataAccessException; // // /** // * Deletes a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @throws DataAccessException if an error occurred while deleting the object or the provided keys are invalid. // */ // public abstract void delete(Object... keys) throws DataAccessException; // // /** // * Returns (possibly an estimate of) the total number of entries for this particular resource. // * // * @return // * @throws DataAccessException // */ // public abstract int count() throws DataAccessException; // // /** // * @return mapping of string to column definition // * @throws DataAccessException if the column definitions could not be retrieved // */ // public Map<String, ColumnDefinition> getColumnDefinitions() throws DataAccessException { // if(columnDefinitionMap == null && resourceSchemaProvider == null) { // return Collections.emptyMap(); // } else if(columnDefinitionMap == null) { // columnDefinitionMap = resourceSchemaProvider.getColumnDefinitions().stream() // .collect(Collectors.toMap(ColumnDefinition::getName, Function.identity())); // } // // return columnDefinitionMap; // } // } // // Path: src/main/java/net/nextpulse/jadmin/elements/PageElement.java // public interface PageElement { // // /** // * Returns the template name to use for this type of PageElement. // * <p> // * Warnings are suppressed as this method is only called dynamically by the template engine. // * // * @return filename of the template to use // */ // @SuppressWarnings("unused") // String getTemplateName(); // }
import net.nextpulse.jadmin.dao.AbstractDAO; import net.nextpulse.jadmin.dsl.*; import net.nextpulse.jadmin.elements.PageElement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors;
package net.nextpulse.jadmin; /** * Top level configuration object for a resourceSchemaProvider that can be managed through JAdmin. * * @author yholkamp */ public class Resource { /** * Internal 'table' name of this resource */ private final String tableName; /** * Column names to display on the index/list page. */ private final List<String> indexColumns = new ArrayList<>(); /** * Page elements to display on the form (create & edit) pages. */
// Path: src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java // public abstract class AbstractDAO { // // /** // * Resource managed by this DAO instance. // */ // protected ResourceSchemaProvider resourceSchemaProvider; // private Map<String, ColumnDefinition> columnDefinitionMap; // // /** // * Initializer invoked before any other methods are called by the application. // * // * @param resourceSchemaProvider class that provides schema information about this resource. // */ // public void initialize(ResourceSchemaProvider resourceSchemaProvider) { // this.resourceSchemaProvider = resourceSchemaProvider; // } // // /** // * Retrieves a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @return either an empty optional object or the object represented by the provided keys. // * @throws DataAccessException if an error occurred while retrieving the object or the provided keys are invalid. // */ // public abstract Optional<DatabaseEntry> selectOne(Object... keys) throws DataAccessException; // // /** // * Retrieves multiple DatabaseEntry objects from the data store, optionally sorting by the provided column and in the provided direction. // * // * @param offset number of objects to skip // * @param count number of objects to retrieve // * @param sortColumn name of the column to sort by, may not be implemented // * @param sortDirection false for ascending, true for descending, may not be implemented // * @return list of results // * @throws DataAccessException if an error occurred while retrieving the objects // */ // public abstract List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException; // // /** // * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void insert(FormPostEntry postData) throws DataAccessException; // // /** // * Updates a single resourceSchemaProvider instance in the database using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void update(FormPostEntry postData) throws DataAccessException; // // /** // * Deletes a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @throws DataAccessException if an error occurred while deleting the object or the provided keys are invalid. // */ // public abstract void delete(Object... keys) throws DataAccessException; // // /** // * Returns (possibly an estimate of) the total number of entries for this particular resource. // * // * @return // * @throws DataAccessException // */ // public abstract int count() throws DataAccessException; // // /** // * @return mapping of string to column definition // * @throws DataAccessException if the column definitions could not be retrieved // */ // public Map<String, ColumnDefinition> getColumnDefinitions() throws DataAccessException { // if(columnDefinitionMap == null && resourceSchemaProvider == null) { // return Collections.emptyMap(); // } else if(columnDefinitionMap == null) { // columnDefinitionMap = resourceSchemaProvider.getColumnDefinitions().stream() // .collect(Collectors.toMap(ColumnDefinition::getName, Function.identity())); // } // // return columnDefinitionMap; // } // } // // Path: src/main/java/net/nextpulse/jadmin/elements/PageElement.java // public interface PageElement { // // /** // * Returns the template name to use for this type of PageElement. // * <p> // * Warnings are suppressed as this method is only called dynamically by the template engine. // * // * @return filename of the template to use // */ // @SuppressWarnings("unused") // String getTemplateName(); // } // Path: src/main/java/net/nextpulse/jadmin/Resource.java import net.nextpulse.jadmin.dao.AbstractDAO; import net.nextpulse.jadmin.dsl.*; import net.nextpulse.jadmin.elements.PageElement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; package net.nextpulse.jadmin; /** * Top level configuration object for a resourceSchemaProvider that can be managed through JAdmin. * * @author yholkamp */ public class Resource { /** * Internal 'table' name of this resource */ private final String tableName; /** * Column names to display on the index/list page. */ private final List<String> indexColumns = new ArrayList<>(); /** * Page elements to display on the form (create & edit) pages. */
private final List<PageElement> formPage = new ArrayList<>();
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/Resource.java
// Path: src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java // public abstract class AbstractDAO { // // /** // * Resource managed by this DAO instance. // */ // protected ResourceSchemaProvider resourceSchemaProvider; // private Map<String, ColumnDefinition> columnDefinitionMap; // // /** // * Initializer invoked before any other methods are called by the application. // * // * @param resourceSchemaProvider class that provides schema information about this resource. // */ // public void initialize(ResourceSchemaProvider resourceSchemaProvider) { // this.resourceSchemaProvider = resourceSchemaProvider; // } // // /** // * Retrieves a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @return either an empty optional object or the object represented by the provided keys. // * @throws DataAccessException if an error occurred while retrieving the object or the provided keys are invalid. // */ // public abstract Optional<DatabaseEntry> selectOne(Object... keys) throws DataAccessException; // // /** // * Retrieves multiple DatabaseEntry objects from the data store, optionally sorting by the provided column and in the provided direction. // * // * @param offset number of objects to skip // * @param count number of objects to retrieve // * @param sortColumn name of the column to sort by, may not be implemented // * @param sortDirection false for ascending, true for descending, may not be implemented // * @return list of results // * @throws DataAccessException if an error occurred while retrieving the objects // */ // public abstract List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException; // // /** // * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void insert(FormPostEntry postData) throws DataAccessException; // // /** // * Updates a single resourceSchemaProvider instance in the database using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void update(FormPostEntry postData) throws DataAccessException; // // /** // * Deletes a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @throws DataAccessException if an error occurred while deleting the object or the provided keys are invalid. // */ // public abstract void delete(Object... keys) throws DataAccessException; // // /** // * Returns (possibly an estimate of) the total number of entries for this particular resource. // * // * @return // * @throws DataAccessException // */ // public abstract int count() throws DataAccessException; // // /** // * @return mapping of string to column definition // * @throws DataAccessException if the column definitions could not be retrieved // */ // public Map<String, ColumnDefinition> getColumnDefinitions() throws DataAccessException { // if(columnDefinitionMap == null && resourceSchemaProvider == null) { // return Collections.emptyMap(); // } else if(columnDefinitionMap == null) { // columnDefinitionMap = resourceSchemaProvider.getColumnDefinitions().stream() // .collect(Collectors.toMap(ColumnDefinition::getName, Function.identity())); // } // // return columnDefinitionMap; // } // } // // Path: src/main/java/net/nextpulse/jadmin/elements/PageElement.java // public interface PageElement { // // /** // * Returns the template name to use for this type of PageElement. // * <p> // * Warnings are suppressed as this method is only called dynamically by the template engine. // * // * @return filename of the template to use // */ // @SuppressWarnings("unused") // String getTemplateName(); // }
import net.nextpulse.jadmin.dao.AbstractDAO; import net.nextpulse.jadmin.dsl.*; import net.nextpulse.jadmin.elements.PageElement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors;
package net.nextpulse.jadmin; /** * Top level configuration object for a resourceSchemaProvider that can be managed through JAdmin. * * @author yholkamp */ public class Resource { /** * Internal 'table' name of this resource */ private final String tableName; /** * Column names to display on the index/list page. */ private final List<String> indexColumns = new ArrayList<>(); /** * Page elements to display on the form (create & edit) pages. */ private final List<PageElement> formPage = new ArrayList<>(); /** * List of the column definitions for this resourceSchemaProvider, defining the column type and other properties. */ private List<ColumnDefinition> columnDefinitions = new ArrayList<>(); /** * Data access object handling object retrieval and persistence for this Resource. */
// Path: src/main/java/net/nextpulse/jadmin/dao/AbstractDAO.java // public abstract class AbstractDAO { // // /** // * Resource managed by this DAO instance. // */ // protected ResourceSchemaProvider resourceSchemaProvider; // private Map<String, ColumnDefinition> columnDefinitionMap; // // /** // * Initializer invoked before any other methods are called by the application. // * // * @param resourceSchemaProvider class that provides schema information about this resource. // */ // public void initialize(ResourceSchemaProvider resourceSchemaProvider) { // this.resourceSchemaProvider = resourceSchemaProvider; // } // // /** // * Retrieves a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @return either an empty optional object or the object represented by the provided keys. // * @throws DataAccessException if an error occurred while retrieving the object or the provided keys are invalid. // */ // public abstract Optional<DatabaseEntry> selectOne(Object... keys) throws DataAccessException; // // /** // * Retrieves multiple DatabaseEntry objects from the data store, optionally sorting by the provided column and in the provided direction. // * // * @param offset number of objects to skip // * @param count number of objects to retrieve // * @param sortColumn name of the column to sort by, may not be implemented // * @param sortDirection false for ascending, true for descending, may not be implemented // * @return list of results // * @throws DataAccessException if an error occurred while retrieving the objects // */ // public abstract List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException; // // /** // * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void insert(FormPostEntry postData) throws DataAccessException; // // /** // * Updates a single resourceSchemaProvider instance in the database using the unfiltered client submitted data. // * // * @param postData unfiltered user submitted data, must be used with caution // * @throws DataAccessException if an error occurred while inserting the object // */ // public abstract void update(FormPostEntry postData) throws DataAccessException; // // /** // * Deletes a single DatabaseEntry using the primary key(s) of the resourceSchemaProvider. // * // * @param keys primary key(s) // * @throws DataAccessException if an error occurred while deleting the object or the provided keys are invalid. // */ // public abstract void delete(Object... keys) throws DataAccessException; // // /** // * Returns (possibly an estimate of) the total number of entries for this particular resource. // * // * @return // * @throws DataAccessException // */ // public abstract int count() throws DataAccessException; // // /** // * @return mapping of string to column definition // * @throws DataAccessException if the column definitions could not be retrieved // */ // public Map<String, ColumnDefinition> getColumnDefinitions() throws DataAccessException { // if(columnDefinitionMap == null && resourceSchemaProvider == null) { // return Collections.emptyMap(); // } else if(columnDefinitionMap == null) { // columnDefinitionMap = resourceSchemaProvider.getColumnDefinitions().stream() // .collect(Collectors.toMap(ColumnDefinition::getName, Function.identity())); // } // // return columnDefinitionMap; // } // } // // Path: src/main/java/net/nextpulse/jadmin/elements/PageElement.java // public interface PageElement { // // /** // * Returns the template name to use for this type of PageElement. // * <p> // * Warnings are suppressed as this method is only called dynamically by the template engine. // * // * @return filename of the template to use // */ // @SuppressWarnings("unused") // String getTemplateName(); // } // Path: src/main/java/net/nextpulse/jadmin/Resource.java import net.nextpulse.jadmin.dao.AbstractDAO; import net.nextpulse.jadmin.dsl.*; import net.nextpulse.jadmin.elements.PageElement; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; package net.nextpulse.jadmin; /** * Top level configuration object for a resourceSchemaProvider that can be managed through JAdmin. * * @author yholkamp */ public class Resource { /** * Internal 'table' name of this resource */ private final String tableName; /** * Column names to display on the index/list page. */ private final List<String> indexColumns = new ArrayList<>(); /** * Page elements to display on the form (create & edit) pages. */ private final List<PageElement> formPage = new ArrayList<>(); /** * List of the column definitions for this resourceSchemaProvider, defining the column type and other properties. */ private List<ColumnDefinition> columnDefinitions = new ArrayList<>(); /** * Data access object handling object retrieval and persistence for this Resource. */
private AbstractDAO dao;
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dao/InMemoryDAO.java
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // }
import net.nextpulse.jadmin.FormPostEntry; import java.util.*; import java.util.stream.Collectors;
return Optional.ofNullable(objects.get(key)); } /** * Retrieves multiple DatabaseEntry objects from the data store. * * @param offset number of objects to skip * @param count number of objects to retrieve * @param sortColumn column to sort by * @param sortDirection direction to sort by, true for ascending, false for descending * @return list of results * @throws DataAccessException if an error occurred while retrieving the objects */ @Override public List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException { if(offset >= objects.size()) { return Collections.emptyList(); } else { int direction = sortDirection ? 1 : -1; return objects.values().stream().sorted((o1, o2) -> genericCompare(o1, o2) * direction).skip(offset).limit(count).collect(Collectors.toList()); } } /** * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. * * @param postData unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurred while inserting the object */ @Override
// Path: src/main/java/net/nextpulse/jadmin/FormPostEntry.java // public class FormPostEntry { // // /** // * Key value(s) for this post entry, i.e. the object id, non-editable values. // */ // private LinkedHashMap<String, String> keyValues = new LinkedHashMap<>(); // /** // * Editable values of a resource, i.e. an editable name field. // */ // private LinkedHashMap<String, String> values = new LinkedHashMap<>(); // // public FormPostEntry() { // } // // /** // * @return map of unescaped post values // */ // public LinkedHashMap<String, String> getValues() { // return values; // } // // public void addValue(String columnName, String value) { // values.put(columnName, value); // } // // /** // * @return map of unescaped values that make up the identifier of this row // */ // public LinkedHashMap<String, String> getKeyValues() { // return keyValues; // } // // /** // * Adds a new user supplied value for the specified column. // * // * @param columnName column name // * @param value user provided value // */ // public void addKeyValue(String columnName, String value) { // keyValues.put(columnName, value); // } // // /** // * Returns a Map with column keys linked to the submitted values. // * // * @return this entry as map of column name to value // */ // public Map<String, String> toPropertiesMap() { // LinkedHashMap<String, String> output = new LinkedHashMap<>(); // output.putAll(keyValues); // output.putAll(values); // return output; // } // } // Path: src/main/java/net/nextpulse/jadmin/dao/InMemoryDAO.java import net.nextpulse.jadmin.FormPostEntry; import java.util.*; import java.util.stream.Collectors; return Optional.ofNullable(objects.get(key)); } /** * Retrieves multiple DatabaseEntry objects from the data store. * * @param offset number of objects to skip * @param count number of objects to retrieve * @param sortColumn column to sort by * @param sortDirection direction to sort by, true for ascending, false for descending * @return list of results * @throws DataAccessException if an error occurred while retrieving the objects */ @Override public List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException { if(offset >= objects.size()) { return Collections.emptyList(); } else { int direction = sortDirection ? 1 : -1; return objects.values().stream().sorted((o1, o2) -> genericCompare(o1, o2) * direction).skip(offset).limit(count).collect(Collectors.toList()); } } /** * Inserts a single resourceSchemaProvider instance in to the database, using the unfiltered client submitted data. * * @param postData unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurred while inserting the object */ @Override
public void insert(FormPostEntry postData) throws DataAccessException {
robneild/pocket-query-creator
app/src/main/java/org/pquery/service/PQServiceListener.java
// Path: app/src/main/java/org/pquery/webdriver/ProgressInfo.java // public class ProgressInfo { // // public int percent; // public String htmlMessage; // // // public static ProgressInfo create(int percent, String plainMessage, String goodDetail) { // if (goodDetail != null && goodDetail.length() > 0) // return new ProgressInfo(percent, plainMessage + " [" + goodDetail + "]"); // else // return new ProgressInfo(percent, plainMessage); // } // // public ProgressInfo(int percent, String htmlMessage) { // this.percent = percent; // this.htmlMessage = htmlMessage; // } // // @Override // public String toString() { // return "[percent=" + percent + ",htmlMessage=" + htmlMessage + "]"; // } // // public ProgressInfo(Bundle bundle) { // percent = bundle.getInt("percent"); // htmlMessage = bundle.getString("htmlMessage"); // } // // public void saveToBundle(Bundle bundle) { // bundle.putInt("percent", percent); // bundle.putString("htmlMessage", htmlMessage); // } // }
import org.pquery.webdriver.ProgressInfo; import java.io.File;
package org.pquery.service; public interface PQServiceListener { public void onServiceOperationResult(String title, String message, int notificationId, File fileNameDownloaded); //public void onServicePQDownloaded(); // DownloadPQResult downloadPQResult); public void onServiceRetrievePQList(RetrievePQListResult pqListResult); //public void onServicePQCreated(CreatePQResult createPQResult);
// Path: app/src/main/java/org/pquery/webdriver/ProgressInfo.java // public class ProgressInfo { // // public int percent; // public String htmlMessage; // // // public static ProgressInfo create(int percent, String plainMessage, String goodDetail) { // if (goodDetail != null && goodDetail.length() > 0) // return new ProgressInfo(percent, plainMessage + " [" + goodDetail + "]"); // else // return new ProgressInfo(percent, plainMessage); // } // // public ProgressInfo(int percent, String htmlMessage) { // this.percent = percent; // this.htmlMessage = htmlMessage; // } // // @Override // public String toString() { // return "[percent=" + percent + ",htmlMessage=" + htmlMessage + "]"; // } // // public ProgressInfo(Bundle bundle) { // percent = bundle.getInt("percent"); // htmlMessage = bundle.getString("htmlMessage"); // } // // public void saveToBundle(Bundle bundle) { // bundle.putInt("percent", percent); // bundle.putString("htmlMessage", htmlMessage); // } // } // Path: app/src/main/java/org/pquery/service/PQServiceListener.java import org.pquery.webdriver.ProgressInfo; import java.io.File; package org.pquery.service; public interface PQServiceListener { public void onServiceOperationResult(String title, String message, int notificationId, File fileNameDownloaded); //public void onServicePQDownloaded(); // DownloadPQResult downloadPQResult); public void onServiceRetrievePQList(RetrievePQListResult pqListResult); //public void onServicePQCreated(CreatePQResult createPQResult);
public void onServiceProgressInfo(ProgressInfo progressInfo);
robneild/pocket-query-creator
app/src/main/java/org/pquery/webdriver/parser/PocketQueryPage.java
// Path: app/src/main/java/org/pquery/dao/DownloadablePQ.java // public class DownloadablePQ implements Parcelable, Serializable, PQListItem { // // private static final long serialVersionUID = -6540850109992510771L; // public String name; // public String size; // public String age; // public String waypoints; // public String url; // // public DownloadablePQ(Parcel in) { // name = in.readString(); // size = in.readString(); // age = in.readString(); // waypoints = in.readString(); // url = in.readString(); // } // // public DownloadablePQ() { // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(name); // dest.writeString(size); // dest.writeString(age); // dest.writeString(waypoints); // dest.writeString(url); // } // // /** // * Implementing the Parcelable interface must also have a static field called CREATOR, which is an object // * implementing the Parcelable.Creator interface. // */ // public static final Parcelable.Creator<DownloadablePQ> CREATOR = new Parcelable.Creator<DownloadablePQ>() { // public DownloadablePQ createFromParcel(Parcel in) { // return new DownloadablePQ(in); // } // // public DownloadablePQ[] newArray(int size) { // return new DownloadablePQ[size]; // } // }; // // @Override // public String getName() { // return name; // } // // } // // Path: app/src/main/java/org/pquery/dao/RepeatablePQ.java // public class RepeatablePQ implements Parcelable, Serializable, PQListItem { // // private static final long serialVersionUID = -6540850109992510771L; // public String name; // public String waypoints; // private HashMap<Integer, Schedule> schedules = new HashMap<Integer, Schedule>(); // // public RepeatablePQ(Parcel in) { // name = in.readString(); // waypoints = in.readString(); // schedules = in.readHashMap(ClassLoader.getSystemClassLoader()); // } // // public RepeatablePQ() { // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(name); // dest.writeString(waypoints); // dest.writeMap(schedules); // // } // // /** // * Implementing the Parcelable interface must also have a static field called CREATOR, which is an object // * implementing the Parcelable.Creator interface. // */ // public static final Creator<RepeatablePQ> CREATOR = new Creator<RepeatablePQ>() { // public RepeatablePQ createFromParcel(Parcel in) { // return new RepeatablePQ(in); // } // // public RepeatablePQ[] newArray(int size) { // return new RepeatablePQ[size]; // } // }; // // @Override // public String getName() { // return name; // } // // public List<Integer> getCheckedWeekdays() { // List<Integer> checkedWeekdays = new ArrayList<Integer>(); // for (Schedule schedule : schedules.values()) { // if (schedule.isEnabled()) { // checkedWeekdays.add(schedule.getDay()); // } // } // return checkedWeekdays; // } // // public void addScheduleURL(String url) { // UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(); // sanitizer.setAllowUnregisteredParamaters(true); // sanitizer.parseUrl(url); // String day = sanitizer.getValue("d"); // String opt = sanitizer.getValue("opt"); // Schedule schedule = new Schedule(url, Integer.valueOf(day), "0".equals(opt)); // schedules.put(schedule.getDay(), schedule); // } // // public Map<Integer, Schedule> getSchedules() { // return schedules; // } // // public String getCheckedWeekdaysAsText(String[] weekdayNames) { // String weekdaysString = null; // for (Integer dayNumber : getCheckedWeekdays()) { // String dayName = weekdayNames[dayNumber]; // if (weekdaysString == null) { // weekdaysString = dayName; // } else { // weekdaysString += ", " + dayName; // } // } // if (weekdaysString == null) { // weekdaysString = "-"; // } // return weekdaysString; // } // }
import net.htmlparser.jericho.Attribute; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.HTMLElementName; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.StartTag; import org.pquery.dao.DownloadablePQ; import org.pquery.dao.RepeatablePQ; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
package org.pquery.webdriver.parser; public class PocketQueryPage { private Source parsedHtml; public PocketQueryPage(Source parsedHtml) { this.parsedHtml = parsedHtml; } /** * <thead><tr> * <tr id="ctl00_ContentBody_PQDownloadList_uxDownloadPQList_ctl01_trPQDownloadRow"> * <tr class="TableFooter"> * * @return * @throws ParseException */
// Path: app/src/main/java/org/pquery/dao/DownloadablePQ.java // public class DownloadablePQ implements Parcelable, Serializable, PQListItem { // // private static final long serialVersionUID = -6540850109992510771L; // public String name; // public String size; // public String age; // public String waypoints; // public String url; // // public DownloadablePQ(Parcel in) { // name = in.readString(); // size = in.readString(); // age = in.readString(); // waypoints = in.readString(); // url = in.readString(); // } // // public DownloadablePQ() { // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(name); // dest.writeString(size); // dest.writeString(age); // dest.writeString(waypoints); // dest.writeString(url); // } // // /** // * Implementing the Parcelable interface must also have a static field called CREATOR, which is an object // * implementing the Parcelable.Creator interface. // */ // public static final Parcelable.Creator<DownloadablePQ> CREATOR = new Parcelable.Creator<DownloadablePQ>() { // public DownloadablePQ createFromParcel(Parcel in) { // return new DownloadablePQ(in); // } // // public DownloadablePQ[] newArray(int size) { // return new DownloadablePQ[size]; // } // }; // // @Override // public String getName() { // return name; // } // // } // // Path: app/src/main/java/org/pquery/dao/RepeatablePQ.java // public class RepeatablePQ implements Parcelable, Serializable, PQListItem { // // private static final long serialVersionUID = -6540850109992510771L; // public String name; // public String waypoints; // private HashMap<Integer, Schedule> schedules = new HashMap<Integer, Schedule>(); // // public RepeatablePQ(Parcel in) { // name = in.readString(); // waypoints = in.readString(); // schedules = in.readHashMap(ClassLoader.getSystemClassLoader()); // } // // public RepeatablePQ() { // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(name); // dest.writeString(waypoints); // dest.writeMap(schedules); // // } // // /** // * Implementing the Parcelable interface must also have a static field called CREATOR, which is an object // * implementing the Parcelable.Creator interface. // */ // public static final Creator<RepeatablePQ> CREATOR = new Creator<RepeatablePQ>() { // public RepeatablePQ createFromParcel(Parcel in) { // return new RepeatablePQ(in); // } // // public RepeatablePQ[] newArray(int size) { // return new RepeatablePQ[size]; // } // }; // // @Override // public String getName() { // return name; // } // // public List<Integer> getCheckedWeekdays() { // List<Integer> checkedWeekdays = new ArrayList<Integer>(); // for (Schedule schedule : schedules.values()) { // if (schedule.isEnabled()) { // checkedWeekdays.add(schedule.getDay()); // } // } // return checkedWeekdays; // } // // public void addScheduleURL(String url) { // UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(); // sanitizer.setAllowUnregisteredParamaters(true); // sanitizer.parseUrl(url); // String day = sanitizer.getValue("d"); // String opt = sanitizer.getValue("opt"); // Schedule schedule = new Schedule(url, Integer.valueOf(day), "0".equals(opt)); // schedules.put(schedule.getDay(), schedule); // } // // public Map<Integer, Schedule> getSchedules() { // return schedules; // } // // public String getCheckedWeekdaysAsText(String[] weekdayNames) { // String weekdaysString = null; // for (Integer dayNumber : getCheckedWeekdays()) { // String dayName = weekdayNames[dayNumber]; // if (weekdaysString == null) { // weekdaysString = dayName; // } else { // weekdaysString += ", " + dayName; // } // } // if (weekdaysString == null) { // weekdaysString = "-"; // } // return weekdaysString; // } // } // Path: app/src/main/java/org/pquery/webdriver/parser/PocketQueryPage.java import net.htmlparser.jericho.Attribute; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.HTMLElementName; import net.htmlparser.jericho.Segment; import net.htmlparser.jericho.Source; import net.htmlparser.jericho.StartTag; import org.pquery.dao.DownloadablePQ; import org.pquery.dao.RepeatablePQ; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; package org.pquery.webdriver.parser; public class PocketQueryPage { private Source parsedHtml; public PocketQueryPage(Source parsedHtml) { this.parsedHtml = parsedHtml; } /** * <thead><tr> * <tr id="ctl00_ContentBody_PQDownloadList_uxDownloadPQList_ctl01_trPQDownloadRow"> * <tr class="TableFooter"> * * @return * @throws ParseException */
public DownloadablePQ[] getReadyForDownload() throws ParseException {
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/ContainerTypeList.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList;
package org.pquery.filter; public class ContainerTypeList implements Iterable<ContainerType> { private LinkedList<ContainerType> inner = new LinkedList<ContainerType>(); public ContainerTypeList() { } public ContainerTypeList(String s) {
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/ContainerTypeList.java import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList; package org.pquery.filter; public class ContainerTypeList implements Iterable<ContainerType> { private LinkedList<ContainerType> inner = new LinkedList<ContainerType>(); public ContainerTypeList() { } public ContainerTypeList(String s) {
Assert.assertNotNull(s);
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/ContainerTypeList.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList;
public ContainerTypeList(boolean[] selection) { Assert.assertEquals(ContainerType.values().length, selection.length); for (int i = 0; i < selection.length; i++) { if (selection[i]) { inner.add(ContainerType.values()[i]); } } if (ContainerType.values().length == inner.size()) inner.clear(); } public String toString() { String ret = ""; for (ContainerType cache : inner) { ret += cache.toString() + ","; } return ret; } /** * Get a nice, comma seperated, localized, HTML display string representation of enum */ public String toLocalisedString(Resources res) { if (isAll())
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // // Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/ContainerTypeList.java import android.content.res.Resources; import com.google.android.gms.common.internal.Asserts; import org.pquery.R; import org.pquery.util.Assert; import org.pquery.util.MyColors; import java.util.Iterator; import java.util.LinkedList; public ContainerTypeList(boolean[] selection) { Assert.assertEquals(ContainerType.values().length, selection.length); for (int i = 0; i < selection.length; i++) { if (selection[i]) { inner.add(ContainerType.values()[i]); } } if (ContainerType.values().length == inner.size()) inner.clear(); } public String toString() { String ret = ""; for (ContainerType cache : inner) { ret += cache.toString() + ","; } return ret; } /** * Get a nice, comma seperated, localized, HTML display string representation of enum */ public String toLocalisedString(Resources res) { if (isAll())
return "<font color='" + MyColors.LIME + "'>" + res.getString(R.string.any) + "</font>";
robneild/pocket-query-creator
app/src/androidTest/java/org/pquery/webdriver/parser/SuccessMessageParserTest.java
// Path: app/src/main/java/org/pquery/webdriver/FailurePermanentException.java // public class FailurePermanentException extends Exception { // // private static final long serialVersionUID = 7687740322490670417L; // // public String error; // public String details; // // public FailurePermanentException(String error) { // super(error); // this.error = error; // } // // public FailurePermanentException(String error, String details) { // super(error); // this.error = error; // this.details = details; // } // // public FailurePermanentException(String error, Exception details) { // super(error, details); // this.error = error; // this.details = details.getMessage(); // } // // @Override // public String toString() { // String ret = error; // if (details != null) // ret += " [" + details + "]"; // return ret; // } // // public String toHTML() { // String ret = error; // if (details != null) // ret += "<font color=red><small><br>[" + details + "]</small></font>"; // return ret; // } // // }
import android.test.AndroidTestCase; import org.pquery.webdriver.FailurePermanentException;
package org.pquery.webdriver.parser; public class SuccessMessageParserTest extends AndroidTestCase { private static final String GOOD = "<p class=\"Success\">Thanks! Your pocket query has been saved and currently results in 10 caches. You can <a href=\"http://www.geocaching.com/seek/nearest.aspx?pq=dd2e3f12-2c04-4090-bd1b-4e601f521fe5\" title=\"Preview the Search\">preview the search</a> on the nearest cache page.</p>"; /** * Extract download link from good English html * * @throws FailurePermanentException */
// Path: app/src/main/java/org/pquery/webdriver/FailurePermanentException.java // public class FailurePermanentException extends Exception { // // private static final long serialVersionUID = 7687740322490670417L; // // public String error; // public String details; // // public FailurePermanentException(String error) { // super(error); // this.error = error; // } // // public FailurePermanentException(String error, String details) { // super(error); // this.error = error; // this.details = details; // } // // public FailurePermanentException(String error, Exception details) { // super(error, details); // this.error = error; // this.details = details.getMessage(); // } // // @Override // public String toString() { // String ret = error; // if (details != null) // ret += " [" + details + "]"; // return ret; // } // // public String toHTML() { // String ret = error; // if (details != null) // ret += "<font color=red><small><br>[" + details + "]</small></font>"; // return ret; // } // // } // Path: app/src/androidTest/java/org/pquery/webdriver/parser/SuccessMessageParserTest.java import android.test.AndroidTestCase; import org.pquery.webdriver.FailurePermanentException; package org.pquery.webdriver.parser; public class SuccessMessageParserTest extends AndroidTestCase { private static final String GOOD = "<p class=\"Success\">Thanks! Your pocket query has been saved and currently results in 10 caches. You can <a href=\"http://www.geocaching.com/seek/nearest.aspx?pq=dd2e3f12-2c04-4090-bd1b-4e601f521fe5\" title=\"Preview the Search\">preview the search</a> on the nearest cache page.</p>"; /** * Extract download link from good English html * * @throws FailurePermanentException */
public void testExtractDownloadLink() throws FailurePermanentException {
robneild/pocket-query-creator
app/src/main/java/org/pquery/filter/CountryList.java
// Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // }
import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import org.pquery.R; import org.pquery.util.MyColors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet;
// s.length() picks up the ALL countries case if (s.length() == 0 || countyCodes.contains(allCountryCodes[i])) { //Drawable flagDrawable = cxt.getResources().getDrawable(allCountryFlags.getResourceId(i, -1)); inner.add(new Country(allCountryNames[i], allCountryCodes[i], allCountryFlags.getResourceId(i, -1))); } } Collections.sort(inner); } /** * Encode the country list into a comma separated country code string * If ALL countries are selected then 'null' is returned * * @return encoded string or null */ public String toString() { if (isAll()) return null; // all countries String ret = ""; for (Country country : inner) { ret += country.getCode() + ","; } return ret; } public String toLocalisedString(Resources res) { if (isAll())
// Path: app/src/main/java/org/pquery/util/MyColors.java // public class MyColors { // public static String LIME = "#00FF00"; // public static String MEGENTA = "#FF00FF"; // } // Path: app/src/main/java/org/pquery/filter/CountryList.java import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import org.pquery.R; import org.pquery.util.MyColors; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; // s.length() picks up the ALL countries case if (s.length() == 0 || countyCodes.contains(allCountryCodes[i])) { //Drawable flagDrawable = cxt.getResources().getDrawable(allCountryFlags.getResourceId(i, -1)); inner.add(new Country(allCountryNames[i], allCountryCodes[i], allCountryFlags.getResourceId(i, -1))); } } Collections.sort(inner); } /** * Encode the country list into a comma separated country code string * If ALL countries are selected then 'null' is returned * * @return encoded string or null */ public String toString() { if (isAll()) return null; // all countries String ret = ""; for (Country country : inner) { ret += country.getCode() + ","; } return ret; } public String toLocalisedString(Resources res) { if (isAll())
return "<font color='" + MyColors.LIME + "'>" + res.getString(R.string.any) + "</font>";
robneild/pocket-query-creator
app/src/main/java/org/pquery/webdriver/RetriableTask.java
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // }
import android.content.res.Resources; import org.pquery.R; import org.pquery.util.Assert;
package org.pquery.webdriver; public abstract class RetriableTask<T> { protected Resources res; private int numberOfTriesLeft; // number left private int lastPercent; private ProgressListener progressListener; protected CancelledListener cancelledListener; private int fromPercent; private int toPercent; public RetriableTask(int numberOfRetries, int fromPercent, int toPercent, ProgressListener progressListener, CancelledListener cancelledListener, Resources res) {
// Path: app/src/main/java/org/pquery/util/Assert.java // public class Assert { // // public static void assertNotNull(Object a) { // if (a == null) { // throw new IllegalArgumentException("null reference"); // } // } // // public static void assertEquals(int a, int b) { // if (a != b) { // throw new IllegalArgumentException("not equal"); // } // } // // public static void fail() { // throw new IllegalArgumentException("fail"); // } // // public static void assertTrue(boolean a) { // if (!a) { // throw new IllegalArgumentException("not true"); // } // } // // public static void assertFalse(boolean a) { // if (a) { // throw new IllegalArgumentException("true"); // } // } // // public static void assertNull(Object a) { // if (a != null) { // throw new IllegalArgumentException("not null"); // } // } // } // Path: app/src/main/java/org/pquery/webdriver/RetriableTask.java import android.content.res.Resources; import org.pquery.R; import org.pquery.util.Assert; package org.pquery.webdriver; public abstract class RetriableTask<T> { protected Resources res; private int numberOfTriesLeft; // number left private int lastPercent; private ProgressListener progressListener; protected CancelledListener cancelledListener; private int fromPercent; private int toPercent; public RetriableTask(int numberOfRetries, int fromPercent, int toPercent, ProgressListener progressListener, CancelledListener cancelledListener, Resources res) {
Assert.assertNotNull(progressListener);
robneild/pocket-query-creator
app/src/main/java/org/pquery/webdriver/parser/SuccessMessageParser.java
// Path: app/src/main/java/org/pquery/webdriver/FailurePermanentException.java // public class FailurePermanentException extends Exception { // // private static final long serialVersionUID = 7687740322490670417L; // // public String error; // public String details; // // public FailurePermanentException(String error) { // super(error); // this.error = error; // } // // public FailurePermanentException(String error, String details) { // super(error); // this.error = error; // this.details = details; // } // // public FailurePermanentException(String error, Exception details) { // super(error, details); // this.error = error; // this.details = details.getMessage(); // } // // @Override // public String toString() { // String ret = error; // if (details != null) // ret += " [" + details + "]"; // return ret; // } // // public String toHTML() { // String ret = error; // if (details != null) // ret += "<font color=red><small><br>[" + details + "]</small></font>"; // return ret; // } // // }
import android.content.res.Resources; import org.pquery.R; import org.pquery.webdriver.FailurePermanentException; import java.util.regex.Matcher; import java.util.regex.Pattern;
package org.pquery.webdriver.parser; /** * Parser the message we get back after pq creation. It appears at top of * creation page in reponse to the creation POST * <p/> * There are some examples in different languages * <p/> * <p class="Success"> * Thanks! Your pocket query has been saved and currently results in 10 caches. * You can <a href= * "http://www.geocaching.com/seek/nearest.aspx?pq=dd2e3f12-2c04-4090-bd1b-4e601f521fe5" * title="Preview the Search">preview the search</a> on the nearest cache page. * <p/> * <p class="Success"> * Merci ! Votre pocket query a �t� modifi� et comprend pr�sentement 10 caches. * Vous pouvez <a href= * "http://www.geocaching.com/seek/nearest.aspx?pq=692a0d6f-1494-4ba6-9ac9-5877aff7e6b4" * title="Pr�visualiser la recherche">pr�visualiser la recherche</a> sur la page * de caches la plus pr�s. * </p> */ public class SuccessMessageParser { private String successMessage; private Resources res; /** * Try to parse out success message from passed in html * <p/> * Extracts out everything between <p class="Success"> and </p> */
// Path: app/src/main/java/org/pquery/webdriver/FailurePermanentException.java // public class FailurePermanentException extends Exception { // // private static final long serialVersionUID = 7687740322490670417L; // // public String error; // public String details; // // public FailurePermanentException(String error) { // super(error); // this.error = error; // } // // public FailurePermanentException(String error, String details) { // super(error); // this.error = error; // this.details = details; // } // // public FailurePermanentException(String error, Exception details) { // super(error, details); // this.error = error; // this.details = details.getMessage(); // } // // @Override // public String toString() { // String ret = error; // if (details != null) // ret += " [" + details + "]"; // return ret; // } // // public String toHTML() { // String ret = error; // if (details != null) // ret += "<font color=red><small><br>[" + details + "]</small></font>"; // return ret; // } // // } // Path: app/src/main/java/org/pquery/webdriver/parser/SuccessMessageParser.java import android.content.res.Resources; import org.pquery.R; import org.pquery.webdriver.FailurePermanentException; import java.util.regex.Matcher; import java.util.regex.Pattern; package org.pquery.webdriver.parser; /** * Parser the message we get back after pq creation. It appears at top of * creation page in reponse to the creation POST * <p/> * There are some examples in different languages * <p/> * <p class="Success"> * Thanks! Your pocket query has been saved and currently results in 10 caches. * You can <a href= * "http://www.geocaching.com/seek/nearest.aspx?pq=dd2e3f12-2c04-4090-bd1b-4e601f521fe5" * title="Preview the Search">preview the search</a> on the nearest cache page. * <p/> * <p class="Success"> * Merci ! Votre pocket query a �t� modifi� et comprend pr�sentement 10 caches. * Vous pouvez <a href= * "http://www.geocaching.com/seek/nearest.aspx?pq=692a0d6f-1494-4ba6-9ac9-5877aff7e6b4" * title="Pr�visualiser la recherche">pr�visualiser la recherche</a> sur la page * de caches la plus pr�s. * </p> */ public class SuccessMessageParser { private String successMessage; private Resources res; /** * Try to parse out success message from passed in html * <p/> * Extracts out everything between <p class="Success"> and </p> */
public SuccessMessageParser(String html, Resources res) throws FailurePermanentException {
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // }
import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude;
* @param url the base url (scheme,host,port). see * {@link #setBaseUrl(String)} */ public GisgraphyGeocoder(Context context, String url) { this.locale = Locale.getDefault(); addressBuilder = new AndroidAddressBuilder(locale); setBaseUrl(url); } /** * Returns a list of Addresses that are known to describe the area * immediately surrounding the given latitude and longitude. * <p/> * The returned values may be obtained by means of a network lookup. The * results are a best guess and are not guaranteed to be meaningful or * correct. It may be useful to call this method from a thread separate from * your primary UI thread. * * @param latitude the latitude a point for the search * @param longitude the longitude a point for the search * @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults);
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude; * @param url the base url (scheme,host,port). see * {@link #setBaseUrl(String)} */ public GisgraphyGeocoder(Context context, String url) { this.locale = Locale.getDefault(); addressBuilder = new AndroidAddressBuilder(locale); setBaseUrl(url); } /** * Returns a list of Addresses that are known to describe the area * immediately surrounding the given latitude and longitude. * <p/> * The returned values may be obtained by means of a network lookup. The * results are a best guess and are not guaranteed to be meaningful or * correct. It may be useful to call this method from a thread separate from * your primary UI thread. * * @param latitude the latitude a point for the search * @param longitude the longitude a point for the search * @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults);
if (!checkLatitude(latitude) || !checkLongitude(longitude)) {
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // }
import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude;
* @param url the base url (scheme,host,port). see * {@link #setBaseUrl(String)} */ public GisgraphyGeocoder(Context context, String url) { this.locale = Locale.getDefault(); addressBuilder = new AndroidAddressBuilder(locale); setBaseUrl(url); } /** * Returns a list of Addresses that are known to describe the area * immediately surrounding the given latitude and longitude. * <p/> * The returned values may be obtained by means of a network lookup. The * results are a best guess and are not guaranteed to be meaningful or * correct. It may be useful to call this method from a thread separate from * your primary UI thread. * * @param latitude the latitude a point for the search * @param longitude the longitude a point for the search * @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults);
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude; * @param url the base url (scheme,host,port). see * {@link #setBaseUrl(String)} */ public GisgraphyGeocoder(Context context, String url) { this.locale = Locale.getDefault(); addressBuilder = new AndroidAddressBuilder(locale); setBaseUrl(url); } /** * Returns a list of Addresses that are known to describe the area * immediately surrounding the given latitude and longitude. * <p/> * The returned values may be obtained by means of a network lookup. The * results are a best guess and are not guaranteed to be meaningful or * correct. It may be useful to call this method from a thread separate from * your primary UI thread. * * @param latitude the latitude a point for the search * @param longitude the longitude a point for the search * @param maxResults max number of addresses to return. Smaller numbers (1 to 5) * are recommended * @return a list of Address objects. Returns empty list if no matches were * found or there is no backend service available. * @throws IllegalArgumentException if latitude is less than -90 or greater than 90 * @throws IllegalArgumentException if longitude is less than -180 or greater than 180 * @throws IOException if the network is unavailable or any other I/O problem occurs */ public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException { log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults);
if (!checkLatitude(latitude) || !checkLongitude(longitude)) {
robneild/pocket-query-creator
app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // }
import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude;
log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults); if (!checkLatitude(latitude) || !checkLongitude(longitude)) { throw new IllegalArgumentException( "lattitude should be > -90 and < 90 and longitude should be >-180 and < 180"); } if (maxResults < 0) { throw new IllegalArgumentException("maxResults should be positive"); } if (maxResults == 0) { // shortcut filtering return new ArrayList<Address>(); } List<Address> androidAddresses = new ArrayList<Address>(); try { RestClient webService = createRestClient(); // Pass the parameters if needed , if not then pass dummy one as // follows Map<String, String> params = new HashMap<String, String>(); log_d("lat=" + latitude + ", long=" + longitude); // params.put(COUNTRY_PARAMETER_NAME, iso2countryCode); params.put(LATITUDE_PARAMETER_NAME, latitude + ""); params.put(LONGITUDE_PARAMETER_NAME, longitude + ""); params.put("radius", 500 + ""); params.put(FORMAT_PARAMETER_NAME, DEFAULT_FORMAT); params.put("from", "1"); params.put("to", "1"); if (apiKey != null) { params.put(APIKEY_PARAMETER_NAME, apiKey + ""); }
// Path: app/src/main/java/com/gisgraphy/domain/valueobject/StreetSearchResultsDto.java // public class StreetSearchResultsDto { // // /** // * {"numFound":50,"QTime":252,"result":[{"name":"Newton Street","distance":36.3294330748716,"gid":106603218,"openstreetmapId":16978709,"streetType":"RESIDENTIAL","oneWay":false,"countryCode":"US","length":601.901637459321,"lat":39.83543539626998,"lng":-105.03742540092145,"isIn":"Westminster"}, // */ // // public int numFound; // public Street[] result; // // // public Street[] getResult() { // return result; // } // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLatitude(double latitude) { // if (latitude < -90 || latitude > 90) { // throw new IllegalArgumentException("latitude is out of bound"); // } // return true; // } // // Path: app/src/main/java/com/gisgraphy/gishraphoid/JTSHelper.java // public static boolean checkLongitude(double longitude) { // if (longitude < -180 || longitude > 180) { // throw new IllegalArgumentException("longitude is out of bound"); // } // return true; // } // Path: app/src/main/java/com/gisgraphy/gishraphoid/GisgraphyGeocoder.java import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.util.Log; import com.gisgraphy.domain.valueobject.StreetSearchResultsDto; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.gisgraphy.gishraphoid.JTSHelper.checkLatitude; import static com.gisgraphy.gishraphoid.JTSHelper.checkLongitude; log_d("getFromLocation: lat=" + latitude + ",longitude=" + longitude + ",maxResults=" + maxResults); if (!checkLatitude(latitude) || !checkLongitude(longitude)) { throw new IllegalArgumentException( "lattitude should be > -90 and < 90 and longitude should be >-180 and < 180"); } if (maxResults < 0) { throw new IllegalArgumentException("maxResults should be positive"); } if (maxResults == 0) { // shortcut filtering return new ArrayList<Address>(); } List<Address> androidAddresses = new ArrayList<Address>(); try { RestClient webService = createRestClient(); // Pass the parameters if needed , if not then pass dummy one as // follows Map<String, String> params = new HashMap<String, String>(); log_d("lat=" + latitude + ", long=" + longitude); // params.put(COUNTRY_PARAMETER_NAME, iso2countryCode); params.put(LATITUDE_PARAMETER_NAME, latitude + ""); params.put(LONGITUDE_PARAMETER_NAME, longitude + ""); params.put("radius", 500 + ""); params.put(FORMAT_PARAMETER_NAME, DEFAULT_FORMAT); params.put("from", "1"); params.put("to", "1"); if (apiKey != null) { params.put(APIKEY_PARAMETER_NAME, apiKey + ""); }
StreetSearchResultsDto response = webService.get(REVERSE_GEOCODING_URI, StreetSearchResultsDto.class,
robneild/pocket-query-creator
app/src/main/java/org/pquery/fragments/SchedulePQFragment.java
// Path: app/src/main/java/org/pquery/dao/Schedule.java // public class Schedule { // private final String href; // private final Integer day; // private final boolean enabled; // // public Schedule(String href, Integer day, boolean enabled) { // this.href = href; // this.day = day; // this.enabled = enabled; // } // // public String getHref() { // return href; // } // // public Integer getDay() { // return day; // } // // public boolean isEnabled() { // return enabled; // } // // }
import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import org.pquery.R; import org.pquery.dao.Schedule; import java.util.ArrayList; import java.util.List; import java.util.Map;
package org.pquery.fragments; /** * Dialog with a list of weekdays to change the scheduling of a PQ */ public class SchedulePQFragment extends DialogFragment { private List<String> mSelectedItems = new ArrayList<String>(); private boolean[] selectedWeekdays;
// Path: app/src/main/java/org/pquery/dao/Schedule.java // public class Schedule { // private final String href; // private final Integer day; // private final boolean enabled; // // public Schedule(String href, Integer day, boolean enabled) { // this.href = href; // this.day = day; // this.enabled = enabled; // } // // public String getHref() { // return href; // } // // public Integer getDay() { // return day; // } // // public boolean isEnabled() { // return enabled; // } // // } // Path: app/src/main/java/org/pquery/fragments/SchedulePQFragment.java import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import org.pquery.R; import org.pquery.dao.Schedule; import java.util.ArrayList; import java.util.List; import java.util.Map; package org.pquery.fragments; /** * Dialog with a list of weekdays to change the scheduling of a PQ */ public class SchedulePQFragment extends DialogFragment { private List<String> mSelectedItems = new ArrayList<String>(); private boolean[] selectedWeekdays;
private Map<Integer, Schedule> schedules;
robneild/pocket-query-creator
app/src/main/java/org/pquery/util/IOUtils.java
// Path: app/src/main/java/org/pquery/webdriver/CancelledListener.java // public interface CancelledListener { // void ifCancelledThrow() throws InterruptedException; // } // // Path: app/src/main/java/org/pquery/webdriver/HttpClientFactory.java // public class HttpClientFactory { // // // public static DefaultHttpClient createHttpClient() { // // // // // Set timeout // // // I have seen some random failures where the network access just seems to lock-up for over a minute // // // I can't reproduce it but hopefully this will make it error and allow user to manually retry // // final HttpParams httpParams = new BasicHttpParams(); // // HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // // HttpConnectionParams.setSoTimeout(httpParams, 10000); // // // // return new DefaultHttpClient(httpParams); // // } // // public static HttpURLConnection createURLConnection(URL url) throws IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // // // Set timeout // // I have seen some random failures where the network access just seems to lock-up // // ... for minutes // // I can't reproduce it but hopefully this will make it error out and allow user to manually // // retry // conn.setReadTimeout(20000); // 20 seconds // conn.setConnectTimeout(20000); // 20 seconds // // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("Host", "www.geocaching.com"); // // // Makes our job a bit easier trying to work out what is going on with login problems etc. // conn.setInstanceFollowRedirects(false); // // return conn; // } // }
import android.content.Context; import android.util.Pair; import org.pquery.webdriver.CancelledListener; import org.pquery.webdriver.HttpClientFactory; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream;
package org.pquery.util; public class IOUtils { private static final String SET_COOKIE = "Set-Cookie"; /** * Used to store response from downloading a file */ public static class FileDetails { public String filename; // sent to us from far end server in the HTTP headers response public byte[] contents; } private static final int ESTIMATED_COMPRESSION_RATIO = 5; private static final int ESTIMATED_CONTENT_SIZE = 48000; public interface Listener { void update(int bytesReadSoFar, int expectedLength, int percent); }
// Path: app/src/main/java/org/pquery/webdriver/CancelledListener.java // public interface CancelledListener { // void ifCancelledThrow() throws InterruptedException; // } // // Path: app/src/main/java/org/pquery/webdriver/HttpClientFactory.java // public class HttpClientFactory { // // // public static DefaultHttpClient createHttpClient() { // // // // // Set timeout // // // I have seen some random failures where the network access just seems to lock-up for over a minute // // // I can't reproduce it but hopefully this will make it error and allow user to manually retry // // final HttpParams httpParams = new BasicHttpParams(); // // HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // // HttpConnectionParams.setSoTimeout(httpParams, 10000); // // // // return new DefaultHttpClient(httpParams); // // } // // public static HttpURLConnection createURLConnection(URL url) throws IOException { // HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // // // Set timeout // // I have seen some random failures where the network access just seems to lock-up // // ... for minutes // // I can't reproduce it but hopefully this will make it error out and allow user to manually // // retry // conn.setReadTimeout(20000); // 20 seconds // conn.setConnectTimeout(20000); // 20 seconds // // conn.setRequestProperty("Accept-Encoding", "gzip"); // conn.setRequestProperty("Host", "www.geocaching.com"); // // // Makes our job a bit easier trying to work out what is going on with login problems etc. // conn.setInstanceFollowRedirects(false); // // return conn; // } // } // Path: app/src/main/java/org/pquery/util/IOUtils.java import android.content.Context; import android.util.Pair; import org.pquery.webdriver.CancelledListener; import org.pquery.webdriver.HttpClientFactory; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; package org.pquery.util; public class IOUtils { private static final String SET_COOKIE = "Set-Cookie"; /** * Used to store response from downloading a file */ public static class FileDetails { public String filename; // sent to us from far end server in the HTTP headers response public byte[] contents; } private static final int ESTIMATED_COMPRESSION_RATIO = 5; private static final int ESTIMATED_CONTENT_SIZE = 48000; public interface Listener { void update(int bytesReadSoFar, int expectedLength, int percent); }
public static byte[] toByteArray(InputStream input, CancelledListener cancelledListener, Listener listener, int expectedLength) throws IOException, InterruptedException {